hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
3194cb63a68f550de32d688de98f02308d2b7e07
3,076
go
Go
oddities.go
Bhaskers-Blu-Org1/mirbft
55f769ebb63460462401104209f9bfadf3e08713
[ "Apache-2.0" ]
null
null
null
oddities.go
Bhaskers-Blu-Org1/mirbft
55f769ebb63460462401104209f9bfadf3e08713
[ "Apache-2.0" ]
null
null
null
oddities.go
Bhaskers-Blu-Org1/mirbft
55f769ebb63460462401104209f9bfadf3e08713
[ "Apache-2.0" ]
1
2020-07-30T09:57:46.000Z
2020-07-30T09:57:46.000Z
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package mirbft import ( "fmt" pb "github.com/IBM/mirbft/mirbftpb" "go.uber.org/zap" ) const ( SeqNoLog = "SeqNo" ReqNoLog = "ReqNo" EpochLog = "Epoch" NodeIDLog = "NodeID" MsgTypeLog = "MsgType" ) func logBasics(source NodeID, msg *pb.Msg) []zap.Field { fields := []zap.Field{ zap.Uint64(NodeIDLog, uint64(source)), } switch innerMsg := msg.Type.(type) { case *pb.Msg_EpochChange: msg := innerMsg.EpochChange fields = append(fields, zap.String(MsgTypeLog, "epochchange"), zap.Uint64(EpochLog, msg.NewEpoch), ) case *pb.Msg_Preprepare: msg := innerMsg.Preprepare fields = append(fields, zap.String(MsgTypeLog, "preprepare"), zap.Uint64(SeqNoLog, msg.SeqNo), zap.Uint64(EpochLog, msg.Epoch), ) case *pb.Msg_Prepare: msg := innerMsg.Prepare fields = append(fields, zap.String(MsgTypeLog, "prepare"), zap.Uint64(SeqNoLog, msg.SeqNo), zap.Uint64(EpochLog, msg.Epoch), ) case *pb.Msg_Commit: msg := innerMsg.Commit fields = append(fields, zap.String(MsgTypeLog, "commit"), zap.Uint64(SeqNoLog, msg.SeqNo), zap.Uint64(EpochLog, msg.Epoch), ) case *pb.Msg_Checkpoint: msg := innerMsg.Checkpoint fields = append(fields, zap.String(MsgTypeLog, "checkpoint"), zap.Uint64(SeqNoLog, msg.SeqNo), ) case *pb.Msg_ForwardRequest: msg := innerMsg.ForwardRequest fields = append(fields, zap.String(MsgTypeLog, "forwardrequest"), zap.Uint64(ReqNoLog, msg.Request.ReqNo), zap.Binary(ReqNoLog, msg.Request.ClientId), ) default: fields = append(fields, zap.String(MsgTypeLog, fmt.Sprintf("%T", msg.Type)), ) } return fields } // oddities are events which are not necessarily damaging // or detrimental to the state machine, but which may represent // byzantine behavior, misconfiguration, or bugs. type oddities struct { logger Logger nodes map[NodeID]*oddity } type oddity struct { invalid uint64 alreadyProcessed uint64 // aboveWatermarks uint64 // belowWatermarks uint64 // wrongEpoch uint64 } func (o *oddities) getNode(nodeID NodeID) *oddity { if o.nodes == nil { o.nodes = map[NodeID]*oddity{} } od, ok := o.nodes[nodeID] if !ok { od = &oddity{} o.nodes[nodeID] = od } return od } func (o *oddities) alreadyProcessed(source NodeID, msg *pb.Msg) { o.logger.Debug("already processed message", logBasics(source, msg)...) o.getNode(source).alreadyProcessed++ } /* // TODO enable again when we add back these checks func (o *oddities) aboveWatermarks(source NodeID, msg *pb.Msg) { o.logger.Warn("received message above watermarks", logBasics(source, msg)...) o.getNode(source).aboveWatermarks++ } func (o *oddities) belowWatermarks(source NodeID, msg *pb.Msg) { o.logger.Warn("received message below watermarks", logBasics(source, msg)...) o.getNode(source).belowWatermarks++ } */ func (o *oddities) invalidMessage(source NodeID, msg *pb.Msg) { o.logger.Error("invalid message", logBasics(source, msg)...) o.getNode(source).invalid++ }
23.661538
78
0.697659
a18139b4ab010838c7410d7578f9689dbbaad790
684
ts
TypeScript
node_modules/echarts/types/src/util/ECEventProcessor.d.ts
SongYuQiu/SocialNetworkPortraitAnalysisSystem
e35baea7b88576f33290a5b547c30d9901c7733f
[ "MIT" ]
null
null
null
node_modules/echarts/types/src/util/ECEventProcessor.d.ts
SongYuQiu/SocialNetworkPortraitAnalysisSystem
e35baea7b88576f33290a5b547c30d9901c7733f
[ "MIT" ]
null
null
null
node_modules/echarts/types/src/util/ECEventProcessor.d.ts
SongYuQiu/SocialNetworkPortraitAnalysisSystem
e35baea7b88576f33290a5b547c30d9901c7733f
[ "MIT" ]
null
null
null
import { EventProcessor, EventQuery } from 'zrender/lib/core/Eventful'; import { ECEvent, NormalizedEventQuery } from './types'; import ComponentModel from '../model/Component'; import ComponentView from '../view/Component'; import ChartView from '../view/Chart'; import Element from 'zrender/lib/Element'; export declare class ECEventProcessor implements EventProcessor { eventInfo: { targetEl: Element; packedEvent: ECEvent; model: ComponentModel; view: ComponentView | ChartView; }; normalizeQuery(query: EventQuery): NormalizedEventQuery; filter(eventType: string, query: NormalizedEventQuery): boolean; afterTrigger(): void; }
38
71
0.726608
42a59cfcb57194f753fc1823dd2f6b80fde23a78
2,737
dart
Dart
lib/src/constants.dart
suraj-testing2/Elevator_Comics
3e350cb2f8cdbb30f368b6ab38f361d00f145ef8
[ "BSD-3-Clause" ]
9
2015-05-06T17:32:08.000Z
2020-03-15T04:32:19.000Z
lib/src/constants.dart
suraj-testing2/Elevator_Comics
3e350cb2f8cdbb30f368b6ab38f361d00f145ef8
[ "BSD-3-Clause" ]
null
null
null
lib/src/constants.dart
suraj-testing2/Elevator_Comics
3e350cb2f8cdbb30f368b6ab38f361d00f145ef8
[ "BSD-3-Clause" ]
12
2015-06-18T11:51:46.000Z
2021-12-30T12:20:16.000Z
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library episodes.src.constants; // Some string constants for windows.postMessage const String PREFIX = 'EPISODES'; const String MARK = 'mark'; const String MEASURE = 'measure'; const String CLEAR_MARK = 'clearMark'; const String CLEAR_ALL_MARKS = 'clearAllMarks'; const String CLEAR_EPISODE = 'clearEpisode'; const String CLEAR_ALL_EPISODES = 'clearAllEpisodes'; const String INIT = 'init'; const String DONE = 'done'; // Some predefined mark names const String FIRST_BYTE = 'firstbyte'; const String START_TIME = 'starttime'; const String BACK_END = 'backend'; const String FRONT_END = 'frontend'; const String ON_LOAD = 'onload'; const String TOTAL_TIME = 'totaltime'; const String PAGE_LOAD_TIME = 'pageloadtime'; // Marks and episodes from windows.performance.timing const String DOM_COMPLETE = '_domComplete'; const String DOM_INTERACTIVE = '_domInteractive'; const String DOM_LOADING = '_domLoading'; const String FETCH = '_fetch'; const String FETCH_START = '_fetchStart'; const String FETCH_END = '_fetchEnd'; const String NAVIGATION = '_navigation'; const String NAVIGATION_START = '_navigationStart'; const String NAVIGATION_END = '_navigationEnd'; const String SECURE_CONNECTION = '_secureConnection'; const String SECURE_CONNECTION_START = '_secureConnectionStart'; const String SECURE_CONNECTION_END = '_secureConnectionEnd'; const String CONNECT = '_connect'; const String CONNECT_START = '_connectStart'; const String CONNECT_END = '_connectEnd'; const String DOMAIN_LOOKUP = '_domainLookup'; const String DOMAIN_LOOKUP_START = '_domainLookupStart'; const String DOMAIN_LOOKUP_END = '_domainLookupEnd'; const String DOM_CONTENT_LOADED_EVENT = '_domContentLoadedEvent'; const String DOM_CONTENT_LOADED_EVENT_START = '_domContentLoadedEventStart'; const String DOM_CONTENT_LOADED_EVENT_END = '_domContentLoadedEventEnd'; const String LOAD_EVENT = '_loadEvent'; const String LOAD_EVENT_START = '_loadEventStart'; const String LOAD_EVENT_END = '_loadEventEnd'; const String REDIRECT = '_redirect'; const String REDIRECT_START = '_redirectStart'; const String REDIRECT_END = '_redirectEnd'; const String REQUEST = '_request'; const String REQUEST_START = '_requestStart'; const String REQUEST_END = '_requestEnd'; const String RESPONSE = '_response'; const String RESPONSE_START = '_responseStart'; const String RESPONSE_END = '_responseEnd'; const String UNLOAD_EVENT = '_unloadEvent'; const String UNLOAD_EVENT_START = '_unloadEventStart'; const String UNLOAD_EVENT_END = '_unloadEventEnd';
35.089744
77
0.791377
bdfa4f43f46d5e2c966c917062cb489103381b75
2,378
cs
C#
gpmr/MohawkCollege.EHR.HL7v3.MIF.MIF20/PipelineLoader/MifTransformer.cs
avjabalpur/ccd-generator
dee379232f9994f403693fd6954fb48092526be1
[ "Apache-2.0" ]
null
null
null
gpmr/MohawkCollege.EHR.HL7v3.MIF.MIF20/PipelineLoader/MifTransformer.cs
avjabalpur/ccd-generator
dee379232f9994f403693fd6954fb48092526be1
[ "Apache-2.0" ]
null
null
null
gpmr/MohawkCollege.EHR.HL7v3.MIF.MIF20/PipelineLoader/MifTransformer.cs
avjabalpur/ccd-generator
dee379232f9994f403693fd6954fb48092526be1
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Configuration; using System.Xml.XPath; using System.Xml.Xsl; using System.Diagnostics; using System.Reflection; namespace MohawkCollege.EHR.HL7v3.MIF.MIF20.PipelineLoader { /// <summary> /// MIF Transformer component is responsible for transforming MIF files between versions for the /// process. The PipelineComponent can load MIF 2.1.4 /// </summary> internal class MifTransformer { /// <summary> /// True if the transformer did perform a transform /// </summary> public bool DidTransform { get; internal set; } /// <summary> /// Get a file from the transformer /// </summary> internal Stream GetFile(string fileName) { // Get the transform directory string txDirectory = ConfigurationManager.AppSettings["MIF.TransformDir"].Replace("~", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); // Load the file and determine if we need a transform (native version) XPathDocument xpd = new XPathDocument(fileName); var verNode = xpd.CreateNavigator().SelectSingleNode("//*/@schemaVersion"); if (verNode == null) { Trace.WriteLine("Can't find schemaVersion for {0}", Path.GetFileName(fileName)); return null; } else if (verNode.Value.StartsWith("2.1.4")) return File.OpenRead(fileName); // Trasnform , does a transform dir exist? string xslFile = String.Format("{0}.{1}",Path.Combine(txDirectory, verNode.Value), "xslt"); if (File.Exists(xslFile)) { DidTransform = true; // Transform XslCompiledTransform xsl = new XslCompiledTransform(); xsl.Load(xslFile); MemoryStream output = new MemoryStream(); xsl.Transform(xpd, new XsltArgumentList(), output); output.Seek(0, SeekOrigin.Begin); return output; } else Trace.WriteLine(String.Format("Cannot locate suitable transform for MIF v{0}", verNode.Value), "error"); return null; } } }
36.584615
160
0.592094
79486508bea3ba894958ab76b6de745270cc997c
2,478
cpp
C++
gui/processes/AnisotropicDiffusionProcess.cpp
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
8
2016-03-23T08:12:33.000Z
2022-01-25T14:07:03.000Z
gui/processes/AnisotropicDiffusionProcess.cpp
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
null
null
null
gui/processes/AnisotropicDiffusionProcess.cpp
frooms/stira
60b419f3e478397a8ab43ce9315a259567d94a26
[ "MIT" ]
8
2015-06-29T12:00:06.000Z
2019-09-03T12:40:47.000Z
/*********************************************************************************** * Copyright (C) 2008 by Filip Rooms * * * * Terms and conditions for using this software in any form are provided in the * * file COPYING, which can be found in the root directory of this project. * * * * Contact data: [email protected] * * http://www.filiprooms.be/ * * * ***********************************************************************************/ #include "AnisotropicDiffusionProcess.h" #include "../dialogs/AnisotropicDiffusionDialog.h" #include "../../stira/imagedata/datastructures/Image.h" #include "../../stira/diffusion/diffusion/AnisotropicDiffusion.h" using namespace stira::diffusion; using namespace std; AnisotropicDiffusionProcess::AnisotropicDiffusionProcess( Image* pImage ) : Process( pImage ) { mProcessName = QString("Anisotropic Diffusion Result"); } //-------------------------------------------------------- AnisotropicDiffusionProcess::~AnisotropicDiffusionProcess() { } //-------------------------------------------------------- double AnisotropicDiffusionProcess::GetFlowParameter() { return mFlowParameter; } //--------------------------------------------------------; void AnisotropicDiffusionProcess::SetFlowParameter(double f) { mFlowParameter = f; } //--------------------------------------------------------; int AnisotropicDiffusionProcess::GetNrOfIterations() { return mNrIterations; } //--------------------------------------------------------; void AnisotropicDiffusionProcess::SetNrOfIterations(int i) { mNrIterations = i; } //-------------------------------------------------------- void AnisotropicDiffusionProcess::run() { cout << "Applying Diffusion Process directly with Image*" << endl << flush; AnisotropicDiffusion ad ( mpImage ); ad.SetMaxNumberOfIterations ( mNrIterations ); ad.SetFlowFactor ( mFlowParameter ); AddResult( ad.Run() ); // ownership of this image is transfered through GetImage() to ImageDataList } //--------------------------------------------------------
33.945205
103
0.44996
052703878c04599c95e1ba05bc8c68525e6a390b
190
rb
Ruby
calculator.rb
yasmine-hj/programming-univbasics-3-labs-with-tdd-online-web-prework
1b5f6e2e1e05f702f7fc69af10d6058eed446e6b
[ "RSA-MD" ]
null
null
null
calculator.rb
yasmine-hj/programming-univbasics-3-labs-with-tdd-online-web-prework
1b5f6e2e1e05f702f7fc69af10d6058eed446e6b
[ "RSA-MD" ]
null
null
null
calculator.rb
yasmine-hj/programming-univbasics-3-labs-with-tdd-online-web-prework
1b5f6e2e1e05f702f7fc69af10d6058eed446e6b
[ "RSA-MD" ]
null
null
null
first_number = 9 second_number = 11 sum = first_number ++ second_number difference = first_number - second_number product = first_number * second_number quotient = first_number/second_number
31.666667
41
0.821053
b8d8c6586d5692426edcdbaa538a592ae359d6c8
3,072
h
C
JunkMacros.h
toastering/JunkMacros
c4746cae2ae0b88120f890ca069632ffc6757e2e
[ "MIT" ]
1
2021-09-07T22:50:19.000Z
2021-09-07T22:50:19.000Z
JunkMacros.h
toastering/JunkMacros
c4746cae2ae0b88120f890ca069632ffc6757e2e
[ "MIT" ]
null
null
null
JunkMacros.h
toastering/JunkMacros
c4746cae2ae0b88120f890ca069632ffc6757e2e
[ "MIT" ]
null
null
null
/* ---------------------------------------------- JunkMacros.h Created July 2021 Author tostring#1337 ---------------------------------------------- */ #pragma once #include <Windows.h> consteval unsigned fshiftrandom() { unsigned short lfsr = __TIME__[7] * 2; unsigned bit; bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5)) & 1; return lfsr = (lfsr >> 1) | (bit << 15); } void junkcallme() {}; float junkcallme2() { return 3.402823466e+38F + 1; }; constexpr int compiledrand = fshiftrandom() % 100; constexpr int compiledrand2 = fshiftrandom() % 1337; constexpr int compiledrandMAX = fshiftrandom() % 2147483647; template <size_t N> struct NOPCOMPILE { template <size_t I> static void gen() { __asm nop if constexpr (I + 1 < N) NOPCOMPILE<N>::gen<I + 1>(); } }; template <size_t N> struct MOVCOMPILE { template <size_t I> static void gen() { constexpr int yes = fshiftrandom() % 1337; __asm { push ah mov ah, BYTE PTR yes pop ah } if constexpr (I + 1 < N) MOVCOMPILE<N>::gen<I + 1>(); } }; template <size_t N> struct WINDFUNCSCOMPILE { template <size_t I> static void gen() { rand(); FindWindowA((char*)(90 + fshiftrandom() % 30),NULL); GetCurrentProcessId(); GetCurrentProcess(); GetProcessHeap(); if constexpr (I + 1 < N) WINDFUNCSCOMPILE<N>::gen<I + 1>(); } }; template <size_t N> struct NULLSUBCOMPILE { template <size_t I> static void gen() { __asm call junkcallme if constexpr (I + 1 < N) NULLSUBCOMPILE<N>::gen<I + 1>(); } }; template <size_t N> struct IFCOMPILE { template <size_t I> static void gen() { __asm { cmp al, BYTE PTR compiledrand2 jl Less mov al, 1 call junkcallme2 jl Less call junkcallme mov al, BYTE PTR compiledrand2 dec al jmp Both Less : mov ah, BYTE PTR CHAR_MAX xor ah, al jmp Both Both : inc al xor al, BYTE PTR compiledrand } if constexpr (I + 1 < N) IFCOMPILE<N>::gen<I + 1>(); } }; template <size_t N> struct JMPCOMPILE { template <size_t I> static void gen() { __asm { jmp myes myes : } if constexpr (I + 1 < N) JMPCOMPILE<N>::gen<I + 1>(); } }; #define NOP_JUNK(am) NOPCOMPILE<((am == 0) ? (fshiftrandom() % 50 + 1) : am)>::gen<0>() #define MOV_JUNK(am) MOVCOMPILE<((am == 0) ? (fshiftrandom() % 50 + 1) : am)>::gen<0>() #define WIND_JUNK(am) WINDFUNCSCOMPILE<((am == 0) ? (fshiftrandom() % 20 + 1) : am)>::gen<0>() #define NULLSUB_JUNK(am) NULLSUBCOMPILE<((am == 0) ? (fshiftrandom() % 60 + 1) : am)>::gen<0>() #define IF_JUNK(am) IFCOMPILE<((am == 0) ? (fshiftrandom() % 15 + 1) : am)>::gen<0>() #define JMP_JUNK(am) JMPCOMPILE<((am == 0) ? (fshiftrandom() % 50 + 1) : am)>::gen<0>()
24.380952
95
0.522135
149b954d383217bb35ffece8c28a93338f6d2d30
325
ts
TypeScript
WM-client/src/app/phone.pipe.ts
Schlesener73/Capstone-Workshop-Management
d82043ceb9b0e59c32855d234e4acea366c1af8a
[ "MIT" ]
null
null
null
WM-client/src/app/phone.pipe.ts
Schlesener73/Capstone-Workshop-Management
d82043ceb9b0e59c32855d234e4acea366c1af8a
[ "MIT" ]
null
null
null
WM-client/src/app/phone.pipe.ts
Schlesener73/Capstone-Workshop-Management
d82043ceb9b0e59c32855d234e4acea366c1af8a
[ "MIT" ]
null
null
null
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'phone' }) export class PhonePipe implements PipeTransform { transform(input:string) : string { var phoneString; phoneString = "(" + input.substring(0,3) + ") " + input.substring(3,6) + "-" + input.substring(6,10); return phoneString; } }
21.666667
105
0.649231
1ab83da7c2062cf5cc475de448b40326bcf8b514
188
py
Python
desafio003.py
RickChaves29/Desafios-Python
9d67036ca2ba9c6db2a649a381cac832ac83035f
[ "MIT" ]
null
null
null
desafio003.py
RickChaves29/Desafios-Python
9d67036ca2ba9c6db2a649a381cac832ac83035f
[ "MIT" ]
null
null
null
desafio003.py
RickChaves29/Desafios-Python
9d67036ca2ba9c6db2a649a381cac832ac83035f
[ "MIT" ]
null
null
null
algo = input('Digite algo: ') print('Tipo do valor:', type(algo)) print('è um número ?:', algo.isnumeric()) print('é alfabeto', algo.isalpha()) print('é um alfanumerico ', algo.isalnum())
31.333333
43
0.670213
e2d4f5150148adba70684ded7c66f55db8b7f0f8
4,141
py
Python
example/Transformer_vision/imagenet/vit/distrib.py
ddddwee1/TorchSUL
775832049564d8ee7c43e510b57bd716e0a746dd
[ "WTFPL" ]
7
2019-12-14T12:23:36.000Z
2021-11-16T00:25:13.000Z
example/Transformer_vision/imagenet/vit/distrib.py
ddddwee1/TorchSUL
775832049564d8ee7c43e510b57bd716e0a746dd
[ "WTFPL" ]
1
2020-10-20T06:33:53.000Z
2020-10-26T19:01:21.000Z
example/Transformer_vision/imagenet/vit/distrib.py
ddddwee1/TorchSUL
775832049564d8ee7c43e510b57bd716e0a746dd
[ "WTFPL" ]
1
2021-08-24T09:09:36.000Z
2021-08-24T09:09:36.000Z
import torch import torch.distributed as dist import numpy as np import torch.multiprocessing as mp import os os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3' import vit from TorchSUL import Model as M import logging import datareader import losses import random import config def main(): world_size = torch.cuda.device_count() mp.spawn(main_worker, nprocs=world_size, args=(world_size,)) def main_worker(gpu, world_size): BSIZE = 16 FORMAT = '%(asctime)-15s Replica:%(name)s %(message)s' logging.basicConfig(format=FORMAT) logger = logging.getLogger('%d'%gpu) logger.setLevel(10) logger.info('Initialize process.') torch.cuda.set_device(gpu) dist.init_process_group(backend='nccl', init_method='tcp://localhost:23456', world_size=world_size, rank=gpu) net = vit.TransNet() dumb_x = torch.from_numpy(np.float32(np.zeros([2,3,config.inp_size,config.inp_size]))) with torch.no_grad(): net(dumb_x) saver = M.Saver(net) saver.restore('./model/') net.cuda(gpu) net = torch.nn.parallel.DistributedDataParallel(net, device_ids=[gpu]) net.train() logger.info('Model initialization finished.') loader, max_label, sampler = datareader.get_train_dataloader(BSIZE, distributed=True) classifier = losses.SplitClassifier(max_label, world_size, gpu, logger) # classifier = losses.TotalClassifier(max_label, gpu, logger) dumb_x = torch.from_numpy(np.float32(np.zeros([2,512]))) dumb_y = torch.from_numpy(np.int64(np.zeros(2))) with torch.no_grad(): classifier(dumb_x, dumb_y) losses.load_classifier(max_label, world_size, classifier, gpu, './classifier/', logger) classifier.cuda(gpu) # classifier = torch.nn.parallel.DistributedDataParallel(classifier, device_ids=[gpu]) # optim = torch.optim.SGD([{'params':net.parameters(), 'weight_decay':0.0005}, {'params':classifier.parameters(), 'weight_decay':0.0}], lr=0.0001, momentum=0.9) optim = torch.optim.AdamW([{'params':net.parameters(), 'weight_decay':0.0005}, {'params':classifier.parameters(), 'weight_decay':0.0}], lr=0.0001) for e in range(25): if e<3: m2 = 0.0 else: m2 = 0.5 sampler.set_epoch(e) logger.info('Epoch:%d'%e) if e%10==9 and e>0: newlr = lr * 0.1 for param_group in optim.param_groups: param_group['lr'] = newlr for i, (img, label) in enumerate(loader): label = label.cuda(gpu) labels = [torch.zeros_like(label) for _ in range(world_size)] dist.all_gather(labels, label) labels = torch.cat(labels, dim=0) # labels = label optim.zero_grad() feat = net(img) feat_list = [torch.zeros_like(feat) for _ in range(world_size)] dist.all_gather(feat_list, feat) feat_cat = torch.cat(feat_list, dim=0) feat_cat = feat_cat.requires_grad_() # logger.info('%s %s'%(feat_cat.shape, labels.shape)) loss, correct = classifier(feat_cat, labels, m2=m2) # loss, correct = classifier(feat, labels, m2=0.0) loss = loss.sum() # logger.info(f'{loss}') loss.backward() # logger.info('%s'%feat_cat.grad) dist.all_reduce(feat_cat.grad, dist.ReduceOp.SUM) grad_feat = feat_cat.grad[BSIZE*gpu : BSIZE*gpu+BSIZE] # logger.info('%s %s'%(feat.shape, grad_feat.shape)) feat.backward(gradient=grad_feat) # logger.info('%s'%net.module.c1.conv.weight.max()) optim.step() dist.all_reduce(loss) dist.all_reduce(correct) # logger.info(f'{loss} {feat_cat.shape}') # loss = loss / feat_cat.shape[0] # acc = correct / feat_cat.shape[0] loss = loss / BSIZE / world_size acc = correct / BSIZE / world_size lr = optim.param_groups[0]['lr'] if gpu==0 and i%20==0: logger.info('Epoch:%d Iter:%d/%d Loss:%.4f Acc:%.4f LR:%.1e'%(e, i,len(loader),loss, acc, lr)) stamp = random.randint(0, 1000000) if gpu==0: saver.save('./model/R50_%d_%d.pth'%(e, stamp)) losses.save_classifier(max_label, world_size, classifier, './classifier/%d_%d.pth'%(e,stamp), logger, do_save=gpu==0) if __name__=='__main__': FORMAT = '%(asctime)-15s Replica:%(name)s %(message)s' logging.basicConfig(format=FORMAT) # d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} # logger.warning('Protocol problem: %s', 'connection reset', extra=d) main()
35.698276
161
0.696209
cdd3fa6e35ef7b9a0cb96c904430930be2c2902f
3,751
cs
C#
src/Agent.Test/Metrics/UserSampledObject.cs
snakefoot/Loupe.Agent.Core
cdb974055760359217e9c6ed1504a6439c6d2734
[ "MIT" ]
6
2017-08-24T14:52:37.000Z
2022-01-10T14:47:18.000Z
src/Agent.Test/Metrics/UserSampledObject.cs
snakefoot/Loupe.Agent.Core
cdb974055760359217e9c6ed1504a6439c6d2734
[ "MIT" ]
39
2017-08-24T03:15:14.000Z
2022-02-10T20:02:51.000Z
src/Agent.Test/Metrics/UserSampledObject.cs
snakefoot/Loupe.Agent.Core
cdb974055760359217e9c6ed1504a6439c6d2734
[ "MIT" ]
6
2017-08-24T14:36:27.000Z
2020-11-05T22:39:24.000Z
using Gibraltar.Agent.Metrics; namespace Loupe.Agent.Test.Metrics { [SampledMetric("UserSampledObject", "Attributes.Unit Test Data")] public class UserSampledObject { private int m_PrimaryValue; private int m_SecondaryValue; private string m_InstanceName; public UserSampledObject() { m_PrimaryValue = 0; m_SecondaryValue = 1; m_InstanceName = "Dummy instance"; } public UserSampledObject(int primaryValue) { m_PrimaryValue = primaryValue; m_SecondaryValue = 1; m_InstanceName = "Dummy instance"; } public UserSampledObject(int primaryValue, int secondaryValue) { m_PrimaryValue = primaryValue; m_SecondaryValue = secondaryValue; m_InstanceName = "Dummy instance"; } public UserSampledObject(string instanceName) { m_PrimaryValue = 0; m_SecondaryValue = 1; m_InstanceName = instanceName; } public UserSampledObject(string instanceName, int primaryValue) { m_PrimaryValue = primaryValue; m_SecondaryValue = 1; m_InstanceName = instanceName; } public UserSampledObject(string instanceName, int primaryValue, int secondaryValue) { m_PrimaryValue = primaryValue; m_SecondaryValue = secondaryValue; m_InstanceName = instanceName; } public void SetValue(int primaryValue) { m_PrimaryValue = primaryValue; m_SecondaryValue = 1; } public void SetValue(int primaryValue, int secondaryValue) { m_PrimaryValue = primaryValue; m_SecondaryValue = secondaryValue; } public void SetInstanceName(string instanceName) { m_InstanceName = instanceName; } [SampledMetricValue("IncrementalCount", SamplingType.IncrementalCount, null, Description="Unit test sampled metric using the incremental count calculation routine")] [SampledMetricValue("IncrementalFraction", SamplingType.IncrementalFraction, null, Description = "Unit test sampled metric using the incremental fraction calculation routine. Rare, but fun.")] [SampledMetricValue("TotalCount", SamplingType.TotalCount, null, Description = "Unit test sampled metric using the Total Count calculation routine. Very common.")] [SampledMetricValue("TotalFraction", SamplingType.TotalFraction, null, Description = "Unit test sampled metric using the Total Fraction calculation routine. Rare, but rounds us out.")] [SampledMetricValue("RawCount", SamplingType.RawCount, null, Description = "Unit test sampled metric using the Raw Count calculation routine, which we will then average to create sample intervals.")] [SampledMetricValue("RawFraction", SamplingType.RawFraction, null, Description = "Unit test sampled metric using the Raw Fraction calculation routine. Fraction types aren't common.")] public int PrimaryValue { get { return m_PrimaryValue; } set { m_PrimaryValue = value; } } [SampledMetricDivisor("IncrementalFraction")] [SampledMetricDivisor("TotalFraction")] [SampledMetricDivisor("RawFraction")] public int SecondaryValue { get { return m_SecondaryValue; } set { m_SecondaryValue = value; } } [SampledMetricInstanceName] public string GetInstanceName() { return m_InstanceName; } } }
38.670103
161
0.632898
b77ce2e5d8a48c5d3c80b162ff0c92de63ce96f0
1,590
cpp
C++
src/UNIT_4RELAY.cpp
m5stack/UNIT_4RELAY
f7586379b2dfd079527a990f740f98ca97206820
[ "MIT" ]
null
null
null
src/UNIT_4RELAY.cpp
m5stack/UNIT_4RELAY
f7586379b2dfd079527a990f740f98ca97206820
[ "MIT" ]
null
null
null
src/UNIT_4RELAY.cpp
m5stack/UNIT_4RELAY
f7586379b2dfd079527a990f740f98ca97206820
[ "MIT" ]
1
2022-02-10T18:18:56.000Z
2022-02-10T18:18:56.000Z
#include "UNIT_4RELAY.h" void UNIT_4RELAY::write1Byte(uint8_t address, uint8_t Register_address, uint8_t data) { Wire.beginTransmission(address); Wire.write(Register_address); Wire.write(data); Wire.endTransmission(); } uint8_t UNIT_4RELAY::read1Byte(uint8_t address, uint8_t Register_address) { Wire.beginTransmission(address); // Initialize the Tx buffer Wire.write(Register_address); // Put slave register address in Tx buffer Wire.endTransmission(); Wire.requestFrom(address, 1); uint8_t data = Wire.read(); return data; } void UNIT_4RELAY::relayALL(bool state) { write1Byte(addr,relay_Reg,state*(0x0f)); } void UNIT_4RELAY::LED_ALL(bool state) { write1Byte(addr,relay_Reg,state*(0xf0)); } void UNIT_4RELAY::relayWrite( uint8_t number, bool state ) { uint8_t StateFromDevice = read1Byte(addr, relay_Reg); if( state == 0 ) { StateFromDevice &= ~( 0x01 << number ); } else { StateFromDevice |= ( 0x01 << number ); } write1Byte(addr,relay_Reg,StateFromDevice); } void UNIT_4RELAY::LEDWrite( uint8_t number, bool state ) { uint8_t StateFromDevice = read1Byte(addr, relay_Reg); if( state == 0 ) { StateFromDevice &= ~( 0x10 << number ); } else { StateFromDevice |= ( 0x10 << number ); } write1Byte(addr,0x11,StateFromDevice); } void UNIT_4RELAY::switchMode( bool mode ) { write1Byte(addr, 0x10 ,mode); } void UNIT_4RELAY::Init(bool mode) { write1Byte(addr,mode_Reg,mode); write1Byte(addr,relay_Reg,0); }
21.2
87
0.662264
9746f944ee81fb3741cd424976c9482cd8894b6d
3,059
go
Go
pkg/identity/numericidentity.go
peter-slovak/cilium
43dd7623c821a630e92236c02e318bae1a9b798f
[ "Apache-2.0" ]
1
2019-10-16T04:01:13.000Z
2019-10-16T04:01:13.000Z
pkg/identity/numericidentity.go
jukylin/cilium
cc7a4cb6881639caeae4b34512741e82e2b4c041
[ "Apache-2.0" ]
null
null
null
pkg/identity/numericidentity.go
jukylin/cilium
cc7a4cb6881639caeae4b34512741e82e2b4c041
[ "Apache-2.0" ]
null
null
null
// Copyright 2016-2018 Authors of Cilium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package identity import ( "strconv" "time" "github.com/cilium/cilium/pkg/labels" ) const ( secLabelTimeout = 120 * time.Second // MinimalNumericIdentity represents the minimal numeric identity not // used for reserved purposes. MinimalNumericIdentity = NumericIdentity(256) // InvalidIdentity is the identity assigned if the identity is invalid // or not determined yet InvalidIdentity = NumericIdentity(0) ) const ( // IdentityUnknown represents an unknown identity IdentityUnknown NumericIdentity = iota // ReservedIdentityHost represents the local host ReservedIdentityHost // ReservedIdentityWorld represents any endpoint outside of the cluster ReservedIdentityWorld // ReservedIdentityCluster represents any endpoint inside the cluster // that does not have a more specific identity ReservedIdentityCluster // ReservedIdentityHealth represents the local cilium-health endpoint ReservedIdentityHealth ) var ( ReservedIdentities = map[string]NumericIdentity{ labels.IDNameHost: ReservedIdentityHost, labels.IDNameWorld: ReservedIdentityWorld, labels.IDNameHealth: ReservedIdentityHealth, labels.IDNameCluster: ReservedIdentityCluster, } ReservedIdentityNames = map[NumericIdentity]string{ ReservedIdentityHost: labels.IDNameHost, ReservedIdentityWorld: labels.IDNameWorld, ReservedIdentityHealth: labels.IDNameHealth, ReservedIdentityCluster: labels.IDNameCluster, } ) // NumericIdentity is the numeric representation of a security identity / a // security policy. type NumericIdentity uint32 func ParseNumericIdentity(id string) (NumericIdentity, error) { nid, err := strconv.ParseUint(id, 0, 32) if err != nil { return NumericIdentity(0), err } return NumericIdentity(nid), nil } func (id NumericIdentity) StringID() string { return strconv.FormatUint(uint64(id), 10) } func (id NumericIdentity) String() string { if v, exists := ReservedIdentityNames[id]; exists { return v } return id.StringID() } // Uint32 normalizes the ID for use in BPF program. func (id NumericIdentity) Uint32() uint32 { return uint32(id) } func GetReservedID(name string) NumericIdentity { if v, ok := ReservedIdentities[name]; ok { return v } return IdentityUnknown } // IsReservedIdentity returns whether id is one of the special reserved identities. func (id NumericIdentity) IsReservedIdentity() bool { _, isReservedIdentity := ReservedIdentityNames[id] return isReservedIdentity }
27.809091
83
0.773128
67bcbaa82ce5a9d73ce19bbdb8f683564d190532
1,108
sql
SQL
03_ddl/003.tpcds.catalog_returns.sql
vmware-archive/TPC-DS
591d8a14a274718032aaacef0b09598d4a2ee41f
[ "Apache-2.0" ]
2
2018-01-18T06:00:47.000Z
2019-01-16T01:39:39.000Z
03_ddl/003.tpcds.catalog_returns.sql
vmware-archive/TPC-DS
591d8a14a274718032aaacef0b09598d4a2ee41f
[ "Apache-2.0" ]
null
null
null
03_ddl/003.tpcds.catalog_returns.sql
vmware-archive/TPC-DS
591d8a14a274718032aaacef0b09598d4a2ee41f
[ "Apache-2.0" ]
6
2016-10-05T16:54:36.000Z
2020-03-25T15:16:37.000Z
CREATE TABLE tpcds.catalog_returns ( cr_returned_date_sk integer, cr_returned_time_sk integer, cr_item_sk integer NOT NULL, cr_refunded_customer_sk integer, cr_refunded_cdemo_sk integer, cr_refunded_hdemo_sk integer, cr_refunded_addr_sk integer, cr_returning_customer_sk integer, cr_returning_cdemo_sk integer, cr_returning_hdemo_sk integer, cr_returning_addr_sk integer, cr_call_center_sk integer, cr_catalog_page_sk integer, cr_ship_mode_sk integer, cr_warehouse_sk integer, cr_reason_sk integer, cr_order_number bigint NOT NULL, cr_return_quantity integer, cr_return_amount numeric(7,2), cr_return_tax numeric(7,2), cr_return_amt_inc_tax numeric(7,2), cr_fee numeric(7,2), cr_return_ship_cost numeric(7,2), cr_refunded_cash numeric(7,2), cr_reversed_charge numeric(7,2), cr_store_credit numeric(7,2), cr_net_loss numeric(7,2) ) WITH (:MEDIUM_STORAGE) :DISTRIBUTED_BY partition by range(cr_returned_date_sk) (start(2450815) INCLUSIVE end(2453005) INCLUSIVE every (200), default partition others) ;
30.777778
61
0.766245
e237596a22c738363fe6e7959950ee928309e7b4
2,162
js
JavaScript
lib/classes/Socket.js
ya-kostik/rubik-http
aad1b0204f98cd68a829f67b351bb80bb828759d
[ "Apache-2.0" ]
null
null
null
lib/classes/Socket.js
ya-kostik/rubik-http
aad1b0204f98cd68a829f67b351bb80bb828759d
[ "Apache-2.0" ]
null
null
null
lib/classes/Socket.js
ya-kostik/rubik-http
aad1b0204f98cd68a829f67b351bb80bb828759d
[ "Apache-2.0" ]
null
null
null
const { Kubik, helpers } = require('rubik-main'); const io = require('socket.io'); /** * WebSocket HTTP kubik for Rubik * Use socket.io for process ws connections * @namespace Rubik.HTTP * @class Socket * @prop {Nubmber} serverIndex index of http.servers server, defaults — 0 * @prop {Object} options options for attach connections, can be changed across http.socket config * @param {Object} options default options */ class Socket extends Kubik { constructor(options = {}) { super(); this.name = 'http/socket'; this.dependencies = ['http']; this.serverIndex = 0; this.options = options || {}; this.io = io(); } /** * up socket kubik * @param {HTTP} http kubik */ up({ http }) { this.http = http; this.config = this.http.config && this.http.config.socket || {}; this.log = this.http.log; helpers.assignDeep(this.options, this.config); this.io.use((socket, next) => { socket.rubik = this.app; next(); }); this.applyHooks('before'); } /** * add listener to io * @param {String} name of listener * @param {Function} cb callback of listener * @return {Rubik.HTTP.Socket} this */ on(/* arguments */) { this.io.on(...arguments); return this; } /** * remove listener from io * @return {Rubik.HTTP.Socket} this */ off(event, cb) { // It is a strange changes in the socket.io // if (!cb) this.io.removeAllListeners(event); // else this.io.removeListener(event, cb); if (!cb) this.io.sockets.removeAllListeners(event); else this.io.sockets.removeListener(event, cb); return this; } /** * after all kubiks up hook */ after() { this.applyHooks('after'); const server = Array.from(this.http.servers)[this.serverIndex]; if (!server) { throw new TypeError( this.serverIndex + ' server of http is not defined. Up http first.' ); } this.io.attach(server, this.options); const addText = this.http.servers.size > 1 ? ' ' + (this.serverIndex + 1) : ''; this.log.info('Socket attached to the server' + addText + ' 🏓'); } } module.exports = Socket;
26.691358
103
0.614246
c43402ad7bbdea3df85f9ce6468261494faf0794
56,087
sql
SQL
src/test/sql-pl/Tests_LOG4DB2_CONF_LOGGERS_EFFECTIVE.sql
angoca/log4db2
c6e6a9ca6f94aad6eb892344eb5f51d9b0996e02
[ "BSD-2-Clause" ]
3
2016-08-19T12:04:10.000Z
2019-12-29T20:51:25.000Z
src/test/sql-pl/Tests_LOG4DB2_CONF_LOGGERS_EFFECTIVE.sql
angoca/log4db2
c6e6a9ca6f94aad6eb892344eb5f51d9b0996e02
[ "BSD-2-Clause" ]
18
2015-01-08T16:23:15.000Z
2020-07-07T21:06:04.000Z
src/test/sql-pl/Tests_LOG4DB2_CONF_LOGGERS_EFFECTIVE.sql
angoca/log4db2
c6e6a9ca6f94aad6eb892344eb5f51d9b0996e02
[ "BSD-2-Clause" ]
null
null
null
--#SET TERMINATOR @ /* Copyright (c) 2012 - 2014, Andres Gomez Casanova (AngocA) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Tests for the conf loggers effective table. * * Version: 2022-06-07 1-RC * Author: Andres Gomez Casanova (AngocA) * Made in COLOMBIA. */ SET CURRENT SCHEMA LOG4DB2_CONF_LOGGERS_EFFECTIVE @ SET PATH = LOG4DB2_CONF_LOGGERS_EFFECTIVE @ BEGIN DECLARE STATEMENT VARCHAR(128); DECLARE CONTINUE HANDLER FOR SQLSTATE '42710' BEGIN END; SET STATEMENT = 'CREATE SCHEMA LOG4DB2_CONF_LOGGERS_EFFECTIVE'; EXECUTE IMMEDIATE STATEMENT; END @ -- Install CREATE OR REPLACE FUNCTION GET_MAX_ID( ) RETURNS ANCHOR LOGDATA.CONF_LOGGERS.LOGGER_ID BEGIN DECLARE RET ANCHOR LOGDATA.CONF_LOGGERS.LOGGER_ID; SET RET = (SELECT MAX(LOGGER_ID) FROM LOGDATA.CONF_LOGGERS); RETURN RET; END @ CREATE OR REPLACE PROCEDURE DELETE_LAST_MESSAGE_FROM_TRIGGER() BEGIN DECLARE MAX_DATE ANCHOR LOGDATA.LOGS.DATE_UNIQ; SELECT MAX(DATE_UNIQ) INTO MAX_DATE FROM LOGDATA.LOGS; DELETE FROM LOGDATA.LOGS WHERE MESSAGE = 'A manual CONF_LOGGERS_EFFECTIVE update should be realized.' AND DATE_UNIQ = MAX_DATE; UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = 0 WHERE LOGGER_ID = 0; END @ -- Test fixtures CREATE OR REPLACE PROCEDURE ONE_TIME_SETUP() BEGIN CALL DB2UNIT.SET_AUTONOMOUS(FALSE); CALL LOGGER_1RC.LOGADMIN.RESET_TABLES(); CALL DELETE_LAST_MESSAGE_FROM_TRIGGER(); END @ CREATE OR REPLACE PROCEDURE SETUP() BEGIN DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; END @ CREATE OR REPLACE PROCEDURE TEAR_DOWN() BEGIN -- Empty END @ CREATE OR REPLACE PROCEDURE ONE_TIME_TEAR_DOWN() BEGIN DELETE FROM LOGDATA.CONFIGURATION; INSERT INTO LOGDATA.CONFIGURATION (KEY, VALUE) VALUES ('autonomousLogging', 'true'), ('defaultRootLevelId', '3'), ('internalCache', 'true'), ('logInternals', 'false'), ('secondsToRefresh', '30'); CALL DELETE_LAST_MESSAGE_FROM_TRIGGER(); END @ -- Test01: Inserts a normal logger. CREATE OR REPLACE PROCEDURE TEST_01() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T1', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test1', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test01a: Inserts a normal logger', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test01b: Inserts a normal logger', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test01c: Inserts a normal logger', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test02: Tries to insert a logger with a null id. CREATE OR REPLACE PROCEDURE TEST_02() BEGIN DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_407 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE '23502' SET RAISED_407 = TRUE; SET LEVEL = 2; SET HIERARCHY = '0' ; INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (NULL, LEVEL, HIERARCHY); CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test02: Tries to insert a logger with a ' || 'null id', RAISED_407); END @ -- Test03: Tries to insert a logger with a negative id. CREATE OR REPLACE PROCEDURE TEST_03() BEGIN DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_530 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE '23503' SET RAISED_530 = TRUE; SET LEVEL = 4; SET HIERARCHY = '0' ; INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (-5, LEVEL, HIERARCHY); CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test03: Tries to insert a logger with a ' || 'negative id', RAISED_530); END @ -- Test04: Tries to insert a logger with a inexistant id. CREATE OR REPLACE PROCEDURE TEST_04() BEGIN DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_530 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE '23503' SET RAISED_530 = TRUE; SET LEVEL = 5; SET HIERARCHY = '0,500' ; INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (500, LEVEL, HIERARCHY); CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test04: Tries to insert a logger with a ' || 'inexistant id', RAISED_530); END @ -- Test05: Tries to insert a logger with a null level. CREATE OR REPLACE PROCEDURE TEST_05() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T5', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test5', 0, EXPECTED_LEVEL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, NULL, EXPECTED_HIERARCHY); SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test05a: Tries to insert a logger with a null ' || 'level', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test05b: Tries to insert a logger with a null ' || 'level', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test05c: Tries to insert a logger with a ' || 'null level', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test06: Tries to insert a logger with a negative level. CREATE OR REPLACE PROCEDURE TEST_06() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T6', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 2; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test6', 0, EXPECTED_LEVEL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, -1, EXPECTED_HIERARCHY); SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test06a: Tries to insert a logger with a ' || 'negative level', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test06b: Tries to insert a logger with a ' || 'negative level', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test06c: Tries to insert a logger with a ' || 'negative level', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test07: Tries to insert a logger with an inexistant level. CREATE OR REPLACE PROCEDURE TEST_07() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T7', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 4; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test7', 0, EXPECTED_LEVEL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, MAX_ID + 5, EXPECTED_HIERARCHY); SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test07a: Tries to insert a logger with an ' || 'inexistant level', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test07b: Tries to insert a logger with an ' || 'inexistant level', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test07c: Tries to insert a logger with an ' || 'inexistant level', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test08: Tries to insert a logger with a null hierarchy. CREATE OR REPLACE PROCEDURE TEST_08() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE RAISED_407 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE '23502' SET RAISED_407 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T8', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 5; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test8', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, NULL); CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test08: Tries to insert a logger with a ' || 'null hierarchy', RAISED_407); END @ -- Test09: Tries to insert a logger with an empty hierarchy. CREATE OR REPLACE PROCEDURE TEST_09() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T9', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = ''; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test9', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test09a: Tries to insert a logger with an ' || 'empty hierarchy', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test09b: Tries to insert a logger with an ' || 'empty hierarchy', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test09c: Tries to insert a logger with an ' || 'empty hierarchy', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test10: Tries to insert a logger with an invalid hierarchy. CREATE OR REPLACE PROCEDURE TEST_10() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T10', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 2; SET EXPECTED_HIERARCHY = 'andres'; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test10', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test10a: Tries to insert a logger with an ' || 'invalid hierarchy', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test10b: Tries to insert a logger with an ' || 'invalid hierarchy', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test10c: Tries to insert a logger with an ' || 'invalid hierarchy', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test11: Tries to update the id. CREATE OR REPLACE PROCEDURE TEST_11() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_LG0E1 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E1' SET RAISED_LG0E1 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T11', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 4; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test11', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LOGGER_ID = LOGGER WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test11: Tries to update the id', RAISED_LG0E1); END @ -- Test12: Tries to update the id to root. CREATE OR REPLACE PROCEDURE TEST_12() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_LG0E1 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E1' SET RAISED_LG0E1 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T12', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 5; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test12', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LOGGER_ID = 0 WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test12: Tries to update the id to root', RAISED_LG0E1); END @ -- Test13: Tries to update the id to some id. CREATE OR REPLACE PROCEDURE TEST_13() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_LG0E1 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E1' SET RAISED_LG0E1 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T13', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 1; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test13', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LOGGER_ID = LOGGER + 5 WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test13: Tries to update the id to some id', RAISED_LG0E1); END @ -- Test14: Tries to update the hierarchy. CREATE OR REPLACE PROCEDURE TEST_14() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_LG0E1 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E1' SET RAISED_LG0E1 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T14', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 2; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test14', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET HIERARCHY = '0,1' WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test14: Tries to update the hierarchy', RAISED_LG0E1); END @ -- Test15: Tries to update the hierarchy to null. CREATE OR REPLACE PROCEDURE TEST_15() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_LG0E1 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E1' SET RAISED_LG0E1 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T15', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 4; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test15', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET HIERARCHY = NULL WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test15: Tries to update to null', RAISED_LG0E1); END @ -- Test16: Tries to update the hierarchy to empty. CREATE OR REPLACE PROCEDURE TEST_16() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE RAISED_LG0E1 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E1' SET RAISED_LG0E1 = TRUE; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T16', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET LOGGER = MAX_ID + 1; SET LEVEL = 5; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test16', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET HIERARCHY = '' WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test16: Tries to update to empty', RAISED_LG0E1); END @ -- Test17: Update the level. CREATE OR REPLACE PROCEDURE TEST_17() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T17', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test17', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = 2 WHERE LOGGER_ID = EXPECTED_LOGGER; SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test17a: Updates the level', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test17b: Updates the level', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test17c: Updates the level', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test18: Update the level to null. CREATE OR REPLACE PROCEDURE TEST_18() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T18', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 2; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test18', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = NULL WHERE LOGGER_ID = EXPECTED_LOGGER; SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test18a: Updates the level to null', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test18b: Updates the level to null', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test18c: Updates the level to null', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test19: Update the level to negative. CREATE OR REPLACE PROCEDURE TEST_19() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T19', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 4; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test19', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = -2 WHERE LOGGER_ID = EXPECTED_LOGGER; SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test19a: Updates the level to negative', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test19b: Updates the level to negative', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test19c: Updates the level to negative', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test20: Update the level to inexistant. CREATE OR REPLACE PROCEDURE TEST_20() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T20', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 5; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test20', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = 8 WHERE LOGGER_ID = EXPECTED_LOGGER; SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test20a: Updates the level to inexistant', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test20b: Updates the level to inexistant', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test20c: Updates the level to inexistant', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test21: Update the level to same. CREATE OR REPLACE PROCEDURE TEST_21() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T21', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test21', 0, EXPECTED_LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (EXPECTED_LOGGER, EXPECTED_LEVEL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = EXPECTED_LOGGER; SET MAX_ID = GET_MAX_ID(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test21a: Updates the level to same', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test21b: Updates the level to same', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test21c: Updates the level to same', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test22: Delete one logger. CREATE OR REPLACE PROCEDURE TEST_22() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_QTY SMALLINT; DECLARE EXPECTED_QTY SMALLINT; SET MAX_ID = GET_MAX_ID(); SET LOGGER = MAX_ID + 1; SET LEVEL = 2; SET HIERARCHY = '0,' || CHAR(LOGGER); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test22', 0, LEVEL); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (LOGGER, LEVEL, HIERARCHY); SELECT COUNT(0) - 1 INTO EXPECTED_QTY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID = LOGGER; SELECT COUNT(0) INTO ACTUAL_QTY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_INT_EQUALS('Test22: Delete one logger', EXPECTED_QTY, ACTUAL_QTY); END @ -- Test23: Delete ROOT. CREATE OR REPLACE PROCEDURE TEST_23() BEGIN DECLARE RAISED_LG0E2 BOOLEAN DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLSTATE 'LG0E2' SET RAISED_LG0E2 = TRUE; DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID = 0; CALL DB2UNIT.ASSERT_BOOLEAN_TRUE('Test23: Delete ROOT', RAISED_LG0E2); END @ -- Test24: Delete all but root. CREATE OR REPLACE PROCEDURE TEST_24() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_QTY SMALLINT; DECLARE EXPECTED_QTY SMALLINT; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test24A', 0, 3); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, 3, '0,1'); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test24B', 0, 4); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, 4, '0,1'); SET EXPECTED_QTY = 0; DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SELECT COUNT(0) INTO ACTUAL_QTY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID <> 0; CALL DB2UNIT.ASSERT_INT_EQUALS('Test24: Delete all but root', EXPECTED_QTY, ACTUAL_QTY); END @ -- Test25: Updates root logger changing the default value, value from root. CREATE OR REPLACE PROCEDURE TEST_25() BEGIN DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; SET EXPECTED_LEVEL = 4; UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = 4 WHERE LOGGER_ID = 0; UPDATE LOGDATA.CONFIGURATION SET VALUE = '2' WHERE KEY = 'defaultRootLevelId'; CALL LOGGER.REFRESH_CACHE(); SELECT LEVEL_ID INTO ACTUAL_LEVEL FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = 0; CALL DB2UNIT.ASSERT_INT_EQUALS('Test25: Updates ROOT logger changing the ' || 'default', EXPECTED_LEVEL, ACTUAL_LEVEL); END @ -- Test26: Updates root logger changing the default value, value from root. CREATE OR REPLACE PROCEDURE TEST_26() BEGIN DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; SET EXPECTED_LEVEL = 1; UPDATE LOGDATA.CONFIGURATION SET VALUE = '5' WHERE KEY = 'defaultRootLevelId'; CALL LOGGER.REFRESH_CACHE(); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = 0; SELECT LEVEL_ID INTO ACTUAL_LEVEL FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = 0; CALL DB2UNIT.ASSERT_INT_EQUALS('Test26: Updates ROOT logger changing the ' || 'default', EXPECTED_LEVEL, ACTUAL_LEVEL); END @ -- Test27: Updates root logger changing the default value, value from default. CREATE OR REPLACE PROCEDURE TEST_27() BEGIN DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; SET EXPECTED_LEVEL = 4; UPDATE LOGDATA.CONFIGURATION SET VALUE = '4' WHERE KEY = 'defaultRootLevelId'; CALL LOGGER.REFRESH_CACHE(); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = NULL WHERE LOGGER_ID = 0; SELECT LEVEL_ID INTO ACTUAL_LEVEL FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = 0; CALL DB2UNIT.ASSERT_INT_EQUALS('Test27: Updates root logger changing the ' || 'default', EXPECTED_LEVEL, ACTUAL_LEVEL); END @ -- Test28: Updates a normal logger changing the default value. Nothing happens. CREATE OR REPLACE PROCEDURE TEST_28() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T28', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 5; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = 1 WHERE LOGGER_ID = 0; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test28', 0, EXPECTED_LEVEL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, 3, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONFIGURATION SET VALUE = '5' WHERE KEY = 'defaultRootLevelId'; CALL LOGGER.REFRESH_CACHE(); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = MAX_ID; UPDATE LOGDATA.CONFIGURATION SET VALUE = '4' WHERE KEY = 'defaultRootLevelId'; CALL LOGGER.REFRESH_CACHE(); SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test28a: Updates a normal logger changing the ' || 'default value', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test28b: Updates a normal logger changing the ' || 'default value', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test28c: Updates a normal logger changing ' || 'the default value', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test29: Updates a normal logger changing the default value, value from root. CREATE OR REPLACE PROCEDURE TEST_29() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T26', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 5; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = 0; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test29', 0, NULL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, NULL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONFIGURATION SET VALUE = '2' WHERE KEY = 'defaultRootLevelId'; CALL LOGGER.REFRESH_CACHE(); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = MAX_ID; SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test29a: Updates a normal logger changing the ' || 'default value', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test29b: Updates a normal logger changing the ' || 'default value', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test29c: Updates a normal logger changing ' || 'the default value', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test30: Updates a normal logger changing the default value, value from -- default. CREATE OR REPLACE PROCEDURE TEST_30() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T30', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 4; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = NULL WHERE LOGGER_ID = 0; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test30', 0, NULL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, NULL, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONFIGURATION SET VALUE = '1' WHERE KEY = 'defaultRootLevelId'; CALL DELETE_LAST_MESSAGE_FROM_TRIGGER(); CALL LOGGER.REFRESH_CACHE(); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = MAX_ID; SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test30a: Updates a normal logger changing the ' || 'default value', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test30b: Updates a normal logger changing the ' || 'default value', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test30c: Updates a normal logger changing ' || 'the default value', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test31: Tests hierarchy path one level. CREATE OR REPLACE PROCEDURE TEST_31() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE STRING VARCHAR(32); DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_PATH VARCHAR(64); DECLARE EXPECTED_PATH VARCHAR(64); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T31', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET STRING = 'path1'; SET EXPECTED_PATH = '0,' || TRIM(CHAR(MAX_ID + 1)); CALL LOGGER.GET_LOGGER(STRING, LOGGER); SELECT TRIM(HIERARCHY) INTO ACTUAL_PATH FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_STRING_EQUALS('Test31: Tests hierarchy path one level', EXPECTED_PATH, ACTUAL_PATH); END @ -- Test32: Tests hierarchy path two levels. CREATE OR REPLACE PROCEDURE TEST_32() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE STRING VARCHAR(32); DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_PATH VARCHAR(64); DECLARE EXPECTED_PATH VARCHAR(64); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T32', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET STRING = 'path1.path2'; SET EXPECTED_PATH = '0,' || TRIM(CHAR(MAX_ID + 1)) || ',' || TRIM(CHAR(MAX_ID + 2)); CALL LOGGER.GET_LOGGER(STRING, LOGGER); SELECT TRIM(HIERARCHY) INTO ACTUAL_PATH FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_STRING_EQUALS('Test32: Tests hierarchy path two levels', EXPECTED_PATH, ACTUAL_PATH); END @ -- Test33: Tests hierarchy path three levels. CREATE OR REPLACE PROCEDURE TEST_33() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE STRING VARCHAR(32); DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_PATH VARCHAR(64); DECLARE EXPECTED_PATH VARCHAR(64); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T33', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET STRING = 'path1.path2.path3'; SET EXPECTED_PATH = '0,' || TRIM(CHAR(MAX_ID + 1)) || ',' || TRIM(CHAR(MAX_ID + 2)) || ',' || TRIM(CHAR(MAX_ID + 3)); CALL LOGGER.GET_LOGGER(STRING, LOGGER); SELECT TRIM(HIERARCHY) INTO ACTUAL_PATH FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_STRING_EQUALS('Test33: Tests hierarchy path three levels', EXPECTED_PATH, ACTUAL_PATH); END @ -- Test34: Tests hierarchy path other two levels. CREATE OR REPLACE PROCEDURE TEST_34() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE STRING VARCHAR(32); DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_PATH VARCHAR(64); DECLARE EXPECTED_PATH VARCHAR(64); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T34', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET STRING = 'path1.path2'; CALL LOGGER.GET_LOGGER(STRING, LOGGER); SET STRING = 'path1.path3'; SET EXPECTED_PATH = '0,' || TRIM(CHAR(MAX_ID + 1)) || ',' || TRIM(CHAR(MAX_ID + 3)); CALL LOGGER.GET_LOGGER(STRING, LOGGER); SELECT TRIM(HIERARCHY) INTO ACTUAL_PATH FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_STRING_EQUALS('Test34: Tests hierarchy other two levels', EXPECTED_PATH, ACTUAL_PATH); END @ -- Test35: Tests hierarchy path other one level. CREATE OR REPLACE PROCEDURE TEST_35() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE STRING VARCHAR(32); DECLARE LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_PATH VARCHAR(64); DECLARE EXPECTED_PATH VARCHAR(64); INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T35', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET STRING = 'path1'; CALL LOGGER.GET_LOGGER(STRING, LOGGER); SET STRING = 'path2'; SET EXPECTED_PATH = '0,' || TRIM(CHAR(MAX_ID + 2)); CALL LOGGER.GET_LOGGER(STRING, LOGGER); SELECT TRIM(HIERARCHY) INTO ACTUAL_PATH FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = LOGGER; CALL DB2UNIT.ASSERT_STRING_EQUALS('Test35: Tests hierarchy other one level', EXPECTED_PATH, ACTUAL_PATH); END @ -- Test36: Updates to null conf_logger. Value from ascendancy. CREATE OR REPLACE PROCEDURE TEST_36() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T36', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = 0; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test36', 0, 2); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, 4, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = NULL WHERE LOGGER_ID = MAX_ID; SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test36a: Updates to null conf_logger. Value ' || 'from ascendancy', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test36b: Updates to null conf_logger. Value ' || 'from ascendancy', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test36c: Updates to null conf_logger. ' || 'Value from ascendancy', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test37: Updates to not null conf_logger. Value from conf_loggers. CREATE OR REPLACE PROCEDURE TEST_37() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T37', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 5; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); UPDATE LOGDATA.CONF_LOGGERS_EFFECTIVE SET LEVEL_ID = 4 WHERE LOGGER_ID = 0; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test37', 0, NULL); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, 2, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = MAX_ID; SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test36a: Updates to not null conf_logger. ' || 'Value from conf_loggers', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test36b: Updates to not null conf_logger. ' || 'Value from conf_loggers', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test36c: Updates to not null conf_logger. ' || 'Value from conf_loggers', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Test38: Updates to null conf_logger. Value from ascendancy. CREATE OR REPLACE PROCEDURE TEST_38() BEGIN DECLARE MAX_ID ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE EXPECTED_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE EXPECTED_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; DECLARE ACTUAL_LOGGER ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LOGGER_ID; DECLARE ACTUAL_LEVEL ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.LEVEL_ID; DECLARE ACTUAL_HIERARCHY ANCHOR DATA TYPE TO LOGDATA.CONF_LOGGERS_EFFECTIVE.HIERARCHY; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('T38', 0, 0); SET MAX_ID = GET_MAX_ID(); DELETE FROM LOGDATA.CONF_LOGGERS WHERE LOGGER_ID <> 0; SET EXPECTED_LOGGER = MAX_ID + 1; SET EXPECTED_LEVEL = 1; SET EXPECTED_HIERARCHY = '0,' || CHAR(EXPECTED_LOGGER); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = EXPECTED_LEVEL WHERE LOGGER_ID = 0; INSERT INTO LOGDATA.CONF_LOGGERS (NAME, PARENT_ID, LEVEL_ID) VALUES ('test38', 0, 2); SET MAX_ID = GET_MAX_ID(); INSERT INTO LOGDATA.CONF_LOGGERS_EFFECTIVE (LOGGER_ID, LEVEL_ID, HIERARCHY) VALUES (MAX_ID, 4, EXPECTED_HIERARCHY); UPDATE LOGDATA.CONF_LOGGERS SET LEVEL_ID = NULL WHERE LOGGER_ID = MAX_ID; SELECT LOGGER_ID, LEVEL_ID, HIERARCHY INTO ACTUAL_LOGGER, ACTUAL_LEVEL, ACTUAL_HIERARCHY FROM LOGDATA.CONF_LOGGERS_EFFECTIVE WHERE LOGGER_ID = MAX_ID; CALL DB2UNIT.ASSERT_INT_EQUALS('Test38a: Updates to null conf_logger. Value from ascendancy', EXPECTED_LOGGER, ACTUAL_LOGGER); CALL DB2UNIT.ASSERT_INT_EQUALS('Test38b: Updates to null conf_logger. Value from ascendancy', EXPECTED_LEVEL, ACTUAL_LEVEL); CALL DB2UNIT.ASSERT_STRING_EQUALS('Test38c: Updates to null conf_logger. Value from ascendancy', EXPECTED_HIERARCHY, ACTUAL_HIERARCHY); END @ -- Register the suite. CALL DB2UNIT.REGISTER_SUITE(CURRENT SCHEMA) @
42.490152
98
0.771712
33f8c905efb4c71f9b6ce0a8340c405bc5600843
661
php
PHP
mlnr-server/app/Mail/RSVPMail.php
deroude/mlnr-php
d967ea2505033ff393ed063640a64e1244c9f759
[ "MIT" ]
null
null
null
mlnr-server/app/Mail/RSVPMail.php
deroude/mlnr-php
d967ea2505033ff393ed063640a64e1244c9f759
[ "MIT" ]
null
null
null
mlnr-server/app/Mail/RSVPMail.php
deroude/mlnr-php
d967ea2505033ff393ed063640a64e1244c9f759
[ "MIT" ]
null
null
null
<?php namespace App\Mail; use Illuminate\Mail\Mailable; class RSVPMail extends Mailable { public $text; public $secret; public $name; public $date; public function __construct($name, $text, $secret, $date) { $this->text = $text; $this->secret = $secret; $this->name = $name; $this->date = $date; } /** * Build the message. * * @return $this */ public function build() { return $this ->from(['address' => '[email protected]', 'name' => 'Toleranta si Fraternitate']) ->subject('Invitatie') ->markdown('rsvp_mail'); } }
18.885714
92
0.526475
e7f86980be188e531b32d49c3b6be7418d34f337
3,184
go
Go
src/kubernetes-alerts/api-client.go
AcalephStorage/kubernetes-alerts
61df4be489af24773e9a99ca688c5ffec84c72e6
[ "Apache-2.0" ]
42
2015-12-09T04:51:34.000Z
2020-05-19T07:56:56.000Z
src/kubernetes-alerts/api-client.go
AcalephStorage/kubernetes-alerts
61df4be489af24773e9a99ca688c5ffec84c72e6
[ "Apache-2.0" ]
7
2016-01-11T07:48:34.000Z
2016-02-26T10:08:55.000Z
src/kubernetes-alerts/api-client.go
AcalephStorage/kubernetes-alerts
61df4be489af24773e9a99ca688c5ffec84c72e6
[ "Apache-2.0" ]
7
2016-01-25T15:27:55.000Z
2022-03-25T18:18:39.000Z
package main import ( "errors" "io" "time" "crypto/tls" "crypto/x509" "encoding/json" "io/ioutil" "net/http" "github.com/Sirupsen/logrus" ) type ApiClient struct { *http.Client apiBaseUrl string certificateAuthority string clientCertificate string clientKey string token string tokenFile string } func (a *ApiClient) prepareClient() error { var cacert *x509.CertPool if a.certificateAuthority != "" { capem, err := ioutil.ReadFile(a.certificateAuthority) if err != nil { return err } cacert = x509.NewCertPool() if !cacert.AppendCertsFromPEM(capem) { return errors.New("unable to load certificate authority") } } var cert tls.Certificate if a.clientCertificate != "" && a.clientKey != "" { c := a.clientCertificate k := a.clientKey var err error cert, err = tls.LoadX509KeyPair(c, k) if err != nil { return err } } if cacert != nil || &cert != nil { config := &tls.Config{ RootCAs: cacert, Certificates: []tls.Certificate{cert}, } transport := &http.Transport{ TLSClientConfig: config, TLSHandshakeTimeout: 5 * time.Second, } client := &http.Client{Transport: transport} a.Client = client } else { a.Client = &http.Client{} } if a.token == "" && a.tokenFile != "" { token, err := ioutil.ReadFile(a.tokenFile) if err != nil { return err } a.token = string(token) } return nil } func (a *ApiClient) GetRequest(path string, resData interface{}) error { endpoint := a.apiBaseUrl + path logrus.Debugf("GET request to: %s", endpoint) req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return err } if a.token != "" { req.Header.Add("Authorization", "Bearer "+a.token) } res, err := a.Do(req) if err != nil { return err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return err } err = json.Unmarshal(body, resData) if err != nil { return err } logrus.Debug("Get request successful") return nil } func (a *ApiClient) PostRequest(path string, data io.Reader) error { endpoint := a.apiBaseUrl + path logrus.Debugf("POST request to: %s", endpoint) req, err := http.NewRequest("POST", endpoint, data) if err != nil { return err } if a.token != "" { req.Header.Add("Authorization", "Bearer "+a.token) } res, err := a.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode == http.StatusCreated || res.StatusCode == http.StatusOK { logrus.Debug("POST request successful.") return nil } return errors.New(res.Status) } func (a *ApiClient) PutRequest(path, data string) error { endpoint := a.apiBaseUrl + path logrus.Debugf("PUT request to: %s", endpoint) req, err := http.NewRequest("PUT", endpoint, nil) req.PostForm["value"] = []string{data} if err != nil { return err } if a.token != "" { req.Header.Add("Authorization", "Bearer "+a.token) } res, err := a.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode == http.StatusCreated || res.StatusCode == http.StatusOK { logrus.Debug("PUT request successful") return nil } return errors.New(res.Status) }
21.369128
77
0.646357
ddd10cb2f5636eedd004b13d3fe65e2852a7d38c
3,105
java
Java
src/test/java/org/jab/microservices/repository/AccountRepositoryTest.java
jabrena/spring-boot-testcontainers-poc
e382f4a3408e61515623bee5c7e2ede88fa0fa93
[ "Apache-2.0" ]
null
null
null
src/test/java/org/jab/microservices/repository/AccountRepositoryTest.java
jabrena/spring-boot-testcontainers-poc
e382f4a3408e61515623bee5c7e2ede88fa0fa93
[ "Apache-2.0" ]
2
2018-11-02T13:52:25.000Z
2018-12-12T22:06:10.000Z
src/test/java/org/jab/microservices/repository/AccountRepositoryTest.java
jabrena/spring-boot-testcontainers-poc
e382f4a3408e61515623bee5c7e2ede88fa0fa93
[ "Apache-2.0" ]
null
null
null
package org.jab.microservices.repository; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import org.testcontainers.containers.PostgreSQLContainer; import java.util.Arrays; import java.util.List; @RunWith(SpringRunner.class) @ContextConfiguration(initializers = AccountRepositoryTest.Initializer.class) @Transactional @SpringBootTest @ActiveProfiles("test") public class AccountRepositoryTest { @ClassRule public static PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer(); @Autowired private AccountRepository accountRepository; @Test public void getAccountTest() { List<Account> account = this.accountRepository.getAccounts(); Assert.assertEquals(3, account.size()); } @Test public void findById() { Account account = this.accountRepository.findById(1).get(); Assert.assertEquals("user1", account.getUsername()); Assert.assertEquals("[email protected]", account.getEmail()); System.out.println(account.getCreated()); } @Test public void length() { int length = this.accountRepository.accountsLength(); Assert.assertEquals(3, length); } @Test public void updateName() { boolean updated = this.accountRepository.updateName(3, "updatedname"); Assert.assertTrue(updated); } @Test public void deleteList() { this.accountRepository.deleteIdList(Arrays.asList(1, 2)); int length = this.accountRepository.accountsLength(); Assert.assertEquals(1, length); } /** * This class replaces the embedded database with a PostgreSQL Docker Container */ static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues.of( "spring.datasource.initialization-mode: always", "spring.datasource.postgres.driverClassName=" + postgresqlContainer.getDriverClassName(), "spring.datasource.postgres.jdbc-url=" + postgresqlContainer.getJdbcUrl(), "spring.datasource.postgres.username=" + postgresqlContainer.getUsername(), "spring.datasource.postgres.password=" + postgresqlContainer.getPassword()) .applyTo(configurableApplicationContext.getEnvironment()); } } }
34.120879
109
0.72818
b09c32ff73d0a487ec14563bd1241029ed25569e
49,052
py
Python
BookModel.py
BitWorks/xbrlstudio
231beb46c56c8086f9fcc8846955667d947709c2
[ "MIT" ]
null
null
null
BookModel.py
BitWorks/xbrlstudio
231beb46c56c8086f9fcc8846955667d947709c2
[ "MIT" ]
null
null
null
BookModel.py
BitWorks/xbrlstudio
231beb46c56c8086f9fcc8846955667d947709c2
[ "MIT" ]
null
null
null
""" :mod: 'BookModel' ~~~~~~~~~~~~~~~~~ .. py:module:: BookModel :copyright: Copyright BitWorks LLC, All rights reserved. :license: MIT :synopsis: Collection of PyQt models used by XBRLStudio :description: Contains the following classes: BookTableModel - model for numerical and textual XBRLStudio tables BookEntityTreeModel - model for the entity tree BookEntityTreeItem - model for an item within the entity tree BookFilingTreeModel - model for the filing tree BookFilingTreeItem - model for an item within the filing tree BookLineEdit - custom QLineEdit with overridden contextMenuEvent() BookTableViewDelegate - delegate object for table editors and models (see Qt model/view documentation) """ try: import copy, sys, os, datetime, logging model_logger = logging.getLogger() from PySide2 import (QtCore, QtWidgets, QtGui) # Tiered # from . import BookFilingUtility # Flat import BookFilingUtility except Exception as err: model_logger.error("{0}:BookModel import error:{1}".format(str(datetime.datetime.now()), str(err))) class BookTableModel(QtCore.QAbstractTableModel): """ BookTableModel ~~~~~~~~~~~~~~ Customized sub-class of QAbstractTableModel; this class implements all the required model functions, as well as a function for inserting a selected entity/filing pair into the table model Functions ~~~~~~~~~ rowCount(self, parent) - returns row_count, the number of rows in the table addRows(self, num_rows) - appends user-defined number of rows to the table columnCount(self, parent) - returns the number of columns in the table, based on the table type data(self, index, role) - returns the items object at the given index position, for the given role headerData(self, section, orientation, role) - sets labels for the columns, and other column attributes setData(self, index, value, role) - assigns an items object to be equal to the given value, according to position (index) and role insertFilingIntoTable(self, current_cik, current_period) - inserts the selected entity name and filing into items flags(self, index) - function for QAbstractTableModel flags; defines aspects of the different columns setHeaderData(self, section, orientation, value, role) - default implementation of QAbstractTableModel.setHeaderData fillDown(self, index, fill_text) - fills a column (downwards) with text in fill_text at given index viewAll(self) - sets all rows to be viewed in table's graphic (numerical or textual) Attributes ~~~~~~~~~~ book_table_view - (BookView.BookTableView type); view for instances of this model row_count - (int type); number of rows (initialized to be 10) items - (list type); main model collection of bool, string, and int values for use by the view view_indices - (list type); used (e.g., by BookView.BookMainWindow instance) to create persistent checkboxes in 'View' column sub_items - (list type); used during the initial creation of the items matrix (items[row][column]) """ def __init__(self, book_table_view): model_logger.info("{0}:Initializing BookTableModel".format(str(datetime.datetime.now()))) QtCore.QAbstractTableModel.__init__(self) self.book_table_view = book_table_view self.row_count = 10 self.items = [] self.view_indices = [] #cik, period, view, entity, filing, fact, context, value, unit, dec self.sub_items = [None, None, None, None, None, None, None, None, None, None] for i in range(0, self.row_count): self.items.append(copy.deepcopy(self.sub_items)) if self.book_table_view.objectName() == "numericalTableView": self.setObjectName("numericalTableModel") elif self.book_table_view.objectName() == "textualTableView": self.setObjectName("textualTableModel") else: model_logger.error("{0}:BookTableModel.book_table_view.objectName(): unacceptable return value".format(str(datetime.datetime.now()))) def rowCount(self, parent): return self.row_count def addRows(self, num_rows): self.layoutAboutToBeChanged.emit() for i in range(self.row_count, self.row_count + num_rows): self.items.append(copy.deepcopy(self.sub_items)) self.row_count += num_rows self.layoutChanged.emit() return def columnCount(self, parent): if self.objectName() == "textualTableModel": return 5 elif self.objectName() == "numericalTableModel": return 8 else: model_logger.error("{0}:BookTableModel.columnCount(): unacceptable object name".format(str(datetime.datetime.now()))) def data(self, index, role): if not index.isValid(): model_logger.warning("{0}:BookTableModel.data(): invalid index".format(str(datetime.datetime.now()))) return if index.column() == 0: if len(self.view_indices) < self.row_count: row = len(self.view_indices) while row < self.row_count: self.view_indices.append(index.sibling(row, 0)) row += 1 if role == QtCore.Qt.DisplayRole: pass elif role == QtCore.Qt.DecorationRole: return QtCore.Qt.AlignCenter elif role == QtCore.Qt.EditRole: return self.items[index.row()][index.column() + 2] elif index.column() in (1, 2, 3, 4): if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole): return self.items[index.row()][index.column() + 2] elif index.column() in (5, 6, 7): if role == QtCore.Qt.DisplayRole: if self.objectName() == "numericalTableModel": return self.items[index.row()][index.column() + 2] elif self.objectName() == "textualTableModel": return None if index.column() == 5: if role == QtCore.Qt.TextAlignmentRole: return QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter if index.column() == 6 or index.column() == 7: if role == QtCore.Qt.TextAlignmentRole: return QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter else: model_logger.warning("{0}:BookTableModel.data(): invalid index.column()".format(str(datetime.datetime.now()))) return def headerData(self, section, orientation, role): if orientation == QtCore.Qt.Horizontal: if section == 0: if role == QtCore.Qt.DisplayRole: return "View" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(45, 25) elif section == 1: if role == QtCore.Qt.DisplayRole: return "Entity" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif section == 2: if role == QtCore.Qt.DisplayRole: return "Filing" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif section == 3: if role == QtCore.Qt.DisplayRole: return "Fact" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif section == 4: if role == QtCore.Qt.DisplayRole: return "Context" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif section == 5: if role == QtCore.Qt.DisplayRole: return "Value" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif section == 6: if role == QtCore.Qt.DisplayRole: return "Unit" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif section == 7: if role == QtCore.Qt.DisplayRole: return "Dec" elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(100, 25) elif orientation == QtCore.Qt.Vertical: if role == QtCore.Qt.DisplayRole: return str(section + 1) elif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(40, 25) return def setData(self, index, value, role): try: if value is not None and index.isValid(): if index.column() == 0: #view toggled self.book_table_view.closePersistentEditor(index) self.items[index.row()][2] = value self.book_table_view.openPersistentEditor(index) self.book_table_view.refreshGraphic() elif index.column() == 1: #entity selected (set cik) # TODO - rearrange for this to be cik_name_dict ({cik:name}) name_cik_dict = self.book_table_view.book_main_window.cntlr.book_filing_manager.getEntityDict() current_cik = int(name_cik_dict[value]) self.items[index.row()][0] = current_cik self.items[index.row()][3] = value elif index.column() == 2: #filing selected (set period) current_period = value.split("-")[1].lower() + value.split("-")[0] self.items[index.row()][1] = current_period self.items[index.row()][4] = value elif index.column() == 3: #fact selected self.items[index.row()][5] = value elif index.column() == 4: #context selected (set value and unit) self.items[index.row()][6] = value current_cik = self.items[index.row()][0] current_period = self.items[index.row()][1] current_filing = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFiling(current_cik, current_period) current_fact_name = self.items[index.row()][5] current_context = str(value) current_facts = set() if current_filing is not None: for fact_item in current_filing.facts: if fact_item.label == current_fact_name: if fact_item.context_ref == current_context: current_facts.add(fact_item) if len(current_facts) == 1: if self.objectName() == "numericalTableModel": self.items[index.row()][7] = list(current_facts)[0].value self.items[index.row()][8] = list(current_facts)[0].unit_ref self.items[index.row()][9] = list(current_facts)[0].dec elif self.objectName() == "textualTableModel": self.items[index.row()][7] = list(current_facts)[0].value self.items[index.row()][8] = list(current_facts)[0].unit_ref self.items[index.row()][9] = list(current_facts)[0].dec elif len(current_facts) != 1: return False self.book_table_view.refreshGraphic() return True except Exception as err: model_logger.error("{0}:BookTableModel.setData():{1}".format(str(datetime.datetime.now()), str(err))) return def insertFilingIntoTable(self, current_cik, current_period): try: current_filing = self.book_table_view.book_main_window.cntlr.getFiling(current_cik, current_period) entity_name = self.book_table_view.book_main_window.cntlr.getNameFromCik(current_cik) pretty_filing_period = current_period[2:6] + "-" + current_period[0:2].upper() i = 0 while i < self.row_count: if self.items[i][0] == None: self.items[i][0] = int(current_cik) self.items[i][1] = current_period self.items[i][3] = entity_name self.items[i][4] = pretty_filing_period self.book_table_view.update() i = self.row_count i += 1 except Exception as err: model_logger.error("{0}:BookTableModel.insertFilingIntoTable():{1}".format(str(datetime.datetime.now()), str(err))) def flags(self, index): try: if not index.isValid(): model_logger.info("{0}:BookTableModel.flags(): invalid index".format(str(datetime.datetime.now()))) return QtCore.Qt.ItemIsEnabled if index.column() == 0: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable elif index.column() == 1 or index.column() == 2: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDropEnabled elif index.column() == 3 or index.column() == 4: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable elif index.column() == 5 or index.column() == 6 or index.column() == 7: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable else: model_logger.warning("{0}:BookTableModel.flags(): invalid index.column()".format(str(datetime.datetime.now()))) except Exception as err: model_logger.error("{0}:BookTableModel.flags():{1}".format(str(datetime.datetime.now()), str(err))) def setHeaderData(self, section, orientation, value, role): QtCore.QAbstractTableModel.setHeaderData(self, section, orientation, value, role) return def fillDown(self, index, fill_text): try: row_pos = index.row() col_pos = index.column() num_rows = self.row_count - row_pos if num_rows > 0: try: if fill_text is not None and fill_text is not "": i = row_pos while i < self.row_count: current_index = self.createIndex(i, col_pos) self.setData(current_index, fill_text, QtCore.Qt.EditRole) i += 1 self.book_table_view.update() except Exception as err: model_logger.error("{0}:BookTableModel.fillDown():{1}".format(str(datetime.datetime.now()), str(err))) except Exception as err: model_logger.error("{0}:BookTableModel.fillDown():{1}".format(str(datetime.datetime.now()), str(err))) return def viewAll(self): try: i = 0 while i < self.row_count: current_index = self.createIndex(i, 0) self.setData(current_index, True, QtCore.Qt.EditRole) i += 1 self.book_table_view.update() except Exception as err: model_logger.error("{0}:BookTableModel.viewAll():{1}".format(str(datetime.datetime.now()), str(err))) return class BookEntityTreeModel(QtGui.QStandardItemModel): """ BookEntityTreeModel ~~~~~~~~~~~~~~~~~~~ Customized sub-class of QStandardItemModel Functions ~~~~~~~~~ itemMoved(self, item_changed) - updates parent_cik for the entity moved populateRawItems(self) - uses the controller to query the database and get entity tree information renameItem(self, target_cik, new_name) - uses the controller to rename an entity in the database flags(self, index) - enables drag and drop for entity tree, for reorganization of entity hierarchy Attributes ~~~~~~~~~~ book_main_window - (BookView.BookMainWindow type); for accessing main window object, such as controller raw_items - (list type); list of tuples in the format [(entity_cik, parent_cik, entity_name)] itemChanged - (signal type); QStandardItemModel built-in signal, triggered when an item is modified/moved """ def __init__(self, book_main_window, raw_items = None): model_logger.info("{0}:Initializing BookEntityTreeModel".format(str(datetime.datetime.now()))) QtGui.QStandardItemModel.__init__(self) self.book_main_window = book_main_window self.raw_items = raw_items self.itemChanged.connect(self.itemMoved) def itemMoved(self, item_changed): child_cik = item_changed.data() try: parent_cik = item_changed.parent().data() except AttributeError: parent_cik = None update_attempt = self.book_main_window.cntlr.updateParentInfo(child_cik, parent_cik) if update_attempt: self.book_main_window.entity_tree_view.refresh() return else: model_logger.error("{0}:BookEntityTreeModel.itemMoved(): update attempt failed".format(str(datetime.datetime.now()))) return def populateRawItems(self): try: self.raw_items = self.book_main_window.cntlr.book_filing_manager.getEntityTreeInfo() except Exception as err: model_logger.error("{0}:BookEntityTreeModel.populateRawItems():{1}".format(str(datetime.datetime.now()), str(err))) return def renameItem(self, target_cik, new_name): try: self.book_main_window.cntlr.renameEntity(target_cik, new_name) except Exception as err: model_logger.error("{0}:BookEntityTreeModel.renameItem():{1}".format(str(datetime.datetime.now()), str(err))) def flags(self, index): try: flags = super().flags(index) if index.isValid(): flags = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled return flags except Exception as err: model_logger.error("{0}:BookEntityTreeModel.flags():{1}".format(str(datetime.datetime.now()), str(err))) return class BookEntityTreeItem(QtGui.QStandardItem): """ BookEntityTreeItem ~~~~~~~~~~~~~~~~~~ Customized sub-class of QStandardItem Functions ~~~~~~~~~ setChildren(self) - assigns children objects as QStandardItem children to construct the entity tree Attributes ~~~~~~~~~~ cik - (string or int type); central index key, set as QStandardItem instance data parent_cik - (string or int type); parent entity central index key name - (string type); entity name children - (list type); list of children BookEntityTreeItem objects """ def __init__(self, cik, parent_cik, name, children = None): model_logger.info("{0}:Initializing BookEntityTreeItem".format(str(datetime.datetime.now()))) QtGui.QStandardItem.__init__(self) self.setEditable(False) self.cik = cik self.parent_cik = parent_cik self.name = name self.children = [] self.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled) self.setData(self.cik) def setChildren(self): try: for row, child in enumerate(self.children): self.setChild(row, child) except Exception as err: model_logger.error("{0}:BookEntityTreeItem.setChildren():{1}".format(str(datetime.datetime.now()), str(err))) class BookFilingTreeModel(QtGui.QStandardItemModel): """ BookFilingTreeModel ~~~~~~~~~~~~~~~~~~~ Customized sub-class of QStandardItemModel Functions ~~~~~~~~~ populateRawItems(self) - uses the controller to query the database and get filing tree information Attributes ~~~~~~~~~~ book_main_window - (BookView.BookMainWindow type); for accessing main window object, such as controller raw_items - (list type); list of tuples in the format [(entity_cik, parent_cik, entity_name)] """ def __init__(self, book_main_window, raw_items = None): model_logger.info("{0}:Initializing BookFilingTreeModel".format(str(datetime.datetime.now()))) QtGui.QStandardItemModel.__init__(self) self.book_main_window = book_main_window self.raw_items = raw_items def populateRawItems(self, target_cik): try: if target_cik is not None: self.raw_items = self.book_main_window.cntlr.book_filing_manager.getFilingTreeInfo(target_cik) except Exception as err: model_logger.error("{0}:BookFilingTreeModel.populateRawItems():{1}".format(str(datetime.datetime.now()), str(err))) class BookFilingTreeItem(QtGui.QStandardItem): """ BookFilingTreeItem ~~~~~~~~~~~~~~~~~~ Customized sub-class of QStandardItem Functions ~~~~~~~~~ setChildren(self) - assigns children objects as QStandardItem children to construct the filing tree Attributes ~~~~~~~~~~ cik - (string or int type); central index key, set as QStandardItem instance data period - (string type); period descriptor children - (list type); list of children BookEntityTreeItem objects """ def __init__(self, period, cik = None, children = None): model_logger.info("{0}:Initializing BookFilingTreeItem".format(str(datetime.datetime.now()))) QtGui.QStandardItem.__init__(self) self.cik = cik self.period = period self.children = [] self.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) def setChildren(self): try: for row, child in enumerate(self.children): self.setChild(row, child) except Exception as err: model_logger.error("{0}:BookFilingTreeItem.setChildren():{1}".format(str(datetime.datetime.now()), str(err))) class BookLineEdit(QtWidgets.QLineEdit): """ BookLineEdit ~~~~~~~~~~~~ Customized sub-class of QLineEdit Functions ~~~~~~~~~ contextMenuEvent(self, event) - overrides QLineEdit context menu to add "fill down" option Attributes ~~~~~~~~~~ parent - (unknown type) - required argument (see Qt documentation) index - (unknown type) - required argument (see Qt documentation) book_table_view - (BookView.BookTableView type) - allows access to book table view for fill down functionality menu - standard context menu for QLineEdit action_fill_down - (QAction type) - activates the fill down functionality in the current book table model using a lambda function """ def __init__(self, parent, index): model_logger.info("{0}:Initializing BookLineEdit".format(str(datetime.datetime.now()))) QtWidgets.QLineEdit.__init__(self) self.parent = parent self.index = index self.book_table_view = self.parent.parent() self.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self.setObjectName("BookLineEdit") def contextMenuEvent(self, event): try: self.menu = self.createStandardContextMenu() self.menu.addSeparator() self.action_fill_down = self.menu.addAction("Fill Down") self.action_fill_down.triggered.connect(lambda x: self.book_table_view.model().fillDown(self.index, self.text())) self.menu.exec_(event.globalPos()) del(self.menu) except Exception as err: model_logger.error("{0}:BookLineEdit.contextMenuEvent():{1}".format(str(datetime.datetime.now()), str(err))) return class BookTableViewDelegate(QtWidgets.QStyledItemDelegate): """ BookTableViewDelegate ~~~~~~~~~~~~~~~~~~~~~ Customized sub-class of QStyledItemDelegate Functions ~~~~~~~~~ paint(self, painter, option, index) - default implementation of QStyledItemDelegate.paint function sizeHint(self, option, index) - default implementation of QStyledItemDelegate.sizeHint function createEditor(self, parent, option, index) - custom implementation, creates at least a combobox for the view setEditorData(self, editor, index) - sets the editor data to be equal to the current selection setModelData(self, editor, model, index) - sets the model data to be equal to the current selection updateEditorGeometry(self, editor, option, index) - default implmentation of QStyledItemDelegate.updateEditorGeometry function Attributes ~~~~~~~~~~ book_table_view - (BookView.BookTableView type); view for instances of this model (model accessed via index) """ def __init__(self, book_table_view): model_logger.info("{0}:Initializing BookTableViewDelegate".format(str(datetime.datetime.now()))) QtWidgets.QStyledItemDelegate.__init__(self) self.book_table_view = book_table_view def paint(self, painter, option, index): QtWidgets.QStyledItemDelegate.paint(self, painter, option, index) return def sizeHint(self, option, index): return QtWidgets.QStyledItemDelegate.sizeHint(self, option, index) def createEditor(self, parent, option, index): if self.book_table_view.objectName() == "numericalTableView": if index.column() == 0: #View self.num_view_ch = QtWidgets.QCheckBox(parent) self.num_view_ch.toggled.connect(self.book_table_view.refreshGraphic) return self.num_view_ch elif index.column() == 1: #Entity self.num_entity_cb = QtWidgets.QComboBox(parent) self.num_entity_cb.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) try: # [cik, parent_cik, name] self.num_entity_tree_info = self.book_table_view.book_main_window.cntlr.book_filing_manager.getEntityTreeInfo() self.entity_list = [] for item in self.num_entity_tree_info: self.entity_list.append(item[2]) self.num_entity_cb.addItems(self.entity_list) self.num_entity_cb.setEditable(True) self.num_entity_le = BookLineEdit(parent, index) self.num_entity_le.undoAvailable = True self.num_entity_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.num_entity_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.num_entity_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.num_entity_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.num_entity_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.num_entity_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.num_entity_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.num_entity_le.selectAll) self.num_entity_cb.setLineEdit(self.num_entity_le) self.num_entity_cm = QtWidgets.QCompleter(self) self.num_entity_sl = QtCore.QStringListModel(self) self.num_entity_cm.setModel(self.num_entity_sl) self.num_entity_cm.setCompletionRole(QtCore.Qt.EditRole) self.num_entity_sl.setStringList(sorted(self.entity_list)) self.num_entity_cb.setCompleter(self.num_entity_cm) # self.num_entity_le.setFrame(False) # self.num_entity_le.setTextMargins(0, 0, 10, 0) # self.num_entity_le.setStyleSheet("background-color: rgba(0, 0, 0, 0)") except Exception as err: return self.num_entity_cb return self.num_entity_cb elif index.column() == 2: #Filing self.num_filing_cb = QtWidgets.QComboBox(parent) self.num_filing_cb.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) try: self.current_cik = self.book_table_view.model().items[index.row()][0] self.num_filing_tree_info = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFilingTreeInfo(self.current_cik) self.num_filing_cb.addItems(self.num_filing_tree_info) self.num_filing_cb.setEditable(True) self.num_filing_le = BookLineEdit(parent, index) self.num_filing_le.undoAvailable = True self.num_filing_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.num_filing_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.num_filing_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.num_filing_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.num_filing_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.num_filing_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.num_filing_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.num_filing_le.selectAll) self.num_filing_cb.setLineEdit(self.num_filing_le) self.num_filing_cm = QtWidgets.QCompleter(self) self.num_filing_sl = QtCore.QStringListModel(self) self.num_filing_cm.setModel(self.num_filing_sl) self.num_filing_cm.setCompletionRole(QtCore.Qt.EditRole) self.num_filing_sl.setStringList(sorted(self.num_filing_tree_info)) self.num_filing_cb.setCompleter(self.num_filing_cm) except Exception as err: return self.num_filing_cb return self.num_filing_cb elif index.column() == 3: #Fact self.num_fact_cb = QtWidgets.QComboBox(parent) self.num_fact_cb.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) try: self.current_cik = self.book_table_view.model().items[index.row()][0] self.current_period = self.book_table_view.model().items[index.row()][1] self.num_filing = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFiling(self.current_cik, self.current_period) self.num_fact_labels = set() for fact_item in self.num_filing.facts: if not BookFilingUtility.isAlphaOrHtml(fact_item): self.num_fact_labels.add(fact_item.label) self.num_fact_cb.addItems(sorted(list(self.num_fact_labels))) self.num_fact_cb.setEditable(True) self.num_fact_le = BookLineEdit(parent, index) self.num_fact_le.undoAvailable = True self.num_fact_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.num_fact_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.num_fact_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.num_fact_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.num_fact_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.num_fact_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.num_fact_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.num_fact_le.selectAll) self.num_fact_cb.setLineEdit(self.num_fact_le) self.num_fact_cm = QtWidgets.QCompleter(self) self.num_fact_sl = QtCore.QStringListModel(self) self.num_fact_cm.setModel(self.num_fact_sl) self.num_fact_cm.setCompletionRole(QtCore.Qt.EditRole) self.num_fact_sl.setStringList(sorted(list(self.num_fact_labels))) self.num_fact_cb.setCompleter(self.num_fact_cm) except: return self.num_fact_cb return self.num_fact_cb elif index.column() == 4: #Context self.num_con_cb = QtWidgets.QComboBox(parent) self.num_con_cb.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) try: self.current_cik = self.book_table_view.model().items[index.row()][0] self.current_period = self.book_table_view.model().items[index.row()][1] self.num_filing = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFiling(self.current_cik, self.current_period) self.current_fact_name = self.book_table_view.model().items[index.row()][5] self.num_fact_contexts = set() for fact_item in self.num_filing.facts: if fact_item.label == self.current_fact_name: self.num_fact_contexts.add(fact_item.context_ref) self.num_con_cb.addItems(sorted(list(self.num_fact_contexts))) self.num_con_cb.setEditable(True) self.num_con_le = BookLineEdit(parent, index) self.num_con_le.undoAvailable = True self.num_con_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.num_con_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.num_con_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.num_con_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.num_con_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.num_con_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.num_con_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.num_con_le.selectAll) self.num_con_cb.setLineEdit(self.num_con_le) self.num_con_cm = QtWidgets.QCompleter(self) self.num_con_sl = QtCore.QStringListModel(self) self.num_con_cm.setModel(self.num_fact_sl) self.num_con_cm.setCompletionRole(QtCore.Qt.EditRole) self.num_con_sl.setStringList(sorted(list(self.num_fact_contexts))) self.num_con_cb.setCompleter(self.num_con_cm) except: return self.num_con_cb return self.num_con_cb elif self.book_table_view.objectName() == "textualTableView": if index.column() == 0: #View self.tex_view_ch = QtWidgets.QCheckBox(parent) self.tex_view_ch.toggled.connect(self.book_table_view.refreshGraphic) return self.tex_view_ch elif index.column() == 1: #Entity self.tex_entity_cb = QtWidgets.QComboBox(parent) try: # cik, parent_cik, name self.tex_entity_tree_info = self.book_table_view.book_main_window.cntlr.book_filing_manager.getEntityTreeInfo() self.entity_list = [] for item in self.tex_entity_tree_info: self.entity_list.append(item[2]) self.tex_entity_cb.addItems(self.entity_list) self.tex_entity_cb.setEditable(True) self.tex_entity_le = BookLineEdit(parent, index) self.tex_entity_le.undoAvailable = True self.tex_entity_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.tex_entity_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.tex_entity_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.tex_entity_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.tex_entity_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.tex_entity_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.tex_entity_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.tex_entity_le.selectAll) self.tex_entity_cb.setLineEdit(self.tex_entity_le) self.tex_entity_cm = QtWidgets.QCompleter(self) self.tex_entity_sl = QtCore.QStringListModel(self) self.tex_entity_cm.setModel(self.tex_entity_sl) self.tex_entity_cm.setCompletionRole(QtCore.Qt.EditRole) self.tex_entity_sl.setStringList(sorted(self.entity_list)) self.tex_entity_cb.setCompleter(self.tex_entity_cm) except: return self.tex_entity_cb return self.tex_entity_cb elif index.column() == 2: #Filing self.tex_filing_cb = QtWidgets.QComboBox(parent) try: self.current_cik = self.book_table_view.model().items[index.row()][0] self.tex_filing_tree_info = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFilingTreeInfo(self.current_cik) self.tex_filing_cb.addItems(self.tex_filing_tree_info) self.tex_filing_cb.setEditable(True) self.tex_filing_le = BookLineEdit(parent, index) self.tex_filing_le.undoAvailable = True self.tex_filing_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.tex_filing_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.tex_filing_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.tex_filing_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.tex_filing_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.tex_filing_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.tex_filing_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.tex_filing_le.selectAll) self.tex_filing_cb.setLineEdit(self.tex_filing_le) self.tex_filing_cm = QtWidgets.QCompleter(self) self.tex_filing_sl = QtCore.QStringListModel(self) self.tex_filing_cm.setModel(self.tex_filing_sl) self.tex_filing_cm.setCompletionRole(QtCore.Qt.EditRole) self.tex_filing_sl.setStringList(sorted(self.tex_filing_tree_info)) self.tex_filing_cb.setCompleter(self.tex_filing_cm) except: return self.tex_filing_cb return self.tex_filing_cb elif index.column() == 3: #Fact self.tex_fact_cb = QtWidgets.QComboBox(parent) try: self.current_cik = self.book_table_view.model().items[index.row()][0] self.current_period = self.book_table_view.model().items[index.row()][1] self.tex_filing = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFiling(self.current_cik, self.current_period) self.tex_fact_labels = set() for fact_item in self.tex_filing.facts: if BookFilingUtility.isAlphaOrHtml(fact_item): self.tex_fact_labels.add(fact_item.label) self.tex_fact_cb.addItems(sorted(list(self.tex_fact_labels))) self.tex_fact_cb.setEditable(True) self.tex_fact_le = BookLineEdit(parent, index) self.tex_fact_le.undoAvailable = True self.tex_fact_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.tex_fact_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.tex_fact_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.tex_fact_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.tex_fact_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.tex_fact_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.tex_fact_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.tex_fact_le.selectAll) self.tex_fact_cb.setLineEdit(self.tex_fact_le) self.tex_fact_cm = QtWidgets.QCompleter(self) self.tex_fact_sl = QtCore.QStringListModel(self) self.tex_fact_cm.setModel(self.tex_fact_sl) self.tex_fact_cm.setCompletionRole(QtCore.Qt.EditRole) self.tex_fact_sl.setStringList(sorted(list(self.tex_fact_labels))) self.tex_fact_cb.setCompleter(self.tex_fact_cm) except: return self.tex_fact_cb return self.tex_fact_cb elif index.column() == 4: #Context self.tex_con_cb = QtWidgets.QComboBox(parent) try: self.current_cik = self.book_table_view.model().items[index.row()][0] self.current_period = self.book_table_view.model().items[index.row()][1] self.tex_filing = self.book_table_view.book_main_window.cntlr.book_filing_manager.getFiling(self.current_cik, self.current_period) self.current_fact_name = self.book_table_view.model().items[index.row()][5] self.tex_fact_contexts = set() for fact_item in self.tex_filing.facts: if fact_item.label == self.current_fact_name: self.tex_fact_contexts.add(fact_item.context_ref) self.tex_con_cb.addItems(sorted(list(self.tex_fact_contexts))) self.tex_con_cb.setEditable(True) self.tex_con_le = BookLineEdit(parent, index) self.tex_con_le.undoAvailable = True self.tex_con_le.redoAvailable = True self.book_table_view.book_main_window.actionUndo.triggered.connect(self.tex_con_le.undo) self.book_table_view.book_main_window.actionRedo.triggered.connect(self.tex_con_le.redo) self.book_table_view.book_main_window.actionCut.triggered.connect(self.tex_con_le.cut) self.book_table_view.book_main_window.actionCopy.triggered.connect(self.tex_con_le.copy) self.book_table_view.book_main_window.actionPaste.triggered.connect(self.tex_con_le.paste) self.book_table_view.book_main_window.actionDelete.triggered.connect(self.tex_con_le.backspace) self.book_table_view.book_main_window.actionSelectAll.triggered.connect(self.tex_con_le.selectAll) self.tex_con_cb.setLineEdit(self.tex_con_le) self.tex_con_cm = QtWidgets.QCompleter(self) self.tex_con_sl = QtCore.QStringListModel(self) self.tex_con_cm.setModel(self.tex_fact_sl) self.tex_con_cm.setCompletionRole(QtCore.Qt.EditRole) self.tex_con_sl.setStringList(sorted(list(self.tex_fact_contexts))) self.tex_con_cb.setCompleter(self.tex_con_cm) except: return self.tex_con_cb return self.tex_con_cb else: model_logger.error("{0}:BookTableViewDelegate:createEditor(): Invalid book_table_view.objectName()".format(str(datetime.datetime.now()))) def setEditorData(self, editor, index): if self.book_table_view.objectName() == "numericalTableView": if index.column() == 0: super().setEditorData(editor, index) elif index.column() == 1: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.num_entity_cb.findText(current_value) self.num_entity_cb.setCurrentIndex(current_index) elif index.column() == 2: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.num_filing_cb.findText(current_value) self.num_filing_cb.setCurrentIndex(current_index) elif index.column() == 3: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.num_fact_cb.findText(current_value) self.num_fact_cb.setCurrentIndex(current_index) elif index.column() == 4: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.num_con_cb.findText(current_value) self.num_con_cb.setCurrentIndex(current_index) elif self.book_table_view.objectName() == "textualTableView": if index.column() == 0: super().setEditorData(editor, index) elif index.column() == 1: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.tex_entity_cb.findText(current_value) self.tex_entity_cb.setCurrentIndex(current_index) elif index.column() == 2: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.tex_filing_cb.findText(current_value) self.tex_filing_cb.setCurrentIndex(current_index) elif index.column() == 3: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.tex_fact_cb.findText(current_value) self.tex_fact_cb.setCurrentIndex(current_index) elif index.column() == 4: current_value = str(index.data(QtCore.Qt.EditRole)) current_index = self.tex_con_cb.findText(current_value) self.tex_con_cb.setCurrentIndex(current_index) return else: model_logger.error("{0}:BookTableViewDelegate:createEditor(): Invalid book_table_view.objectName()".format(str(datetime.datetime.now()))) def setModelData(self, editor, model, index): if self.book_table_view.objectName() == "numericalTableView": if index.column() == 0: model.setData(index, editor.isChecked(), QtCore.Qt.EditRole) elif index.column() in (1, 2, 3, 4): model.setData(index, editor.currentText(), QtCore.Qt.EditRole) elif self.book_table_view.objectName() == "textualTableView": if index.column() == 0: model.setData(index, editor.isChecked(), QtCore.Qt.EditRole) elif index.column() in (1, 2, 3, 4): model.setData(index, editor.currentText(), QtCore.Qt.EditRole) else: model_logger.error("{0}:BookTableViewDelegate:createEditor(): Invalid book_table_view.objectName()".format(str(datetime.datetime.now()))) return def updateEditorGeometry(self, editor, option, index): QtWidgets.QStyledItemDelegate.updateEditorGeometry(self, editor, option, index) return
54.562848
150
0.628129
a9f49e1c8623071a295d17dbec4e8eb534a3a29d
2,391
php
PHP
src/views/dashboard/layouts/header.blade.php
majazeh/dashboard
3d0deaff1cba6279823d0883d41234d831b59354
[ "MIT" ]
null
null
null
src/views/dashboard/layouts/header.blade.php
majazeh/dashboard
3d0deaff1cba6279823d0883d41234d831b59354
[ "MIT" ]
1
2019-01-26T09:35:21.000Z
2019-01-26T09:35:21.000Z
src/views/dashboard/layouts/header.blade.php
majazeh/dashboard
3d0deaff1cba6279823d0883d41234d831b59354
[ "MIT" ]
1
2022-03-22T12:46:43.000Z
2022-03-22T12:46:43.000Z
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> @section('header-styles') <link rel="stylesheet" type="text/css" href="{{ asset('vendors/bootstrap-4.2.1/css/bootstrap.min.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('vendors/bootstrap4-rtl/bootstrap4-rtl.min.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('vendors/fontawesome-pro-5.7.1/css/all.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('vendors/iziToast/css/iziToast.min.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('vendors/select2/select2.min.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('vendors/Date-Time-Picker-Bootstrap-4/css/bootstrap-datetimepicker.min.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('css/dashio.min.css') . '?v=' . filemtime(public_path('css/dashio.min.css')) }}"> <link rel="stylesheet" type="text/css" href="{{ asset('css/main.css') . '?v=' . filemtime(public_path('css/main.css')) }}"> @if (file_exists(public_path('favicon.ico'))) <link rel="icon" href="{{ asset('favicon.ico') }}?v={{ filemtime(public_path('favicon.ico')) }}" type="image/x-icon" /> @endif @if (file_exists(public_path('apple-touch-icon.png'))) <link rel="apple-touch-icon" sizes="180x180" href="{{ asset('apple-touch-icon.png') }}?v={{ filemtime(public_path('apple-touch-icon.png')) }}"> @endif @if (file_exists(public_path('favicon-32x32.png'))) <link rel="icon" type="image/png" sizes="32x32" href="{{ asset('favicon-32x32.png') }}?v={{ filemtime(public_path('favicon-32x32.png')) }}"> @endif @if (file_exists(public_path('favicon-16x16.png'))) <link rel="icon" type="image/png" sizes="16x16" href="{{ asset('favicon-16x16.png') }}?v={{ filemtime(public_path('favicon-16x16.png')) }}"> @endif @if (file_exists(public_path('site.webmanifest'))) <link rel="manifest" href="/site.webmanifest"> @endif @if (file_exists(public_path('safari-pinned-tab.svg'))) <link rel="mask-icon" href="{{ asset('safari-pinned-tab.svg') }}?v={{ filemtime(public_path('safari-pinned-tab.svg')) }}" color="#ffde00"> @endif <meta name="msapplication-TileColor" content="#ffde00"> <meta name="theme-color" content="#ffde00"> @show <title>{{ $global->title ?: _d('Dashio') }}</title>
56.928571
145
0.672104
26fa28d7789e8405f4e383c6b5d2ed142b08bda8
8,061
asm
Assembly
source/modules/basic/commands/list.asm
paulscottrobson/mega-basic
f71750889136e2fdc4e6053c5696593318162bcf
[ "MIT" ]
3
2019-12-03T06:05:24.000Z
2021-03-24T01:51:07.000Z
source/modules/basic/commands/list.asm
paulscottrobson/mega-basic
f71750889136e2fdc4e6053c5696593318162bcf
[ "MIT" ]
null
null
null
source/modules/basic/commands/list.asm
paulscottrobson/mega-basic
f71750889136e2fdc4e6053c5696593318162bcf
[ "MIT" ]
null
null
null
; ******************************************************************************************* ; ******************************************************************************************* ; ; Name : list.asm ; Purpose : LIST Command ; Date : 29th August 2019 ; Author : Paul Robson ([email protected]) ; ; ******************************************************************************************* ; ******************************************************************************************* Command_LIST: ;; list jsr ListGetRange ; get any parameters #s_toStart BasicProgram ; start of program lda #0 ; reset the indent & last indent sta LastListIndent sta ListIndent _CILLoop: #s_startLine ; start of line #s_get ; read offset cmp #0 ; if zero, end of program beq _CILExit jsr VIOCheckBreak ; check break cmp #0 bne _CILExit jsr ListCheckRange ; check current line in range. bcs _CILNext #s_startLine ; move to start #s_next #s_next #s_next ; jsr ListLine ; list one line. ; _CILNext: #s_nextline ; go to next bra _CILLoop _CILExit: jmp WarmStart ; ******************************************************************************************* ; ; List current line ; ; ******************************************************************************************* ListLine: lda ListIndent ; copy current list indent -> last sta LastListIndent _LICountIndent: ; indent of current line. #s_get cmp #0 beq _LIDoneIndent cmp #firstKeywordPlus bcc _LICINext cmp #firstUnaryFunction bcs _LICINext inc ListIndent cmp #firstKeywordMinus bcc _LICINext dec ListIndent dec ListIndent bpl _LICINext inc ListIndent _LICINext: #s_skipelement ; skip to next element. bra _LICountIndent _LIDoneIndent: #s_startLine ; get line# into low 1st mantissa #s_next #s_get sta XS_Mantissa #s_next #s_get sta XS_Mantissa+1 jsr Print16BitInteger ; print integer. sta zTemp1 ; save spaces printed. lda ListIndent ; smaller of current/prev indent cmp LastListIndent bcc _LISmaller lda LastListIndent _LISmaller: asl a ; double indent eor #$FF ; 2's complement arithmetic sec adc zTemp1 ; "subtract" indent e.g. print more. tax ; print spaces to column 6 _LISpace: lda #" " jsr ListPrintLC inx cpx #6 bne _LISpace ; ; Main decode loop ; _LIDecode: #s_next ; next character #s_get cmp #0 ; zero, exit. beq _LIExit bmi _LIToken cmp #$40 ; 01-$3F, character. bcs _LIInteger eor #$20 ; make 7 bit adc #$20 jsr ListPrintLC ; print in LC bra _LIDecode _LIExit: lda #13 ; print new line. jmp ListPrintLC ; ; Handle $FC-$FF (strings, remarks, decimals.) ; _LIToken: cmp #$FC ; $FC-$FF ? bcc _LICommandToken ; pha ; save in case end ldx #'"' ; print if $FE quoted string cmp #$FE beq _LIPrint ldx #'.' ; print if $FD decimals cmp #$FD beq _LIPrint lda #'R' ; must be REM jsr ListPrintLC lda #'E' jsr ListPrintLC lda #'M' jsr ListPrintLC ldx #' ' _LIPrint: txa jsr ListPrintLC #s_next ; length (overall, e.g. +2) #s_get tax ; put in X dex _LILoop: dex ; exit when count reached zero. beq _LIEnd #s_next ; get and print #s_get jsr ListPrintLC bra _LILoop ; _LIEnd: pla ; get A back cmp #$FE ; if '"' need closing quotes bne _LIDecode lda #'"' jsr ListPrintLC bra _LIDecode ; _LIInteger: ldx #0 jsr EvaluateGetInteger ; get an atom #s_prev ; because we pre-increment on the loop jsr Print32BitInteger ; print integer. bra _LIDecode ; ; Handle a command token. This only handles 80-FF tokens, so needs extending ; for shifts. Change initial value for shifts ; _LICommandToken: phy ; save Y pha ; save token ldx #KeywordText & $FF ; address of keyword text table. lda (#KeywordText >> 8) & $FF stx zLTemp1 sta zLTemp1+1 lda (#KeywordText >> 16) & $FF ; this is for 65816 (it's a table in code sta zLTemp1+2 ; space) and won't affect a 6502 at all. ; pla ; get token and #127 ; chuck bit 7. beq _LIFoundToken tax _LITokenLoop: ; if alpha token, then print space if ldy #0 ; last character not a token. _LIFindEnd: .if cpu=="65816" ; find end next token lda [zLTemp1],y .else lda (zLTemp1),y .endif iny asl a bcc _LIFindEnd ; tya ; that is step to the next clc ; we don't bother bumping the 3rd byte adc zLTemp1 ; here. sta zLTemp1 bcc _LINoBump inc zLTemp1+1 _LINoBump: ; done the lot ? dex ; no go round again. bne _LITokenLoop _LIFoundToken: ldy #0 _LIPrintToken: .if cpu=="65816" ; get next token lda [zLTemp1],y .else lda (zLTemp1),y .endif cpy #0 ; see if needs prefix space bne _LINoPrefixSpace cmp #"A" ; e.g. alphabetic token. bcc _LINoPrefixSpace cmp #"Z"+1 bcs _LINoPrefixSpace ldx LastPrinted ; if last was space not required cpx #" " beq _LINoPrefixSpace pha lda #" " jsr ListPrintLC pla _LINoPrefixSpace: iny pha ; save it and #$7F jsr ListPrintLC pla bpl _LIPrintToken ; go back if not end ply ; restore Y and #$7F ; if last char is a letter cmp #"A" bcc _LINotLetter2 cmp #"Z"+1 bcs _LINotLetter2 lda #" " ; add spacing jsr ListPrintLC _LINotLetter2: jmp _LIDecode ; ; Print A in L/C ; note the interface makes it U/C again in the emulator ;-) ; ListPrintLC: sta LastPrinted cmp #"A" bcc _LPLC0 cmp #"Z"+1 bcs _LPLC0 adc #$20 _LPLC0: jmp VIOCharPrint ; ******************************************************************************************* ; ; Get the range in Mantissa/Mantissa+6 ; ; ******************************************************************************************* ListGetRange: ldx #XS_Size*2-1 ; clear first 2 slots back to defaults. _LGRClear: lda #0 sta XS_Mantissa,x dex bpl _LGRClear #s_get ; value present ? cmp #0 ; nothing beq _LGRBlank cmp #token_Colon ; or colon beq _LGRBlank cmp #token_Comma ; comma beq _LGREnd ; then it's LIST ,x jsr EvaluateInteger ; get the first number into bottom #s_get ; if - follows that cmp #token_Comma beq _LGREnd ; then it is LIST a,b ; lda XS_Mantissa+0 ; copy first to second LIST n is n,n sta XS_Mantissa+XS_Size+0 lda XS_Mantissa+1 sta XS_Mantissa+XS_Size+1 ; _LGRBumpExit: inc XS_Mantissa+XS_Size ; bump it so we can use cc. bne _LGRBump2 inc XS_Mantissa+XS_Size+1 _LGRBump2: rts _LGREnd: #s_next ; skip the minus. _LGRBlank: lda #$FF ; default to the end. sta XS_Mantissa+XS_Size sta XS_Mantissa+XS_Size+1 #s_get ; what's next ? cmp #0 beq _LGRBump2 asl a ; if not a number, then exit (to end) bcs _LGRBump2 ldx #XS_Size ; get to range jsr EvaluateIntegerX bra _LGRBumpExit rts ; ******************************************************************************************* ; ; Return CC if list in range of mantissa,mantissa+size ; ; ******************************************************************************************* ListCheckRange: #s_next ; point to line number low ldx #0 ; test low jsr _LCRCompare bcc _LCRFail ldx #XS_Size ; test high jsr _LCRCompare rts _LCRFail: sec rts _LCRCompare: ; compare line number vs mantissa,X #s_get sec sbc XS_Mantissa+0,x php #s_next #s_get plp sbc XS_Mantissa+1,x php #s_prev plp rts
23.919881
93
0.539511
9fff058b8cd298446bd992e9f3cf5abd6427ebd4
2,888
py
Python
calvin/runtime/south/calvinlib/mathlib/Arithmetic.py
gabrielcercel/calvin-base
c0315f100643230d65aed1745e1c22df3e7a7c2c
[ "Apache-2.0" ]
334
2015-06-04T15:14:28.000Z
2022-02-09T11:14:17.000Z
calvin/runtime/south/calvinlib/mathlib/Arithmetic.py
gabrielcercel/calvin-base
c0315f100643230d65aed1745e1c22df3e7a7c2c
[ "Apache-2.0" ]
89
2015-06-13T19:15:35.000Z
2019-12-03T19:23:20.000Z
calvin/runtime/south/calvinlib/mathlib/Arithmetic.py
gabrielcercel/calvin-base
c0315f100643230d65aed1745e1c22df3e7a7c2c
[ "Apache-2.0" ]
112
2015-06-06T19:16:54.000Z
2020-10-19T01:27:55.000Z
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from calvin.runtime.south.calvinlib import base_calvinlib_object from calvin.utilities.calvinlogger import get_logger import operator _log = get_logger(__name__) class Arithmetic(base_calvinlib_object.BaseCalvinlibObject): """ Operations on numbers """ init_schema = { "description": "Initialize module", } relation_schema = { "description": "Get corresponding relation: >, <, =, !=, >=, <= (with obvious interpretation.)", "type": "object", "properties": { "rel": { "type": "string" } } } operator_schema = { "description": "Get corresponding operator: +, -, /, *, div, mod (with obvious interpretation.)", "type": "object", "properties": { "op": { "type": "string" } } } eval_schema = { "description": "Evaluate expression, returning result. Bindings should be a dictionary of variable mappings to use in evaluation", "type": "object", "properties": { "expr": { "type": "string" }, "bindings": { "type": "object" } } } def init(self): pass def relation(self, rel): try: return { '<': operator.lt, '<=': operator.le, '=': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operator.gt, }[rel] except KeyError: _log.warning("Invalid operator '{}', will always return 'false'".format(rel)) return lambda x,y: False def operator(self, op): try: return { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div, 'div': operator.floordiv, 'mod': operator.mod, }[op] except KeyError: _log.warning("Invalid operator '{}', will always produce 'null'".format(op)) return lambda x,y: None def eval(self, expr, bindings): try: return eval(expr, {}, bindings) except Exception as e: return str(e)
30.4
138
0.538435
385788c9c6a3b23118ae93e1e00aa2a6e37efe0e
132
php
PHP
Modules/Core/Contracts/ImageResizeContract.php
RomanLev4yk/laravue
744b2575ddc61247424c9dade2fdedc51d293088
[ "MIT" ]
null
null
null
Modules/Core/Contracts/ImageResizeContract.php
RomanLev4yk/laravue
744b2575ddc61247424c9dade2fdedc51d293088
[ "MIT" ]
3
2021-02-03T02:08:54.000Z
2022-02-19T05:52:49.000Z
Modules/Core/Contracts/ImageResizeContract.php
RomanLev4yk/laravue
744b2575ddc61247424c9dade2fdedc51d293088
[ "MIT" ]
null
null
null
<?php namespace Modules\Core\Contracts; interface ImageResizeContract { public function imageResize($file, $width, $heigh); }
14.666667
55
0.75
25a0dc5a414840d546f7b36f6c0e3425f83c7f3f
1,031
cs
C#
Music Player/ListBoxItem.cs
Arkedrille/IntelPlayer
34dec2131a8ee601378331df001ee985f664a5c0
[ "MIT" ]
null
null
null
Music Player/ListBoxItem.cs
Arkedrille/IntelPlayer
34dec2131a8ee601378331df001ee985f664a5c0
[ "MIT" ]
null
null
null
Music Player/ListBoxItem.cs
Arkedrille/IntelPlayer
34dec2131a8ee601378331df001ee985f664a5c0
[ "MIT" ]
null
null
null
using System; namespace Music_Player { public class ListBoxItem : Object { public virtual string Text { get; set; } public virtual object Object { get; set; } public virtual string Name { get; set; } public virtual string Path { get; set; } public ListBoxItem() { this.Text = string.Empty; this.Name = string.Empty; this.Path = string.Empty; this.Object = null; } public ListBoxItem(string Text, string Name, object Object, string Path) { this.Text = Text; this.Name = Name; this.Path = Path; this.Object = Object; } public ListBoxItem(object Object) { this.Text = Object.ToString(); this.Name = Object.ToString(); this.Object = Object; this.Path = Object.ToString(); } public override string ToString() { return this.Text; } } }
28.638889
83
0.514064
f989066abf6fb8e74ca2a4a66a0865010f8d57b4
7,550
sql
SQL
php_10.sql
csegue/nivel-10-beta
a25ed4da2119c96306111029edce3f8bac297ea4
[ "MIT" ]
null
null
null
php_10.sql
csegue/nivel-10-beta
a25ed4da2119c96306111029edce3f8bac297ea4
[ "MIT" ]
null
null
null
php_10.sql
csegue/nivel-10-beta
a25ed4da2119c96306111029edce3f8bac297ea4
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 06-10-2021 a las 18:42:51 -- Versión del servidor: 10.4.20-MariaDB -- Versión de PHP: 8.0.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `php_10` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `catalogos` -- CREATE TABLE `catalogos` ( `id` bigint(20) UNSIGNED NOT NULL, `titulo` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `autor` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `genero` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `catalogos` -- INSERT INTO `catalogos` (`id`, `titulo`, `autor`, `genero`, `created_at`, `updated_at`) VALUES (1, 'Curso Laravel 8', 'ITAcademy', 'Informatica Fullstack', '2021-09-23 08:51:04', '2021-09-30 08:39:42'), (2, 'Africanus', 'Santiago Posteguillo', 'Ficción/historia', '2021-09-23 08:51:04', '2021-09-23 08:51:04'), (3, 'Julia Navarro', 'De ninguna parte', 'Ficción', '2021-09-23 08:51:04', '2021-09-23 08:51:04'), (4, 'Los vencejos', 'Fernando Aramburu', 'Acción', '2021-09-23 12:42:25', '2021-09-24 04:57:07'), (5, 'Sira', 'María Dueñas', 'Amor', '2021-09-23 12:49:29', '2021-09-25 15:06:17'), (6, 'Nada', 'Carmen Laforet', 'Ficción', '2021-09-23 12:56:08', '2021-10-02 19:51:41'), (17, 'Caperucita roja', 'El Lobo', 'Terror infantil', '2021-09-30 09:22:52', '2021-09-30 09:22:52'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (6, '2014_10_12_000000_create_users_table', 1), (7, '2014_10_12_100000_create_password_resets_table', 1), (8, '2019_08_19_000000_create_failed_jobs_table', 1), (9, '2019_12_14_000001_create_personal_access_tokens_table', 1), (10, '2021_09_23_100018_create_catalogos_table', 1), (11, '2021_09_28_101235_create_roles_table', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `personal_access_tokens` -- CREATE TABLE `personal_access_tokens` ( `id` bigint(20) UNSIGNED NOT NULL, `tokenable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `tokenable_id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL, `abilities` text COLLATE utf8mb4_unicode_ci DEFAULT NULL, `last_used_at` timestamp NULL DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `role_id` int(11) DEFAULT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `users` -- INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `role_id`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'Carlos', '[email protected]', NULL, '$2y$10$TcTjZf1RRObybxxIU4y6KeiMgmx1vMVaEy/NoGKhUBO4TazLwq4oy', 1, 'zZMyHbgRJav7a93CBXqVFpwtAU8Zm0FqLy2zxgp580xHGpARPjfUEw5b1wKw', '2021-09-28 08:42:03', '2021-09-30 03:47:04'), (2, 'Maribel', '[email protected]', NULL, '$2y$10$WjmEX9.Z6vUR9NO49/BmguJatpL1wKGJ/i.BkBoVumgLsUZsh26Ge', 2, NULL, '2021-09-28 13:28:02', '2021-09-28 13:28:02'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `catalogos` -- ALTER TABLE `catalogos` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`); -- -- Indices de la tabla `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indices de la tabla `personal_access_tokens` -- ALTER TABLE `personal_access_tokens` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `personal_access_tokens_token_unique` (`token`), ADD KEY `personal_access_tokens_tokenable_type_tokenable_id_index` (`tokenable_type`,`tokenable_id`); -- -- Indices de la tabla `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `catalogos` -- ALTER TABLE `catalogos` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; -- -- AUTO_INCREMENT de la tabla `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT de la tabla `personal_access_tokens` -- ALTER TABLE `personal_access_tokens` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
32.826087
219
0.700795
f3d1d0661aa6d0a975529053a34d9ddd21a849f8
4,029
rs
Rust
fruity_editor/src/editor_component_service.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
[ "MIT" ]
null
null
null
fruity_editor/src/editor_component_service.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
[ "MIT" ]
null
null
null
fruity_editor/src/editor_component_service.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
[ "MIT" ]
null
null
null
use crate::components::fields::edit_introspect_fields; use crate::ui_element::UIElement; use fruity_any::*; use fruity_core::introspect::FieldInfo; use fruity_core::introspect::IntrospectObject; use fruity_core::introspect::MethodInfo; use fruity_core::object_factory_service::ObjectFactoryService; use fruity_core::resource::resource::Resource; use fruity_core::resource::resource_container::ResourceContainer; use fruity_core::resource::resource_reference::ResourceReference; use fruity_core::serialize::serialized::Serialized; use fruity_ecs::component::component::AnyComponent; use fruity_ecs::component::component_reference::ComponentReference; use std::collections::HashMap; use std::fmt::Debug; use std::sync::Arc; lazy_static! { pub static ref DEFAULT_INSPECTOR: Arc<dyn Fn(ComponentReference) -> UIElement + Send + Sync> = Arc::new(|component| edit_introspect_fields(Box::new(component))); } #[derive(FruityAny)] pub struct RegisterComponentParams { pub inspector: Arc<dyn Fn(ComponentReference) -> UIElement + Send + Sync>, pub dependencies: Vec<String>, } impl Default for RegisterComponentParams { fn default() -> Self { Self { inspector: DEFAULT_INSPECTOR.clone(), dependencies: Vec::new(), } } } #[derive(FruityAny)] pub struct EditorComponentService { components: HashMap<String, RegisterComponentParams>, object_factory_service: ResourceReference<ObjectFactoryService>, } impl EditorComponentService { pub fn new(resource_container: Arc<ResourceContainer>) -> Self { Self { components: HashMap::new(), object_factory_service: resource_container.require::<ObjectFactoryService>(), } } pub fn register_component( &mut self, component_identifier: &str, params: RegisterComponentParams, ) { self.components .insert(component_identifier.to_string(), params); } pub fn inspect(&self, component: ComponentReference) -> UIElement { let component_identifier = component.get_class_name(); match self.components.get(&component_identifier) { Some(params) => (params.inspector)(component), None => edit_introspect_fields(Box::new(component)), } } pub fn instantiate(&self, component_identifier: &str) -> Option<Vec<AnyComponent>> { let object_factory_service = self.object_factory_service.read(); let component_params = self.components.get(component_identifier)?; let instance = object_factory_service.instantiate(component_identifier, vec![])?; let instance = if let Serialized::NativeObject(instance) = instance { instance } else { return None; }; let instance = instance.as_any_box().downcast::<AnyComponent>().ok()?; let mut result = vec![*instance]; let mut dependencies = component_params .dependencies .iter() .filter_map(|dependency| self.instantiate(dependency)) .flatten() .collect::<Vec<_>>(); result.append(&mut dependencies); Some(result) } pub fn search(&self, search: &str) -> impl Iterator<Item = String> + '_ { let search = search.to_string(); self.components .keys() .filter(move |key| key.to_lowercase().contains(&search.to_lowercase())) .map(|key| key.clone()) } } impl Debug for EditorComponentService { fn fmt( &self, _formatter: &mut std::fmt::Formatter<'_>, ) -> std::result::Result<(), std::fmt::Error> { Ok(()) } } // TODO: Complete that impl IntrospectObject for EditorComponentService { fn get_class_name(&self) -> String { "EditorComponentService".to_string() } fn get_method_infos(&self) -> Vec<MethodInfo> { vec![] } fn get_field_infos(&self) -> Vec<FieldInfo> { vec![] } } impl Resource for EditorComponentService {}
31.724409
98
0.659965
5ef619423819e989854528f971b1516e79170cac
943
php
PHP
app/Manage/Operation/AbstractOperation.php
dashingunique/train-carbon
1e3983ab82ef6c788b3d7e08053f681331832db2
[ "MIT" ]
null
null
null
app/Manage/Operation/AbstractOperation.php
dashingunique/train-carbon
1e3983ab82ef6c788b3d7e08053f681331832db2
[ "MIT" ]
null
null
null
app/Manage/Operation/AbstractOperation.php
dashingunique/train-carbon
1e3983ab82ef6c788b3d7e08053f681331832db2
[ "MIT" ]
null
null
null
<?php /** * File AbstractOperation.php * @description * @author liqilin */ namespace App\Manage\Operation; use App\Contracts\OperationInterface; use App\Manage\Personnel\AbstractPersonnel; use App\Models\Carbon; use App\Models\SubwayPosition; abstract class AbstractOperation implements OperationInterface { protected $name; /** * 操作人员 * @var AbstractPersonnel */ protected $personnel; /** * @var SubwayPosition */ protected $position; /** * @var Carbon */ protected $carbon; /** * AbstractOperation constructor. * @param AbstractPersonnel $personnel * @param SubwayPosition $position * @param Carbon $carbon */ public function __construct(AbstractPersonnel $personnel, SubwayPosition $position, Carbon $carbon) { $this->personnel = $personnel; $this->position = $position; $this->carbon = $carbon; } }
19.244898
103
0.646872
5722890865f86ab9076eca6310b2c74cd0526735
64
js
JavaScript
src/config/jwt-config.js
randyou/address-book-app
7f208238caf9299f2b611cf975692bf8cedd167d
[ "MIT" ]
null
null
null
src/config/jwt-config.js
randyou/address-book-app
7f208238caf9299f2b611cf975692bf8cedd167d
[ "MIT" ]
null
null
null
src/config/jwt-config.js
randyou/address-book-app
7f208238caf9299f2b611cf975692bf8cedd167d
[ "MIT" ]
null
null
null
'use strict' export default { secret: 'fghfgjh546fdgghghj' }
10.666667
30
0.71875
709f42b72e64ce4c22e9b39c26f792862f541d83
1,670
css
CSS
CSS3_30_days/ModernLayouts/sandbox.css
srijanss/365_day_challenge
59209b788742cf3c8ecdfa7647d43a48d9a165a8
[ "MIT" ]
null
null
null
CSS3_30_days/ModernLayouts/sandbox.css
srijanss/365_day_challenge
59209b788742cf3c8ecdfa7647d43a48d9a165a8
[ "MIT" ]
4
2020-06-17T03:38:59.000Z
2022-02-27T06:37:51.000Z
CSS3_30_days/ModernLayouts/sandbox.css
srijanss/365_day_challenge
59209b788742cf3c8ecdfa7647d43a48d9a165a8
[ "MIT" ]
null
null
null
/* ======================================== CODE YOUR STYLES BELOW! ====================================== */ .layout1 article { width: 58%; float: left; } .layout1 aside { width: 40%; float: right; } /* simple clearfix for sibling element*/ .layout1 footer { clear: both; } .layout2 header .logo { width: 20%; float: left; margin: 0; } .layout2 header nav { width: 78%; float: right; margin: 0; } /* simple clearfix for parent element*/ .layout2 header::after { display: table; content: ""; clear: both; } .layout2 article { width: 50%; margin-left: 2%; float: left; } .layout2 aside.sidenav { width: 23%; float: left; } .layout2 aside.sidebar { width: 23%; float: right; } /* simple clearfix for sibling element*/ .layout2 footer { clear: both; } .layout3 header .logo { width: 20%; float: right; margin: 0; } .layout3 header nav { width: 78%; float: left; margin: 0; } .layout3 header::after { display: table; content: ""; clear: both; } .layout3 article { width: 32%; float: left; margin: 0 2% 0 0; } /* clear maring of last element to fit within layout*/ .layout3 article:last-child { margin: 0; } .layout3 .articles::after { display: table; content: ""; clear: both; } /* simple media queries for responsive layouts */ @media screen and (max-width: 768px) { .layout1 article, .layout1 aside, .layout2 header .logo, .layout2 header nav, .layout2 article, .layout2 aside.sidenav, .layout2 aside.sidebar, .layout3 article, .layout3 aside, .layout3 header .logo, .layout3 header nav { float: none; width: 100%; margin: 0 0 2%; } }
14.649123
54
0.597605
a3dd4647d52b8bf5f64866956212951aad1e2fc0
14,234
java
Java
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/DeveloperResourceImpl.java
shachindrasingh/apiman
de3266f29b6c3436e8aa7e0e33b03800ac967837
[ "Apache-2.0" ]
711
2015-01-13T04:56:18.000Z
2022-03-15T11:22:03.000Z
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/DeveloperResourceImpl.java
shachindrasingh/apiman
de3266f29b6c3436e8aa7e0e33b03800ac967837
[ "Apache-2.0" ]
1,148
2015-01-23T12:29:02.000Z
2022-03-31T18:59:54.000Z
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/DeveloperResourceImpl.java
shachindrasingh/apiman
de3266f29b6c3436e8aa7e0e33b03800ac967837
[ "Apache-2.0" ]
405
2015-01-09T17:03:25.000Z
2022-03-25T02:07:41.000Z
/* * Copyright 2020 Scheer PAS Schweiz AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.manager.api.rest.impl; import io.apiman.common.logging.ApimanLoggerFactory; import io.apiman.common.logging.IApimanLogger; import io.apiman.manager.api.beans.apis.ApiVersionBean; import io.apiman.manager.api.beans.developers.DeveloperBean; import io.apiman.manager.api.beans.developers.DeveloperMappingBean; import io.apiman.manager.api.beans.developers.UpdateDeveloperBean; import io.apiman.manager.api.beans.summary.ClientVersionSummaryBean; import io.apiman.manager.api.beans.summary.ContractSummaryBean; import io.apiman.manager.api.core.IStorage; import io.apiman.manager.api.core.IStorageQuery; import io.apiman.manager.api.core.exceptions.StorageException; import io.apiman.manager.api.gateway.IGatewayLinkFactory; import io.apiman.manager.api.rest.IDeveloperResource; import io.apiman.manager.api.rest.exceptions.DeveloperAlreadyExistsException; import io.apiman.manager.api.rest.exceptions.DeveloperNotFoundException; import io.apiman.manager.api.rest.exceptions.InvalidNameException; import io.apiman.manager.api.rest.exceptions.NotAuthorizedException; import io.apiman.manager.api.rest.exceptions.SystemErrorException; import io.apiman.manager.api.rest.exceptions.util.ExceptionFactory; import io.apiman.manager.api.security.ISecurityContext; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.ws.rs.core.Response; /** * Implementation of the Developer Portal API */ public class DeveloperResourceImpl implements IDeveloperResource { private final IApimanLogger log = ApimanLoggerFactory.getLogger(DeveloperResourceImpl.class); @Inject IStorage storage; @Inject IStorageQuery query; @Inject ISecurityContext securityContext; @Inject IGatewayLinkFactory gatewayLinkFactory; private OrganizationResourceImpl organizationResource; /** * Constructor */ public DeveloperResourceImpl() { } @Override public List<ApiVersionBean> getAllPublicApiVersions() throws NotAuthorizedException { List<ApiVersionBean> apiVersionBeans = new ArrayList<>(); Iterator<ApiVersionBean> iterator; try { storage.beginTx(); iterator = storage.getAllPublicApiVersions(); storage.commitTx(); while (iterator.hasNext()) { ApiVersionBean apiVersionBean = iterator.next(); apiVersionBeans.add(apiVersionBean); } } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return apiVersionBeans; } /** * @see IDeveloperResource#getDevelopers() */ @Override public List<DeveloperBean> getDevelopers() throws NotAuthorizedException { securityContext.checkAdminPermissions(); Iterator<DeveloperBean> iterator; List<DeveloperBean> developerBeans = new ArrayList<>(); try { storage.beginTx(); iterator = storage.getDevelopers(); storage.commitTx(); while (iterator.hasNext()) { DeveloperBean bean = iterator.next(); developerBeans.add(bean); } } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return developerBeans; } /** * @see IDeveloperResource#create(DeveloperBean) */ @Override public DeveloperBean create(DeveloperBean bean) throws InvalidNameException, NotAuthorizedException, DeveloperAlreadyExistsException { securityContext.checkAdminPermissions(); DeveloperBean developerBean = new DeveloperBean(); developerBean.setId(bean.getId()); developerBean.setClients(bean.getClients()); try { storage.beginTx(); if (storage.getDeveloper(bean.getId()) != null) { throw ExceptionFactory.developerAlreadyExistsException(bean.getId()); } storage.createDeveloper(developerBean); storage.commitTx(); log.debug(String.format("Created developer %s: %s", developerBean.getId(), developerBean)); //$NON-NLS-1$ } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return developerBean; } /** * @see IDeveloperResource#update(String, UpdateDeveloperBean) */ @Override public void update(String id, UpdateDeveloperBean bean) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkAdminPermissions(); try { storage.beginTx(); DeveloperBean developerBean = getDeveloperBeanFromStorage(id); developerBean.setClients(bean.getClients()); storage.updateDeveloper(developerBean); storage.commitTx(); log.debug(String.format("Updated developer %s: %s", developerBean.getId(), developerBean)); } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } } /** * @see IDeveloperResource#get(String) */ @Override public DeveloperBean get(String id) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkAdminPermissions(); DeveloperBean developerBean; try { storage.beginTx(); developerBean = getDeveloperBeanFromStorage(id); storage.commitTx(); log.debug(String.format("Got developer %s: %s", developerBean.getId(), developerBean)); } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return developerBean; } /** * Gets the developer from storage * A transaction must be present * * @param id the id of the developer * @return the developer * @throws StorageException if something unexpected happens * @throws DeveloperNotFoundException when trying to get, update, or delete an organization that does not exist */ private DeveloperBean getDeveloperBeanFromStorage(String id) throws StorageException, DeveloperNotFoundException { DeveloperBean developerBean = storage.getDeveloper(id); if (developerBean == null) { throw ExceptionFactory.developerNotFoundException(id); } return developerBean; } /** * @see IDeveloperResource#delete(String) */ @Override public void delete(String id) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkAdminPermissions(); try { storage.beginTx(); DeveloperBean developerBean = getDeveloperBeanFromStorage(id); storage.deleteDeveloper(developerBean); storage.commitTx(); log.debug("Deleted developer: " + developerBean.getId()); //$NON-NLS-1$ } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } } /** * @see IDeveloperResource#getAllApiVersions(String) */ @Override public List<ClientVersionSummaryBean> getAllClientVersions(String id) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkIfUserIsCurrentUser(id); DeveloperBean developer; List<ClientVersionSummaryBean> clientVersionSummaryBeans; try { storage.beginTx(); developer = getDeveloperBeanFromStorage(id); storage.commitTx(); clientVersionSummaryBeans = queryMatchingClientVersions(developer); } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return clientVersionSummaryBeans; } /** * Queries all matching client versions to the corresponding developer * * @param developer the developer * @return a list of ClientVersionSummaryBeans * @throws StorageException if something unexpected happens */ private List<ClientVersionSummaryBean> queryMatchingClientVersions(DeveloperBean developer) throws StorageException { List<ClientVersionSummaryBean> clientVersionSummaryBeans = new ArrayList<>(); Set<DeveloperMappingBean> developerMappingBeans = developer.getClients(); for (DeveloperMappingBean bean : developerMappingBeans) { List<ClientVersionSummaryBean> allClientVersionsList = query.getClientVersions(bean.getOrganizationId(), bean.getClientId()); clientVersionSummaryBeans.addAll(allClientVersionsList); } return clientVersionSummaryBeans; } /** * @see IDeveloperResource#getAllClientContracts(String) */ @Override public List<ContractSummaryBean> getAllClientContracts(String id) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkIfUserIsCurrentUser(id); DeveloperBean developer; List<ClientVersionSummaryBean> clientVersionSummaryBeans; List<ContractSummaryBean> contractSummaryBeans = new ArrayList<>(); try { storage.beginTx(); developer = getDeveloperBeanFromStorage(id); storage.commitTx(); clientVersionSummaryBeans = queryMatchingClientVersions(developer); for (ClientVersionSummaryBean bean : clientVersionSummaryBeans) { List<ContractSummaryBean> allClientContracts = query.getClientContracts(bean.getOrganizationId(), bean.getId(), bean.getVersion()); contractSummaryBeans.addAll(allClientContracts); } } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return contractSummaryBeans; } /** * @see IDeveloperResource#getAllApiVersions(String) */ @Override public List<ApiVersionBean> getAllApiVersions(String id) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkIfUserIsCurrentUser(id); List<ApiVersionBean> apiVersionBeans = new ArrayList<>(); List<ContractSummaryBean> contracts = getAllClientContracts(id); try { storage.beginTx(); for (ContractSummaryBean contract : contracts) { ApiVersionBean apiVersion = storage.getApiVersion(contract.getApiOrganizationId(), contract.getApiId(), contract.getApiVersion()); apiVersionBeans.add(apiVersion); } storage.commitTx(); } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return apiVersionBeans; } /** * @see IDeveloperResource#getPublicApiDefinition(String, String, String) */ @Override public Response getPublicApiDefinition(String organizationId, String apiId, String version) { instantiateOrganizationResource(); try { storage.beginTx(); ApiVersionBean apiVersion = organizationResource.getApiVersionFromStorage(organizationId, apiId, version); storage.commitTx(); if (apiVersion.isPublicAPI()) { return organizationResource.getApiDefinition(organizationId, apiId, version); } else { throw ExceptionFactory.notAuthorizedException(); } } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } } /** * @see IDeveloperResource#getApiDefinition(String, String, String, String) */ @Override public Response getApiDefinition(String developerId, String organizationId, String apiId, String version) throws DeveloperNotFoundException, NotAuthorizedException { securityContext.checkIfUserIsCurrentUser(developerId); instantiateOrganizationResource(); Set<DeveloperMappingBean> developerClients; List<ContractSummaryBean> contracts; try { storage.beginTx(); developerClients = getDeveloperBeanFromStorage(developerId).getClients(); // get all contracts from the API Version contracts = query.getContracts(organizationId, apiId, version, 1, 10000); storage.commitTx(); for (ContractSummaryBean contract : contracts) { for (DeveloperMappingBean client : developerClients) { // check if the developer is allowed to request the definition if (client.getClientId().equals(contract.getClientId()) && client.getOrganizationId().equals(contract.getClientOrganizationId())) { return organizationResource.getApiDefinition(organizationId, apiId, version); } } } } catch (StorageException e) { storage.rollbackTx(); throw new SystemErrorException(e); } return null; } private void instantiateOrganizationResource() { if (organizationResource == null) { organizationResource = new OrganizationResourceImpl(); organizationResource.securityContext = securityContext; organizationResource.storage = storage; organizationResource.query = query; organizationResource.gatewayLinkFactory = gatewayLinkFactory; } } }
37.457895
169
0.672123
e25e45bace8e8247761999dcb59736c9762f5ac4
2,970
py
Python
ceasiompy/CLCalculator/__specs__.py
cfsengineering/CEASIOMpy
b9ba84be3af3250cdd86c929ec02dbce5253b399
[ "Apache-2.0" ]
33
2018-11-20T16:34:40.000Z
2022-03-29T07:26:18.000Z
ceasiompy/CLCalculator/__specs__.py
cfsengineering/CEASIOMpy
b9ba84be3af3250cdd86c929ec02dbce5253b399
[ "Apache-2.0" ]
54
2019-09-17T15:57:47.000Z
2022-03-30T08:12:52.000Z
ceasiompy/CLCalculator/__specs__.py
cfsengineering/CEASIOMpy
b9ba84be3af3250cdd86c929ec02dbce5253b399
[ "Apache-2.0" ]
26
2018-11-30T14:33:44.000Z
2022-03-22T07:30:18.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ceasiompy.utils.moduleinterfaces import CPACSInOut, CEASIOM_XPATH, AIRCRAFT_XPATH # ===== RCE integration ===== RCE = { "name": "CLCalculator", "description": "Calculate required Lift coefficient to fly", "exec": "pwd\npython clcalculator.py", "author": "Aidan Jungo", "email": "[email protected]", } # ===== CPACS inputs and outputs ===== cpacs_inout = CPACSInOut() # ===== Input ===== cpacs_inout.add_input( var_name='mass_type', var_type=list, default_value= ['mTOM', 'mZFM', 'Custom','% fuel mass'], unit=None, descr='Type of mass to use for CL calculation', xpath=CEASIOM_XPATH +'/aerodynamics/clCalculation/massType', gui=True, gui_name='Type', gui_group='Mass' ) cpacs_inout.add_input( var_name='custom_mass', var_type=float, default_value=0.0, unit='kg', descr='Mass value if Custom is selected', xpath=CEASIOM_XPATH +'/aerodynamics/clCalculation/customMass', gui=True, gui_name='Custom mass', gui_group='Mass', ) cpacs_inout.add_input( var_name='percent_fuel_mass', var_type=float, default_value=100, unit='-', descr='Percentage of fuel mass between mTOM and mZFM, if % fuel mass is selected', xpath=CEASIOM_XPATH + '/aerodynamics/clCalculation/percentFuelMass', gui=True, gui_name='Percent fuel mass', gui_group='Mass', ) cpacs_inout.add_input( var_name='cruise_mach', var_type=float, default_value=0.78, unit='1', descr='Aircraft cruise Mach number', xpath=CEASIOM_XPATH + '/aerodynamics/clCalculation/cruiseMach', gui=True, gui_name='Mach', gui_group='Cruise', ) cpacs_inout.add_input( var_name='cruise_alt', var_type=float, default_value=12000.0, unit='m', descr='Aircraft cruise altitude', xpath=CEASIOM_XPATH + '/aerodynamics/clCalculation/cruiseAltitude', gui=True, gui_name='Altitude', gui_group='Cruise', ) cpacs_inout.add_input( var_name='load_fact', var_type=float, default_value=1.05, unit='1', descr='Aircraft cruise altitude', xpath=CEASIOM_XPATH + '/aerodynamics/clCalculation/loadFactor', gui=True, gui_name='Load Factor', gui_group='Cruise', ) cpacs_inout.add_input( var_name='ref_area', var_type=float, default_value=None, unit='m^2', descr='Aircraft reference area', xpath=AIRCRAFT_XPATH + '/model/reference/area', gui=False, gui_name=None, gui_group=None, ) #===== Output ===== cpacs_inout.add_output( var_name='target_cl', default_value=None, unit='1', descr='Value of CL to achieve to have a level flight with the given conditions', xpath=CEASIOM_XPATH + '/aerodynamics/su2/targetCL', ) cpacs_inout.add_output( var_name='fixed_cl', default_value=None, unit='-', descr='FIXED_CL_MODE parameter for SU2', xpath=CEASIOM_XPATH + '/aerodynamics/su2/fixedCL', )
23.951613
86
0.67037
cd3564e4a70557e40cb230b33fb62291907ccbeb
1,555
cs
C#
src/Mocklis.MockGenerator.Tests/TestCases/MethodWithRestrictedType.Expected.cs
eredmo/mocklis
1044d7ca38761421b6b94eedc0de96d3a4e83499
[ "MIT" ]
7
2019-03-14T09:44:09.000Z
2020-12-14T12:38:07.000Z
src/Mocklis.MockGenerator.Tests/TestCases/MethodWithRestrictedType.Expected.cs
eredmo/mocklis
1044d7ca38761421b6b94eedc0de96d3a4e83499
[ "MIT" ]
18
2019-05-06T11:35:35.000Z
2021-02-20T14:59:05.000Z
src/Mocklis.MockGenerator.Tests/TestCases/MethodWithRestrictedType.Expected.cs
eredmo/mocklis
1044d7ca38761421b6b94eedc0de96d3a4e83499
[ "MIT" ]
2
2020-05-11T21:55:00.000Z
2020-05-11T21:57:50.000Z
using System; using System.CodeDom.Compiler; using Mocklis.Core; namespace Test { public interface ITestClass { void Restricted(RuntimeArgumentHandle runtimeArgumentHandle); void Restricted(ArgIterator argIterator); void Restricted(TypedReference typedReference); } [MocklisClass, GeneratedCode("Mocklis", "[VERSION]")] public class TestClass : ITestClass { // The contents of this class were created by the Mocklis code-generator. // Any changes you make will be overwritten if the contents are re-generated. protected virtual void Restricted(RuntimeArgumentHandle runtimeArgumentHandle) { throw new MockMissingException(MockType.VirtualMethod, "TestClass", "ITestClass", "Restricted", "Restricted"); } void ITestClass.Restricted(RuntimeArgumentHandle runtimeArgumentHandle) => Restricted(runtimeArgumentHandle); protected virtual void Restricted0(ArgIterator argIterator) { throw new MockMissingException(MockType.VirtualMethod, "TestClass", "ITestClass", "Restricted", "Restricted0"); } void ITestClass.Restricted(ArgIterator argIterator) => Restricted0(argIterator); protected virtual void Restricted1(TypedReference typedReference) { throw new MockMissingException(MockType.VirtualMethod, "TestClass", "ITestClass", "Restricted", "Restricted1"); } void ITestClass.Restricted(TypedReference typedReference) => Restricted1(typedReference); } }
37.02381
123
0.710611
c29a2db021a2f4adb2e5ccaeb89028cf25f2467c
1,312
h
C
include/l0-infra/array/mixin/find/UnsafePointerRangeFind.h
godsme/object-array
c3c9a707b14d265271f169ed91bb533b05d7ec17
[ "Apache-2.0" ]
9
2021-06-25T11:06:07.000Z
2021-09-23T09:47:58.000Z
include/l0-infra/array/mixin/find/UnsafePointerRangeFind.h
godsme/object-array
c3c9a707b14d265271f169ed91bb533b05d7ec17
[ "Apache-2.0" ]
2
2021-08-17T17:35:42.000Z
2021-11-27T02:00:18.000Z
include/l0-infra/array/mixin/find/UnsafePointerRangeFind.h
godsme/object-array
c3c9a707b14d265271f169ed91bb533b05d7ec17
[ "Apache-2.0" ]
1
2021-08-17T17:05:19.000Z
2021-08-17T17:05:19.000Z
// // Created by Darwin Yuan on 2021/7/13. // #ifndef OBJECT_ARRAY_2_1E20317D794F49B59F9FCED94485D9A3 #define OBJECT_ARRAY_2_1E20317D794F49B59F9FCED94485D9A3 #include <l0-infra/array/concept/Pred.h> namespace mixin { template<typename T> struct UnsafePointerRangeFind : T { using typename T::SizeType; using typename T::ObjectType; using typename T::Maybe; public: template<__pRed_CoNcEpT(PRED)> auto Unsafe_RangeFindIndex(SizeType from, SizeType until, PRED&& pred) const -> Maybe { return T::GetPointers().Unsafe_RangeFindIndex(from, until, T::GetPointerPred(std::forward<PRED>(pred))); } template<__pRed_CoNcEpT(PRED)> auto Unsafe_RangeFind(SizeType from, SizeType until, PRED&& pred) const -> ObjectType const* { auto* p = T::GetPointers().Unsafe_RangeFind(from, until, T::GetPointerPred(std::forward<PRED>(pred))); return p == nullptr ? nullptr : *p; } template<__pRed_CoNcEpT(PRED)> auto Unsafe_RangeFindRange(SizeType from, SizeType until, PRED&& pred) const -> auto { return T::GetPointers().Unsafe_RangeFindRange(from, until, T::GetPointerPred(std::forward<PRED>(pred))); } }; } #endif //OBJECT_ARRAY_2_1E20317D794F49B59F9FCED94485D9A3
35.459459
116
0.68064
a68f431838cbe7a318c8f494fb57dd21949afc33
466
lua
Lua
Assets/LuaScripts/Network/ConnectState.lua
sdupan/UnityLuaFramework
7953a10021455ebcd39e4a2609ec5eb6c6bd6bc3
[ "MIT" ]
1
2021-03-16T06:12:39.000Z
2021-03-16T06:12:39.000Z
Assets/LuaScripts/Network/ConnectState.lua
sdupan/UnityLuaFramework
7953a10021455ebcd39e4a2609ec5eb6c6bd6bc3
[ "MIT" ]
null
null
null
Assets/LuaScripts/Network/ConnectState.lua
sdupan/UnityLuaFramework
7953a10021455ebcd39e4a2609ec5eb6c6bd6bc3
[ "MIT" ]
null
null
null
local M = {} -----------------------连接状态---------------------------- M.CONNECT_STATE_IDLE = "idle" M.CONNECT_STATE_START = "startreconnect" M.CONNECT_STATE_CONNECTING = "connecting" M.CONNECT_STATE_CONNECTED = "connected" M.CONNECT_STATE_CONNECT_FAILURE = "connectFailure" M.CONNECT_STATE_CLOSED = "closed" M.CONNECT_STATE_RECONNECT = "reconnect"--在重连中,可以继续重连 M.CONNECT_STATE_RECONNECTING = "reconnecting" return M
35.846154
58
0.633047
652783f4f5b2c5feb764fe331c0720ff3cc80b4d
1,999
css
CSS
css/colorStyle.css
matt-ngo/matt-ngo.github.io
c349ab54f7f0cf7d1454c8c3ecbf4f2f4c6d5efb
[ "MIT" ]
null
null
null
css/colorStyle.css
matt-ngo/matt-ngo.github.io
c349ab54f7f0cf7d1454c8c3ecbf4f2f4c6d5efb
[ "MIT" ]
null
null
null
css/colorStyle.css
matt-ngo/matt-ngo.github.io
c349ab54f7f0cf7d1454c8c3ecbf4f2f4c6d5efb
[ "MIT" ]
null
null
null
body { /* background-color: rgb(40, 40, 40); */ background-color: #f7f2e7; /* font-family: 'Roboto Mono', monospace; */ font-family: 'Nunito', sans-serif; /* margin: 0; */ } span { color: #3b5249; font-size: 1.125rem; } .square { border-radius: 1.5rem; width: 30%; padding-bottom: 30%; float: left; /* border: white solid 1px; */ background: purple; margin: 1.66%; transition: background .25s; -webkit-transition: background .25s; -moz-transition: background .25s; } .container { margin: 0 auto; max-width: 600px; padding-top: 3%; } h1 { border-radius: 1.5rem; color: #3b5249; text-align: center; background-color: #e6e1dc; /* margin: 0; */ padding: 3%; margin: 3%; font-weight: 800; } #colorDisplay { text-transform: uppercase; /* color: rgb(29, 32, 33); */ color: #519872; font-size: 2.5rem; } #stripe { /* background-color: rgb(29, 32, 33); */ height: 30px; text-align: center; } button { outline: none; /* font-family: 'Roboto Mono', monospace; */ font-family: 'Nunito', sans-serif; border-radius: 0.3rem; padding: 0.4rem 1rem; font-size: 1.125rem; border: 0px; color: rgb(249, 249, 243); background: #382933; transition: all .5s; -webkit-transition: background .5s; -moz-transition: background .5s; } button:hover { background-color: rgb(234, 220, 181); color: rgb(29, 32, 33); } #refresh { background: rgb(106, 159, 108); } #refresh:hover { background-color: rgb(234, 220, 181); } .selected { border: 4px #a4b494 solid; border-radius: 0.3rem; } #message { display: inline-block; width: 30%; } @media (max-width: 768px) { h1 { font-size: 1.3rem; } #colorDisplay { font-size: 1.5rem; } #message { display: inline-block; width: 20%; } #stripe { margin-top: 5%; margin-bottom: 5%; } }
18.172727
48
0.566783
c5f70ed8b0205dd10ab745c8a324b20d131f30c3
5,716
kt
Kotlin
app/src/main/java/com/example/androiddevchallenge/ui/place/PlaceChooser.kt
DavidMendozaMartinez/AndroidDevChallenge-Jetpack-Compose-Week-4
b92324f43c2d6925b437e28dabe44800c905fe73
[ "Apache-2.0" ]
3
2021-03-24T14:25:52.000Z
2021-12-24T08:54:17.000Z
app/src/main/java/com/example/androiddevchallenge/ui/place/PlaceChooser.kt
DavidMendozaMartinez/AndroidDevChallenge-Jetpack-Compose-Week-4
b92324f43c2d6925b437e28dabe44800c905fe73
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/androiddevchallenge/ui/place/PlaceChooser.kt
DavidMendozaMartinez/AndroidDevChallenge-Jetpack-Compose-Week-4
b92324f43c2d6925b437e28dabe44800c905fe73
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.place import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.expandVertically import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Place import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.R import com.example.androiddevchallenge.model.Place @OptIn(ExperimentalAnimationApi::class) @Composable fun PlaceChooser( places: List<Place>, onChosenPlace: (Place) -> Unit, modifier: Modifier = Modifier ) { var selectedPosition by remember { mutableStateOf(0) } var isPlaceListExpanded by remember { mutableStateOf(false) } Column( modifier = modifier ) { SelectedPlace( place = places[selectedPosition], onClick = { isPlaceListExpanded = !isPlaceListExpanded } ) AnimatedVisibility( visible = isPlaceListExpanded, enter = expandVertically(expandFrom = Alignment.Top), exit = shrinkVertically(shrinkTowards = Alignment.Top), ) { PlaceList( places = places, selectedPosition = selectedPosition, onItemClick = { position -> selectedPosition = position onChosenPlace(places[position]) isPlaceListExpanded = false } ) } } } @Composable fun SelectedPlace( place: Place, onClick: () -> Unit, modifier: Modifier = Modifier ) { Surface( color = MaterialTheme.colors.background, elevation = 8.dp ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier .fillMaxWidth() .clickable { onClick() } .padding(16.dp) ) { Icon( imageVector = Icons.Outlined.Place, contentDescription = null, tint = MaterialTheme.colors.primary ) Spacer(modifier = Modifier.width(12.dp)) Text( text = place.displayName, style = MaterialTheme.typography.h6 ) } } } @Composable fun PlaceList( places: List<Place>, selectedPosition: Int, onItemClick: (Int) -> Unit, modifier: Modifier = Modifier ) { Column { LazyColumn( verticalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(16.dp), modifier = modifier ) { items(places) { place -> PlaceItem( place = place, selected = places.indexOf(place) == selectedPosition, onClick = { onItemClick(places.indexOf(place)) } ) } } Image( painter = painterResource(id = R.drawable.places_bg), contentDescription = null, modifier = Modifier.padding(8.dp) ) } } @Composable fun PlaceItem( place: Place, selected: Boolean, onClick: () -> Unit ) { Surface( color = if (selected) MaterialTheme.colors.surface.copy(alpha = 0.4F) else Color.Transparent, shape = MaterialTheme.shapes.medium, border = if (selected) BorderStroke(2.dp, MaterialTheme.colors.surface) else null ) { Text( text = place.displayName, textAlign = TextAlign.Center, color = if (selected) MaterialTheme.colors.onSurface else MaterialTheme.colors.onBackground, modifier = Modifier .fillMaxWidth() .clickable { onClick() } .padding(16.dp) ) } }
32.850575
104
0.662176
4e404b2f4be54a9163894ade8b831e884a865a7d
6,167
dart
Dart
lib/src/features/package/controller/publication_metadata/epub_publication_metadata_reader_controller.dart
getBoolean/epub_master
6288dbbaabb4ac2155b39c5ef61b11f58bca6769
[ "MIT" ]
2
2022-03-23T21:05:27.000Z
2022-03-24T01:21:17.000Z
lib/src/features/package/controller/publication_metadata/epub_publication_metadata_reader_controller.dart
getBoolean/epub_master
6288dbbaabb4ac2155b39c5ef61b11f58bca6769
[ "MIT" ]
2
2022-03-23T20:17:55.000Z
2022-03-26T21:31:07.000Z
lib/src/features/package/controller/publication_metadata/epub_publication_metadata_reader_controller.dart
getBoolean/shu_epub
6288dbbaabb4ac2155b39c5ef61b11f58bca6769
[ "MIT" ]
null
null
null
part of shu_epub.features.package.controller; class EpubPublicationMetadataReaderController { final XmlElement element; XmlElement get compatibleMetadataElement => hasDcMetadataElement ? dcMetadata! : element; final XmlElement? dcMetadata; bool get hasDcMetadataElement => dcMetadata != null; final XmlElement? xMetadata; bool get hasXMetadataElement => xMetadata != null; static const elementName = EpubPublicationMetadata.elementName; EpubPublicationMetadataReaderController._internal({ required this.element, this.dcMetadata, this.xMetadata, }); /// Throws [EpubException] if the metadata element is not the root node factory EpubPublicationMetadataReaderController.fromXmlElement( XmlElement metadataElement) { if (metadataElement.name.qualified != elementName) { throw EpubException( 'Invalid data, expected $elementName to be the root node but it was not found', ); } final dcMetadata = metadataElement.findElements('dc-metadata').firstOrNull; final xMetadata = metadataElement.findElements('x-metadata').firstOrNull; return EpubPublicationMetadataReaderController._internal( element: metadataElement, dcMetadata: dcMetadata, xMetadata: xMetadata, ); } /// Create an instance of [EpubPublicationMetadataReaderController] from the [String] representation /// of the metadata element /// /// Throws [EpubException] if the string does not have the metadata element factory EpubPublicationMetadataReaderController.fromXmlString( String metadataString) { final stringList = metadataString.codeUnits; final data = Uint8List.fromList(stringList); return EpubPublicationMetadataReaderController(data); } /// Create an instance of [EpubPublicationMetadataReaderController] from the [Uint8List] data /// of the metadata element in the navigation file. /// /// Throws [EpubException] if the data does not have the metadata element factory EpubPublicationMetadataReaderController(Uint8List metadataData) { final String content = utf8.decode( metadataData, allowMalformed: true, ); final xmlDocument = XmlUtils.parseToXmlDocument(content); final metadataElement = xmlDocument.findElements('metadata').firstOrNull; if (metadataElement == null) { throw EpubException( 'Malformed navigation file, could not find required $elementName element', ); } return EpubPublicationMetadataReaderController.fromXmlElement( metadataElement, ); } List<EpubMetadataTitle> getAllTitles() { return compatibleMetadataElement .findElements(EpubMetadataTitle.elementName) .map(EpubMetadataTitle.fromXmlElement) .toList(); } List<EpubMetadataCreator> getCreators() { return compatibleMetadataElement .findElements(EpubMetadataCreator.elementName) .map(EpubMetadataCreator.fromXmlElement) .toList(); } List<String> getSubjects() { return compatibleMetadataElement .findElements('dc:subject') .map((node) => node.innerText.trim()) .where((element) => element.isNotEmpty) .toList(); } String? getDescription() { return compatibleMetadataElement .findElements('dc:description') .firstOrNull ?.innerText .trimThenNullIfEmpty; } String? getPublisher() { return compatibleMetadataElement .findElements('dc:publisher') .firstOrNull ?.innerText .trimThenNullIfEmpty; } List<EpubMetadataContributor> getContributors() { return compatibleMetadataElement .findElements(EpubMetadataContributor.elementName) .map(EpubMetadataContributor.fromXmlElement) .toList(); } List<EpubExtraMetadata> getExtraMetadataItems() { return hasXMetadataElement ? xMetadata! .findElements(EpubExtraMetadata.elementName) .map((node) => EpubExtraMetadata( name: node.getAttribute('name'), content: node.getAttribute('content'), )) .toList() : element .findElements(EpubExtraMetadata.elementName) .map((node) => EpubExtraMetadata( name: node.getAttribute('name'), content: node.getAttribute('content'), )) .toList(); } EpubMetadataDate? getDate() { final dateElement = compatibleMetadataElement .findElements(EpubMetadataDate.elementName) .firstOrNull; if (dateElement == null) { return null; } return EpubMetadataDate.fromXmlElement(dateElement); } String? getType() { return compatibleMetadataElement .findElements('dc:type') .firstOrNull ?.innerText .trimThenNullIfEmpty; } String? getFormat() { return compatibleMetadataElement .findElements('dc:format') .firstOrNull ?.innerText .trimThenNullIfEmpty; } List<EpubMetadataIdentifier> getIdentifiers() { return compatibleMetadataElement .findElements(EpubMetadataIdentifier.elementName) .map(EpubMetadataIdentifier.fromXmlElement) .toList(); } String? getSource() { return compatibleMetadataElement .findElements('dc:source') .firstOrNull ?.innerText .trimThenNullIfEmpty; } List<String> getLanguages() { return compatibleMetadataElement .findElements('dc:language') .map((node) => node.innerText.trim()) .where((element) => element.isNotEmpty) .toList(); } String? getRelation() { return compatibleMetadataElement .findElements('dc:relation') .firstOrNull ?.innerText .trimThenNullIfEmpty; } String? getCoverage() { return compatibleMetadataElement .findElements('dc:coverage') .firstOrNull ?.innerText .trimThenNullIfEmpty; } String? getRights() { return compatibleMetadataElement .findElements('dc:rights') .firstOrNull ?.innerText .trimThenNullIfEmpty; } }
29.227488
102
0.676018
fa8b981d6f87909ebffa1adb4dda63f149086ff7
3,721
ps1
PowerShell
Tests/ParallelRemote.Tests.ps1
bvangrinsven/PowerShellLoggingModule
6bf6aabe0e855876822169910ac80e6446fbbbec
[ "Apache-2.0" ]
56
2015-02-09T02:30:06.000Z
2022-01-14T07:59:15.000Z
Tests/ParallelRemote.Tests.ps1
Kriegel/PowerShellLoggingModule
6bf6aabe0e855876822169910ac80e6446fbbbec
[ "Apache-2.0" ]
9
2017-01-23T17:31:43.000Z
2021-08-07T04:05:36.000Z
Tests/ParallelRemote.Tests.ps1
Kriegel/PowerShellLoggingModule
6bf6aabe0e855876822169910ac80e6446fbbbec
[ "Apache-2.0" ]
19
2015-09-07T14:30:50.000Z
2020-02-18T13:58:03.000Z
#requires -Module PowerShellLogging, ThreadJob param($Count = 4) Describe "Working when called in parallel in remote runspaces" -Tag "Remoting" { $Path = "TestDrive:\log{0}.txt" $Path = (Join-Path (Convert-Path (Split-Path $Path)) (Split-Path $Path -Leaf)) BeforeAll { $script:PowerShell = $( foreach($index in 1..$Count) { $LocalHost = [System.Management.Automation.Runspaces.WSManConnectionInfo]@{ComputerName = "."; EnableNetworkAccess = $true } $Runspace = [runspacefactory]::CreateRunspace($LocalHost) $Runspace.Open() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell } ) } AfterAll { foreach($PS in $script:PowerShell) { $PS.Runspace.Dispose() $PS.Dispose() } } $TestScript = " Import-Module PowerShellLogging `$Logging = Enable-LogFile -Path '${Path}' Write-Host 'This is a host test from attempt {0}' '${Path}' Start-Sleep 2 Write-Verbose 'This is a verbose test from attempt {0}' -Verbose Disable-LogFile `$Logging " It "Should not crash when used" { $script:Results = & { $i = 0 foreach($PS in $script:PowerShell) { $i += 1 Start-ThreadJob { param($PS, $Script) $PS.AddScript($Script).Invoke() } -ArgumentList $PS, ($TestScript -f $i) } } | Wait-Job | Receive-Job } It "Should not interfere with output" { $script:Results.Count | Should -Be $script:PowerShell.Count $i = 0 foreach ($resultPath in $script:Results) { $i += 1 $resultPath | Should -Be ($Path -f $i) } } It "Should not cause Enable-LogFile to fail" { foreach($PS in $script:PowerShell) { $PS.Streams.Error.InvocationInfo.MyCommand.Name | Should -Not -Contain "Enable-LogFile" } } It "Should not cause Write-Host to fail" { foreach ($PS in $script:PowerShell) { $PS.Streams.Error.InvocationInfo.MyCommand.Name | Should -Not -Contain "Write-Host" } } It "Should not cause Write-Verbose to fail" { foreach ($PS in $script:PowerShell) { $PS.Streams.Error.InvocationInfo.MyCommand.Name | Should -Not -Contain "Write-Verbose" } } It "Should not cause Disable-LogFile to fail" { foreach ($PS in $script:PowerShell) { $PS.Streams.Error.InvocationInfo.MyCommand.Name | Should -Not -Contain "Disable-LogFile" } } It "Should not cause any errors" { foreach ($PS in $script:PowerShell) { $PS.Streams.Error.Count | Should -Be 0 } } Write-Warning "Expecting $($script:Results.Count) log files!" It "Should create the log file" { # this is enough to prove the logging works $i = 0 foreach($PS in $script:PowerShell) { $i += 1 ($Path -f $i) | Should -Exist } } $i = 0 foreach ($PS in $script:PowerShell) { $i += 1 It "Should log host output to $($Path -f $i)" -Skip:(!(Test-Path ($Path -f $i))) { (Get-Content ($Path -f $i)) -match "This is a host test from attempt $i$" | Should -Not -BeNullOrEmpty } } $i = 0 foreach ($PS in $script:PowerShell) { $i += 1 It "Should log host output to $($Path -f $i)" -Skip:(!(Test-Path ($Path -f $i))) { (Get-Content ($Path -f $i)) -match "This is a verbose test from attempt $i$" | Should -Not -BeNullOrEmpty } } }
32.640351
140
0.550658
79a43db91b712e9387993773e5a949763a234420
263
lua
Lua
MMOCoreORB/bin/scripts/object/custom_content/tangible/furniture/all/frn_all_bed_sm_hue_s1.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/furniture/all/frn_all_bed_sm_hue_s1.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/furniture/all/frn_all_bed_sm_hue_s1.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_tangible_furniture_all_frn_all_bed_sm_hue_s1 = object_tangible_furniture_all_shared_frn_all_bed_sm_hue_s1:new { } ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_bed_sm_hue_s1, "object/tangible/furniture/all/frn_all_bed_sm_hue_s1.iff")
43.833333
139
0.908745
3f0ad9c698ae1ce00c54e6c147bf68d021ac26eb
5,256
php
PHP
src/Grid/Concerns/HasGridAttributes.php
yiiso/laravel-vue-admin
180eb1517d4571dd8dc4989e90967564578af5e2
[ "MIT" ]
394
2020-01-21T10:43:48.000Z
2022-03-28T01:41:27.000Z
src/Grid/Concerns/HasGridAttributes.php
yiiso/laravel-vue-admin
180eb1517d4571dd8dc4989e90967564578af5e2
[ "MIT" ]
73
2020-01-21T01:36:13.000Z
2022-02-26T21:50:45.000Z
src/Grid/Concerns/HasGridAttributes.php
yiiso/laravel-vue-admin
180eb1517d4571dd8dc4989e90967564578af5e2
[ "MIT" ]
75
2020-01-22T07:58:44.000Z
2022-03-27T14:52:49.000Z
<?php namespace SmallRuralDog\Admin\Grid\Concerns; use SmallRuralDog\Admin\Grid\Table\Attributes; trait HasGridAttributes { /** * @var Attributes */ protected $attributes; /** * Table 的高度,默认为自动高度。如果 height 为 number 类型,单位 px;如果 height 为 string 类型,则这个高度会设置为 Table 的 style.height 的值,Table 的高度会受控于外部样式。 * @param string|int $height * @return $this */ public function height($height) { $this->attributes->height = $height; return $this; } /** * js计算页面高度,使表格高度撑满窗口 * @return $this */ public function autoHeight(){ $this->attributes->height = 'auto'; return $this; } /** * Table 的最大高度。合法的值为数字或者单位为 px 的高度。 * @param string|int $maxHeight * @return $this */ public function maxHeight($maxHeight) { $this->attributes->maxHeight = $maxHeight; return $this; } /** * 是否为斑马纹 table * @param bool $stripe * @return $this */ public function stripe($stripe = true) { $this->attributes->stripe = $stripe; return $this; } /** * 是否带有纵向边框 * @param bool $border * @return $this */ public function border($border = true) { $this->attributes->border = $border; return $this; } /** * Table 的尺寸 * medium / small / mini * @param string $size * @return $this */ public function size(string $size) { $this->attributes->size = $size; return $this; } /** * 列的宽度是否自撑开 * @param bool $fit * @return $this */ public function fit(bool $fit = true) { $this->attributes->fit = $fit; return $this; } /** * 是否显示表头 * @param bool $showHeader * @return $this */ public function showHeader($showHeader = true) { $this->attributes->showHeader = $showHeader; return $this; } /** * 是否要高亮当前行 * @param bool $highlightCurrentRow * @return $this */ public function highlightCurrentRow($highlightCurrentRow = true) { $this->attributes->highlightCurrentRow = $highlightCurrentRow; return $this; } /** * 空数据时显示的文本内容 * @param string $emptyText * @return $this */ public function emptyText($emptyText) { $this->attributes->emptyText = $emptyText; return $this; } /** * tooltip effect 属性 * dark/light * @param string $tooltipEffect * @return $this */ public function tooltipEffect($tooltipEffect) { $this->attributes->tooltipEffect = $tooltipEffect; return $this; } public function rowKey($rowKey) { $this->attributes->rowKey = $rowKey; return $this; } /** * @param $url * @return $this * @deprecated * 开启拖拽排序 */ public function draggable($url) { $this->attributes->draggable = true; $this->attributes->draggableUrl = $url; return $this; } /** * 是否默认展开所有行,当 Table 包含展开行存在或者为树形表格时有效 * @param bool $defaultExpandAll * @return $this */ public function defaultExpandAll($defaultExpandAll = true) { $this->attributes->defaultExpandAll = $defaultExpandAll; return $this; } public function treeProps($hasChildren, $children) { $this->attributes->treeProps = [ 'hasChildren' => $hasChildren, 'children' => $children, ]; } public function getTreeChildrenName() { return $this->attributes->treeProps['children']; } /** * 是否开启多选 * @param bool $selection * @return $this */ public function selection($selection = true) { $this->attributes->selection = $selection; return $this; } /** * 操作栏宽度 * @param $actionWidth * @return $this */ public function actionWidth($actionWidth) { $this->attributes->actionWidth = $actionWidth; return $this; } /** * 操作栏名称 * @param $actionLabel * @return $this */ public function actionLabel($actionLabel) { $this->attributes->actionLabel = $actionLabel; return $this; } /** * 操作栏对齐 * left right center * @param $actionAlign * @return $this */ public function actionAlign($actionAlign) { $this->attributes->actionAlign = $actionAlign; return $this; } /** * 操作栏固定位置 * @param $actionFixed * @return $this */ public function actionFixed($actionFixed) { $this->attributes->actionFixed = $actionFixed; return $this; } /** * 隐藏操作栏 * @return $this */ public function hideActions() { $this->attributes->hideActions = true; return $this; } public function getHideActions() { return $this->attributes->hideActions; } /** * 表格数据是否存入vuex * @param $dataVuex * @return $this */ public function dataVuex($dataVuex = true) { $this->attributes->dataVuex = $dataVuex; return $this; } }
19.539033
127
0.541857
26b1aec919c54ec078909844f179007444c9d97a
1,158
rs
Rust
src/algebra/linear/matrix/mod.rs
matthiaseiholzer/mathru_mirror
da0117e59dd99b6e3e763f8dd1787d309482e866
[ "MIT" ]
null
null
null
src/algebra/linear/matrix/mod.rs
matthiaseiholzer/mathru_mirror
da0117e59dd99b6e3e763f8dd1787d309482e866
[ "MIT" ]
null
null
null
src/algebra/linear/matrix/mod.rs
matthiaseiholzer/mathru_mirror
da0117e59dd99b6e3e763f8dd1787d309482e866
[ "MIT" ]
null
null
null
#[macro_use] pub mod matrix; //mod matrixcolumniterator; //mod matrixcolumniteratormut; mod matrixintoiterator; mod matrixiterator; mod matrixiteratormut; //mod matrixrowiterator; //mod matrixrowiteratormut; mod matrixcolumnintoiterator; mod matrixrowintoiterator; mod eigen; pub use self::eigen::EigenDec; mod hessenberg; pub use self::hessenberg::HessenbergDec; mod lu; pub use self::lu::LUDec; mod qr; pub use self::qr::QRDec; mod add; mod div; mod inverse; mod mul; mod sub; mod det; mod singular; mod cholesky; pub use self::cholesky::CholeskyDec; mod solve; mod substitute; mod transpose; pub use self::{ inverse::Inverse, matrix::Matrix, //matrixcolumniterator::MatrixColumnIterator, //matrixcolumniteratormut::MatrixColumnIteratorMut, matrixcolumnintoiterator::MatrixColumnIntoIterator, matrixintoiterator::MatrixIntoIterator, matrixiterator::MatrixIterator, matrixiteratormut::MatrixIteratorMut, //matrixrowiterator::MatrixRowIterator, //matrixrowiteratormut::MatrixRowIteratorMut, matrixrowintoiterator::MatrixRowIntoIterator, solve::Solve, substitute::Substitute, transpose::Transpose };
21.444444
55
0.776339
29661079d74ea6b17f38047aecc5748b8ea1c00f
624
sql
SQL
db/disagg/3-triggers/map_trg.sql
alazarolop/dicsm
e15059e951115b7033ff197481d0814261d801db
[ "PostgreSQL", "CC-BY-4.0" ]
null
null
null
db/disagg/3-triggers/map_trg.sql
alazarolop/dicsm
e15059e951115b7033ff197481d0814261d801db
[ "PostgreSQL", "CC-BY-4.0" ]
null
null
null
db/disagg/3-triggers/map_trg.sql
alazarolop/dicsm
e15059e951115b7033ff197481d0814261d801db
[ "PostgreSQL", "CC-BY-4.0" ]
null
null
null
--MAP UNITS -- *TRIGGER* CREATE OR REPLACE FUNCTION disagg.stu_controlpc() RETURNS trigger AS $$ DECLARE i RECORD; BEGIN -- SELECT dsmu_id AS dsmu, sum(stupc) AS pc INTO i FROM dsmu_stu WHERE dsmu_id LIKE NEW.dsmu_id GROUP BY dsmu ; -- IF NEW.stupc IS NULL THEN RETURN NEW ; ELSE IF (NEW.stupc + COALESCE(i.pc, 0)) <= 100 THEN RETURN NEW ; ELSE RAISE EXCEPTION 'STU percentage (% %%) is greater than the maximum allowed for SMU % (% %%).', NEW.stupc, NEW.dsmu_id, (100-i.pc) ; END IF; END IF; END; $$ LANGUAGE plpgsql ; COMMENT ON FUNCTION disagg.stu_controlpc() IS 'Ocupation control for STU within SMU' ;
24
140
0.698718
d0dc64abd4b17205b53a34f959930b63e41031c3
1,452
sh
Shell
aws/openresty-awscert-proxy/build-openresty-image/start.sh
zulily/zutools
fe8fa75d589477aa6d24de0f56128fe76eead530
[ "Apache-2.0" ]
null
null
null
aws/openresty-awscert-proxy/build-openresty-image/start.sh
zulily/zutools
fe8fa75d589477aa6d24de0f56128fe76eead530
[ "Apache-2.0" ]
null
null
null
aws/openresty-awscert-proxy/build-openresty-image/start.sh
zulily/zutools
fe8fa75d589477aa6d24de0f56128fe76eead530
[ "Apache-2.0" ]
1
2018-08-30T16:52:13.000Z
2018-08-30T16:52:13.000Z
#!/bin/bash # Configure Auth if [ -n "${ENABLE_SSL+1}" ] && [ "${ENABLE_SSL,,}" = "true" ]; then echo "Enabling SSL..." cp /usr/src/openresty_ssl.conf /usr/local/openresty/nginx/conf/conf.d/proxy.conf # If an htpasswd file is provided, configure nginx if [ -n "${ENABLE_BASIC_AUTH+1}" ] && [ "${ENABLE_BASIC_AUTH,,}" = "true" ]; then echo "Enabling basic auth..." sed -i "s/#auth_basic/auth_basic/g;" /usr/local/openresty/nginx/conf/conf.d/proxy.conf fi else # No SSL cp /usr/src/openresty_nossl.conf /usr/local/openresty/nginx/conf/conf.d/proxy.conf fi # If rate limiting is requested, set it up, defaulting to 1req/sec. if [ -n "${ENABLE_HTTP_RATE_LIMIT}" ] && [ "${ENABLE_HTTP_RATE_LIMIT}" = "true" ]; then echo "Enabling http rate limiting..." sed -i "s/#limit_req_zone/limit_req_zone/g;" /usr/local/openresty/nginx/conf/conf.d/proxy.conf sed -i "s/#limit_req /limit_req /g;" /usr/local/openresty/nginx/conf/conf.d/proxy.conf if [ -n "${RATE_REQS_SEC}" ]; then sed -i "s/{{RATE_REQS_SEC}}/${RATE_REQS_SEC}/g;" /usr/local/openresty/nginx/conf/conf.d/proxy.conf else sed -i "s/{{RATE_REQS_SEC}}/1/g;" /usr/local/openresty/nginx/conf/conf.d/proxy.conf fi fi # Tell nginx the address and port of the service to proxy to sed -i "s|{{TARGET_SERVICE}}|${TARGET_SERVICE}|g;" /usr/local/openresty/nginx/conf/conf.d/proxy.conf echo "Starting openresty..." /usr/local/openresty/bin/openresty -g 'daemon off;'
41.485714
102
0.687328
2c76126529c4965a133a13463d27045f974025d6
148
py
Python
xrpl/__init__.py
mDuo13/xrpl-py
70f927dcd2dbb8644b3e210b0a8de2a214e71e3d
[ "0BSD" ]
null
null
null
xrpl/__init__.py
mDuo13/xrpl-py
70f927dcd2dbb8644b3e210b0a8de2a214e71e3d
[ "0BSD" ]
null
null
null
xrpl/__init__.py
mDuo13/xrpl-py
70f927dcd2dbb8644b3e210b0a8de2a214e71e3d
[ "0BSD" ]
null
null
null
"""High-level XRPL exports.""" from xrpl.constants import CryptoAlgorithm, XRPLException __all__ = [ "CryptoAlgorithm", "XRPLException", ]
18.5
57
0.716216
850e7b418f25837bf4ca863bb9178ba4308984b6
1,244
kt
Kotlin
src/main/kotlin/com/jetbrains/embeddedProjectJdk/LoadJdkSettingsFromProject.kt
JetBrains/embeddedProjectJdk
7e0a90b3d32254914501a9a40f165edf128b4f6f
[ "MIT" ]
5
2018-02-28T01:04:37.000Z
2021-11-08T09:50:00.000Z
src/main/kotlin/com/jetbrains/embeddedProjectJdk/LoadJdkSettingsFromProject.kt
JetBrains/embeddedProjectJdk
7e0a90b3d32254914501a9a40f165edf128b4f6f
[ "MIT" ]
8
2018-02-28T10:40:37.000Z
2020-09-24T14:53:35.000Z
src/main/kotlin/com/jetbrains/embeddedProjectJdk/LoadJdkSettingsFromProject.kt
JetBrains/embeddedProjectJdk
7e0a90b3d32254914501a9a40f165edf128b4f6f
[ "MIT" ]
6
2018-02-28T01:04:42.000Z
2022-03-19T06:44:05.000Z
package com.jetbrains.embeddedProjectJdk import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.DumbAware import com.intellij.openapi.projectRoots.ProjectJdkTable class LoadJdkSettingsFromProject : AnAction(), DumbAware { private val myLogger = Logger.getInstance(EmbeddedProjectJdkSettingsChecker::class.java) override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project?.let { JdkUtil.hasProjectJdkSettings(it) } ?: false } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: error("e.project shouldn't be null") val projectJdkTable = ProjectJdkTable.getInstance() val jdkList = JdkUtil.readProjectJdkSettings(project) ApplicationManager.getApplication().runWriteAction { jdkList.forEach { jdk -> val originJdk = projectJdkTable.findJdk(jdk.name) if (originJdk != null) { projectJdkTable.removeJdk(originJdk) } projectJdkTable.addJdk(jdk) myLogger.info("Add JDK from per project settings: ${jdk.name}") } } } }
37.69697
92
0.752412
9645b270e2845d7eba773c8652666db2d972e08b
1,546
js
JavaScript
src/__tests__/FrequencyMeter-test.js
vad3x/react-fm
fe1974edcdc4d6729f2e14192616464637811df9
[ "MIT" ]
4
2016-02-15T02:24:21.000Z
2020-04-01T15:30:24.000Z
src/__tests__/FrequencyMeter-test.js
vad3x/react-fm
fe1974edcdc4d6729f2e14192616464637811df9
[ "MIT" ]
null
null
null
src/__tests__/FrequencyMeter-test.js
vad3x/react-fm
fe1974edcdc4d6729f2e14192616464637811df9
[ "MIT" ]
2
2017-10-13T05:24:08.000Z
2019-07-03T18:17:31.000Z
jest.dontMock('../FrequencyMeter'); describe('FrequencyMeter', () => { it('calculate ratio', () => { var calcRatio = require('../FrequencyMeter').calcRatio; const minValue = 10; const maxValue = 100; const minBound = 0; const maxBound = 50; const ratio = calcRatio(minValue, maxValue, minBound, maxBound); expect(ratio.minValue).toBe(minValue); expect(ratio.maxValue).toBe(maxValue); expect(ratio.minBound).toBe(minBound); expect(ratio.maxBound).toBe(maxBound); expect(ratio.value).toBe(1.8); }); it('ratio value', () => { var scaleValue = require('../FrequencyMeter').scaleValue; const value = 14; const minValue = 10; const maxValue = 100; const minBound = 0; const maxBound = 50; const ratio = { minValue, maxValue, minBound, maxBound, value: 1.8 }; const scaledValue = scaleValue(value, ratio); expect(scaledValue).toBe(3); }); it('get log path data', () => { var getLogPathData = require('../FrequencyMeter').getLogPathData; const logPathData = getLogPathData({ width: 10, height: 100, data: [0, 8, 16, 32, 64, 255], maxValue: 255 }); expect(logPathData) .toBe('M0,100L0,100L0,96.86274509803921L4,' + '93.72549019607843L7,87.45098039215686L8,74.90196078431373L9,0Z'); }); });
26.20339
80
0.546572
c6d0955dcb7a4ca9cddc0207ee0d4484683231dc
5,326
py
Python
metapkg/commands/build.py
fantix/metapkg
523214b346dada45cae53b0bc7b62f3098f3b2d2
[ "Apache-2.0" ]
null
null
null
metapkg/commands/build.py
fantix/metapkg
523214b346dada45cae53b0bc7b62f3098f3b2d2
[ "Apache-2.0" ]
null
null
null
metapkg/commands/build.py
fantix/metapkg
523214b346dada45cae53b0bc7b62f3098f3b2d2
[ "Apache-2.0" ]
null
null
null
import importlib import os import platform import tempfile from poetry import packages as poetry_pkg from poetry.puzzle import solver as poetry_solver from metapkg import targets from metapkg.packages import repository as af_repo from metapkg.packages import sources as af_sources from metapkg.packages import topological from . import base class Build(base.Command): """Build the specified package build { name : Package to build. } { --dest= : Destination path. } { --keepwork : Do not remove the work directory. } { --generic : Build a generic target. } { --build-source : Build source packages. } { --build-debug : Build debug symbol packages. } { --source-ref= : VCS ref to build. } { --pkg-version= : Override package version. } { --pkg-revision= : Override package revision number (defaults to 1). } { --pkg-subdist= : Set package sub-distribution (e.g. nightly). } { --extra-optimizations : Enable extra optimization (increases build times). } """ help = """Builds the specified package on the current platform.""" _loggers = ["metapkg.build"] def handle(self): pkgname = self.argument("name") keepwork = self.option("keepwork") destination = self.option("dest") generic = self.option("generic") build_source = self.option("build-source") build_debug = self.option("build-debug") src_ref = self.option("source-ref") version = self.option("pkg-version") revision = self.option("pkg-revision") subdist = self.option("pkg-subdist") extra_opt = self.option("extra-optimizations") modname, _, clsname = pkgname.rpartition(":") mod = importlib.import_module(modname) pkgcls = getattr(mod, clsname) if src_ref: if "extras" not in pkgcls.sources[0]: pkgcls.sources[0]["extras"] = {} pkgcls.sources[0]["extras"]["version"] = src_ref pkg = pkgcls.resolve(self.output, version=version) sources = pkg.get_sources() if len(sources) != 1: self.error("Only single-source git packages are supported") return 1 source = sources[0] if not isinstance(source, af_sources.GitSource): self.error("Only single-source git packages are supported") return 1 root = poetry_pkg.ProjectPackage("__root__", "1") root.add_dependency(pkg.name, pkg.version.text) af_repo.bundle_repo.add_package(root) if generic: if platform.system() == "Linux": target = targets.generic.GenericLinuxTarget() else: target = targets.generic.GenericTarget() else: target = targets.detect_target(self.output) target.prepare() target_capabilities = target.get_capabilities() extras = [f"capability-{c}" for c in target_capabilities] repo_pool = af_repo.Pool() repo_pool.add_repository(target.get_package_repository()) repo_pool.add_repository(af_repo.bundle_repo) item_repo = pkg.get_package_repository(target, io=self.output) if item_repo is not None: repo_pool.add_repository(item_repo) provider = af_repo.Provider( root, repo_pool, self.output, extras=extras ) resolution = poetry_solver.resolve_version(root, provider) graph = {} for package in resolution.packages: deps = {req.name for req in package.requires} graph[package.name] = {"item": package, "deps": deps} packages = list(topological.sort(graph)) # Build a separate package list for build deps. build_deps = {} build_root = poetry_pkg.ProjectPackage("__build_root__", "1") build_root.add_dependency(pkg.name, pkg.version.text) build_root.build_requires = [] provider = af_repo.Provider( build_root, repo_pool, self.output, include_build_reqs=True ) resolution = poetry_solver.resolve_version(build_root, provider) graph = {} for package in resolution.packages: reqs = set(package.requires) | set( getattr(package, "build_requires", []) ) deps = {req.name for req in reqs if req.is_activated()} graph[package.name] = {"item": package, "deps": deps} build_deps = list(topological.sort(graph)) if keepwork: workdir = tempfile.mkdtemp(prefix="metapkg.") else: tempdir = tempfile.TemporaryDirectory(prefix="metapkg.") workdir = tempdir.name os.chmod(workdir, 0o755) try: target.build( root_pkg=pkg, deps=packages, build_deps=build_deps, io=self.output, workdir=workdir, outputdir=destination, build_source=build_source, build_debug=build_debug, revision=revision or "1", subdist=subdist, extra_opt=extra_opt, ) finally: if not keepwork: tempdir.cleanup()
34.584416
79
0.598385
bee3b1776fbbabe82027ef20fa783eeaed48d580
1,999
ts
TypeScript
src/app/manager/manager-routing.module.ts
NardM/Utopia-manage
85727e99625f7e712af2af18f798ac5c90761240
[ "MIT" ]
null
null
null
src/app/manager/manager-routing.module.ts
NardM/Utopia-manage
85727e99625f7e712af2af18f798ac5c90761240
[ "MIT" ]
null
null
null
src/app/manager/manager-routing.module.ts
NardM/Utopia-manage
85727e99625f7e712af2af18f798ac5c90761240
[ "MIT" ]
null
null
null
/** * Created by nardm on 19.11.16. */ import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {RequestsAcceptedComponent} from './requests/accepted/requests-accepted.component' import {RequestsArchiveComponent} from "./requests/archive/requests-archive.component"; import {RequestsNewComponent} from "./requests/new/requests-new.component"; import {RequestsPublishedComponent} from "./requests/published/requests-published.component"; import {RegisterCompanyComponent} from "./register-company/register-company.component"; import {UserComponent} from "./manager.component"; import {FormRequestComponent} from "./form-request/form-request.component"; import {ClientComponent} from "./clients/client.component"; import {FormClientItemComponent} from "./clients/form-client/client/client.component"; const managerRoutes: Routes = [ { path: '', component: UserComponent, children: [ { path: '', children: [ { path: '', component: RequestsNewComponent }, /*{ path: 'users', component: ClientComponent }, { path: 'user/:id', component: FormClientItemComponent }, { path: 'new-requests', component: RequestsNewComponent }, { path: 'published-requests', component: RequestsPublishedComponent }, { path: 'accepted-requests', component: RequestsAcceptedComponent }, { path: 'archive-requests', component: RequestsArchiveComponent },*/ ] } ] } ]; @NgModule({ imports: [ RouterModule.forChild(managerRoutes) ], exports: [ RouterModule ] }) export class ManagerRoutingModule {} /* Copyright 2016 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license */
37.018519
99
0.646823
e058f1c1e42b3f889a9d56b3abfc7178734a9289
1,965
h
C
WPF/COM/TetradEngine.h
petrsnd/tetrad
890221ca730011cac3437b92427d041cbc921db3
[ "MIT" ]
null
null
null
WPF/COM/TetradEngine.h
petrsnd/tetrad
890221ca730011cac3437b92427d041cbc921db3
[ "MIT" ]
null
null
null
WPF/COM/TetradEngine.h
petrsnd/tetrad
890221ca730011cac3437b92427d041cbc921db3
[ "MIT" ]
null
null
null
// TetradEngine.h : Declaration of the CTetradEngine #pragma once #include "resource.h" // main symbols #include "COM_i.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." #endif using namespace ATL; #include <Interfaces.h> #include <memory> // CTetradEngine class ATL_NO_VTABLE CTetradEngine : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CTetradEngine, &CLSID_TetradEngine>, public ISupportErrorInfo, public IDispatchImpl<ITetradEngine, &IID_ITetradEngine, &LIBID_COMLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { public: CTetradEngine(); DECLARE_REGISTRY_RESOURCEID(IDR_TETRADENGINE) BEGIN_COM_MAP(CTetradEngine) COM_INTERFACE_ENTRY(ITetradEngine) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: STDMETHOD(GetBoard)(PLAYER player, ULONG* encoded); STDMETHOD(GetTetrads)(PLAYER player, ULONG* tetrads); STDMETHOD(GetTargets)(IPosition* position, SAFEARRAY** targets); STDMETHOD(Move)(IPosition* from, IPosition* to, IMoveResult** result); STDMETHOD(GetOpponentMove)(IMoveResult** result); STDMETHOD(Init)(); private: Implbits::IGameEngine::Ptr m_engine; Implbits::IGameMutator::Ptr m_mutator; }; OBJECT_ENTRY_AUTO(__uuidof(TetradEngine), CTetradEngine)
28.071429
472
0.790331
4363ac030c291a77b26a8f15ed54952576eb730a
134
ts
TypeScript
lib/private/parse/parseSpaced.d.ts
andy-hanson/mason-compile
8c20d224a6ca95fd7da8dc2570e2a3b12b1795c3
[ "Unlicense" ]
null
null
null
lib/private/parse/parseSpaced.d.ts
andy-hanson/mason-compile
8c20d224a6ca95fd7da8dc2570e2a3b12b1795c3
[ "Unlicense" ]
null
null
null
lib/private/parse/parseSpaced.d.ts
andy-hanson/mason-compile
8c20d224a6ca95fd7da8dc2570e2a3b12b1795c3
[ "Unlicense" ]
null
null
null
import { Val } from '../ast/LineContent'; import { Tokens } from './Slice'; export default function parseSpaced(tokens: Tokens): Val;
33.5
57
0.708955
c692a9f39909e5ae7c743c114bed841e243b6a1f
1,020
py
Python
docs/guide/functional.py
yacth/autogoal
a55c1534161e850587e2ca3533aa2fd5ae28569e
[ "MIT" ]
157
2020-06-20T10:28:04.000Z
2022-03-26T18:20:58.000Z
docs/guide/functional.py
yacth/autogoal
a55c1534161e850587e2ca3533aa2fd5ae28569e
[ "MIT" ]
110
2020-08-10T21:50:52.000Z
2022-02-25T16:13:53.000Z
docs/guide/functional.py
yacth/autogoal
a55c1534161e850587e2ca3533aa2fd5ae28569e
[ "MIT" ]
62
2020-08-09T07:41:50.000Z
2022-03-16T01:07:47.000Z
# # Functional API # AutoGOAL's functional API allows you to transform any Python callable (e.g., a method) # into an optimizable target. In contrast with the [class-based](/guide/cfg/) and [graph-based](/guide/graph/) APIs, # the functional API does not require to know before-hand the structure of the space you want to optimize. # This enables very flexible use cases, in which you can iterate quickly, experiment, and transform deterministic code to solve # one particular task into optimizable software that seems to magically solve the problem for you in the best possible way. # Let's start with a toy example just to show the basic usage of the API. from autogoal.sampling import Sampler def generate(sampler: Sampler): x1 = sampler.continuous(0, 1, "x1") x2 = sampler.continuous(0, 1, "x2") if x1 > x2: return (x1, x2) return (0, 0) def fn(t): x1, x2 = t return x1 * x2 search = PESearch(generate, fn) best, y = search.run(1000) print(search._model) print(best, y)
28.333333
127
0.714706
c6f489678bdd92fad0aa56de553d0c9827d2a18f
910
py
Python
phangsPipeline/__init__.py
low-sky/phangs_imaging_scripts
7d60e8ef4d70e81442f46c844829ab70cbc62500
[ "MIT" ]
null
null
null
phangsPipeline/__init__.py
low-sky/phangs_imaging_scripts
7d60e8ef4d70e81442f46c844829ab70cbc62500
[ "MIT" ]
null
null
null
phangsPipeline/__init__.py
low-sky/phangs_imaging_scripts
7d60e8ef4d70e81442f46c844829ab70cbc62500
[ "MIT" ]
null
null
null
# Licensed under a MIT license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- from .casa_check import is_casa_installed casa_enabled = is_casa_installed() from .phangsLogger import setup_logger from .handlerKeys import KeyHandler from .handlerSingleDish import SingleDishHandler from .handlerVis import VisHandler from .handlerPostprocess import PostProcessHandler from .handlerDerived import DerivedHandler if casa_enabled: from .handlerImaging import ImagingHandler __all__ = ["setup_logger", "KeyHandler", "SingleDishHandler", "VisHandler", "PostProcessHandler", "DerivedHandler"] if casa_enabled: __all__.append("ImagingHandler")
35
115
0.665934
073db9f705f5f0e41929f87991fdc990535b7055
14,915
css
CSS
public/frontend/file/css/default.css
cherki-hamza/laravel-vuejs-blog
df688a746456c986f46318af8ba08ce7f2872c05
[ "MIT" ]
null
null
null
public/frontend/file/css/default.css
cherki-hamza/laravel-vuejs-blog
df688a746456c986f46318af8ba08ce7f2872c05
[ "MIT" ]
null
null
null
public/frontend/file/css/default.css
cherki-hamza/laravel-vuejs-blog
df688a746456c986f46318af8ba08ce7f2872c05
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------ * Project: Suchana * Author: CN-InfoTech * URL: hthttps://themeforest.net/user/cn-infotech * Created: 10/15/2019 ------------------------------------------------------------------- - // TABLE OF CONTENTS // - ======================================================================== # Landing Page =============================================== 1) Default CSS */ /* ========================================= */ /* Default CSS */ /* ========================================= */ @import url('https://fonts.googleapis.com/css?family=Poppins'); @import url('https://fonts.googleapis.com/css?family=Poppins:700&amp;display=swap'); * { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; background: transparent; box-sizing: border-box; } ol, ul {list-style: none; } :focus {outline: 0; } .clear {clear: both; line-height: 0; font-size: 0; } .clearfix:after { clear: both; content: '.'; display: block; visibility: hidden; height: 0; } .clearfix:after .test {color: red; } .clearfix {display: inline-block; } * html .clearfix {height: 1%; } .clearfix {display: block; } header, nav, section, article, aside, footer { display: block; } * { margin: 0; padding: 0; } body { margin: 0; padding: 0; font-size: 15px; background: #ffffff; font-family: 'Poppins', sans-serif; overflow-x: hidden; color: #384252; } /* Preloader */ #preloader { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: #fffcf8; z-index: 99999; /* makes sure it stays on top */ } #status { position: fixed; content: ''; display: block; top: 25%; left: 0; right: 0; width: 400px; height: 300px; margin: 0 auto; background: url(../images/loader.gif); /* background-color: #fff;*/ opacity: 1; visibility: visible; -webkit-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; z-index: 9999999999; } @-webkit-keyframes scaleout { 0% { -webkit-transform: scale(0); } 100% { -webkit-transform: scale(1); opacity: 0; } } @keyframes scaleout { 0% { transform: scale(0); -webkit-transform: scale(0); } 100% { transform: scale(1); -webkit-transform: scale(1); opacity: 0; } } @media(max-width: 369px){ #status{left: -40px;} } /* End Preloader */ h1,h2,h3,h4,h5,h6{ margin-bottom: 15px; color: #2a2f52; font-family: 'Poppins', sans-serif; margin-top:0; font-weight: 700; line-height: 1.5; } h1 { font-size: 48px; } h2 { font-size: 30px; } h3 { font-size: 24px; } h4 { font-size: 18px; } h5 { font-size: 15px; } h6 { font-size: 13px; } hr {border: 0.5px solid #444444; } p { font-weight: 300; line-height:1.6; margin-bottom: 15px; color: #5d5c5c; font-size: 15px; } ul {margin: 0; padding: 0; } ul li { font-size: 15px; font-weight: 300; margin-bottom: 15px; line-height: 1.5; color: #5d5c5c!important; position: relative; display:inline-block; } ol {margin: 0; counter-reset: i; position: relative; } ol li { font-size: 16px; font-weight: 400; margin-bottom: 15px; line-height: 24px; color: #181d31; padding-left: 40px; position: relative; } a { color: #333a65; background-image: linear-gradient(to right, #ffffff, #ffffff); background-position: left 87%; background-repeat: no-repeat; transition: all ease-in-out 0.5s; background-size: 0px 2px; padding-bottom: 6px; } a:hover { text-decoration: none !important; background-size: 100% 2px; transition: all ease-in-out 0.5s; } .button a, .button a:hover{background-image: none;} .home-1 a{ color: #333a65; background-image: linear-gradient(to right, #333a65, #333a65); background-position: left 87%; background-repeat: no-repeat; transition: all ease-in-out 0.5s; background-size: 0px 2px; padding-bottom: 6px; } .home-1 a:hover { text-decoration: none !important; background-size: 100% 2px; transition: all ease-in-out 0.5s; } input[type=text], input[type=email], input[type=number], input[type=search], input[type=password], input[type=tel], textarea, select, textarea#comment { font-size: 14px; font-weight: 300; background-color: #fff; border: 1px solid #eceaea; border-radius:0px; padding: 10px 25px; width: 100%; color: #444444; margin-bottom: 15px; font-family: 'Roboto', sans-serif; height: 42px; box-shadow: none; } input[type=text]:focus, input[type=email]:focus, input[type=number]:focus, input[type=search]:focus, input[type=password]:focus, input[type=tel]:focus, textarea:focus, select:focus { border-color: #ffac00; transition: all 0.5s ease; } /*select {padding: 12px 25px; }*/ textarea {border-radius: 0px; resize: vertical; } label { display: inline-block; color: #333a65; margin-bottom: 12px; font-weight: 500; } img {max-width: 100%; } blockquote { font-size: 14px; font-weight: 300; background-color: #FAF8F8; margin-bottom: 15px; border-left: 4px solid #00418c; padding: 30px 70px 30px 70px; line-height: 24px; color: #444444; margin-bottom: 20px; font-style: italic; position: relative; } blockquote:before { content: '\f10d'; font-family: fontawesome; font-size: 45px; position: absolute; top: 26px; left: 20px; color: #666; opacity: 0.1; } blockquote span {position: relative; padding-left: 20px; } blockquote span:before { content: ''; width: 12px; height: 1px; background: #ffac00; position: absolute; left: 0; top: 50%; margin-top: -2px; } /*margin none*/ .mar-0{margin:0;} /*margin top*/ .mar-top-0{margin-top:0px} .mar-top-5{margin-top:5px} .mar-top-10{margin-top:10px} .mar-top-15{margin-top:15px} .mar-top-20{margin-top:20px} .mar-top-25{margin-top:25px} .mar-top-30{margin-top:30px} .mar-top-40{margin-top:40px} .mar-top-50{margin-top:50px} .mar-top-60{margin-top:60px} .mar-top-70{margin-top:70px} .mar-top-80{margin-top:80px} /*margin bottom*/ .mar-bottom-0{margin-bottom:0px} .mar-bottom-5{margin-bottom:5px} .mar-bottom-10{margin-bottom:10px} .mar-bottom-15{margin-bottom:15px} .mar-bottom-20{margin-bottom:20px} .mar-bottom-25{margin-bottom:25px} .mar-bottom-30{margin-bottom:30px} .mar-bottom-40{margin-bottom:40px} .mar-bottom-50{margin-bottom:50px} .mar-bottom-60{margin-bottom:60px} .mar-bottom-70{margin-bottom:70px} .mar-bottom-80{margin-bottom:80px} /*padding*/ .pad-0{padding: 0!important;} .pad-top-0{padding-top:0px} .pad-top-10{padding-top:10px} .pad-top-15{padding-top:15px} .pad-top-20{padding-top:20px} .pad-top-25{padding-top:25px} .pad-top-30{padding-top:30px} .pad-top-40{padding-top:40px} .pad-top-50{padding-top:50px} .pad-top-60{padding-top:60px} .pad-top-70{padding-top:70px} .pad-top-80{padding-top:80px} .pad-bottom-10{padding-bottom:10px} .pad-bottom-15{padding-bottom:15px} .pad-bottom-20{padding-bottom:20px} .pad-bottom-25{padding-bottom:25px} .pad-bottom-30{padding-bottom:30px} .pad-bottom-40{padding-bottom:40px} .pad-bottom-50{padding-bottom:50px} .pad-bottom-60{padding-bottom:60px} .pad-bottom-70{padding-bottom:70px} .pad-bottom-80{padding-bottom:80px} /*color*/ .white{color: #fff!important;} .line-height{line-height: 1.5;} .text-uppercase{text-transform: uppercase;} section{padding:50px 0; position: relative;} /*button*/ .btn-blog, .btn-blog-1{ position: relative; border:2px solid #2a2f52; padding: 10px 20px 10px; color: #2a2f52; font-size: 15px; letter-spacing: 1px; z-index: 1; transition: all ease-in-out 0.5s; overflow: hidden; display: inline-block; } .btn-blog-1{ border:2px solid #fff; color: #fff; } .btn-blog:after, .btn-blog-1:after{ content: ''; left: 0; width: 0; background: #2a2f52; height: 100%; position: absolute; top: 0; z-index: -1; transition: all ease-in-out 0.5s; } .btn-blog-1:after{ background: #fff; } .btn-blog:hover:after, .btn-blog-1:hover:after{ width: 100%; transition: all ease-in-out 0.5s; } .btn-blog:hover, .btn-blog-1:hover{color: #fff; transition: all ease-in-out 0.5s;} .btn-blog-1:hover{color:#2a2f52; } input.btn-blog:hover{background:#2a2f52; transition: all ease-in-out 0.5s;} /*heading title*/ .section_heading{margin:0 0 6rem; text-align: center; } .section_title{margin-bottom: 15px;} p.heading_txt{margin-bottom: 0;} .mt_heading{padding: 0;} .mt_heading.headmain{padding: 0 25% 0 0;} .mt_heading h2{text-transform: capitalize; font-size: 38px;} .mt_heading h2 span{position: relative;} .mt_heading h2 span:before { content: ""; position: absolute; left: 0; right: 0; bottom: -10px; margin: 0 auto; height: 2px; width: 50%; background: -webkit-linear-gradient(-45deg, rgb(255, 173, 4) 40%,rgb(255, 255, 255) 50%,rgb(51, 58, 101) 60%); background: -webkit-linear-gradient(-45deg, rgb(255, 173, 4) 40%,rgb(255, 255, 255) 50%,rgb(51, 58, 101) 60%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(135deg, rgb(255, 173, 4) 40%,rgb(255, 255, 255) 50%,rgb(51, 58, 101) 60%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ } .inner-heading.inner-width{width: 50%;} .inner-heading{margin-bottom: 4rem; position: relative; z-index: 1;} .inner-heading h3 { position: relative; padding-left: 20px; font-weight: 300; margin-bottom: 10px; } .inner-heading h3:before { content: ""; position: absolute; left: 1px; top: 0; height: 100%; width: 4px; background: #ffac00; } .inner-heading h2{margin-bottom: 0;} @media (max-width: 991px){ .mt_heading.edu_head {text-align: left;} .mt_heading.headmain{padding: 0;} .section_heading{text-align: center;} .mt_heading{padding: 0;} } @media (max-width: 767px) { .section_heading{text-align: center;} .section_heading .button.pull-right{display: none;} .mt_heading {padding: 0px; } .heading_txt {width: 100%; } .section_title, .mission-content h2{font-size: 28px;} blockquote {padding-right: 20px; } .inner-heading h2{font-size: 32px!important;} } @media (max-width: 480px) { .mt_heading.edu_head{padding: 0;} } .title-padding{padding:0 20%; margin-bottom: 0;} @media only screen and (max-width:991px) { .title-padding{padding:0 5%; } } .blog_heading_border {position: relative;} .blog_heading_border:before { content: ""; background: #00418c; bottom: -7px; display: block; height: 2px; margin-bottom: 6px; position: absolute; width: 20%; } /*breadcrumb*/ .breadcrumb-outer{margin-top: 107px;} .breadcrumb-outer h2 { color: #fff; margin: 0; font-size: 36px; padding: 10px 0 15px; } .breadcrumb-content{ position: relative; z-index: 1; margin: 0 auto; } .breadcrumb-content:before { position: absolute; content: ''; height: 2px; background: #fff; width: 50px; top: 0px; left: 0; right: 0; margin: 0 auto; } .breadcrumb-content nav{ display: inline-block; } .breadcrumb-content ul { margin-bottom: 0; background-color:#fff; border-radius: 0; box-shadow: 0 0 5px #ccc; padding: 10px 20px; position: relative; } ul.breadcrumb:before { content: ''; position: absolute; height: 1px; width: 120%; background: white; left: -10%; right: 0; top: 20px; box-shadow: 0 0 2px #ccc; z-index: -1; } .breadcrumb-content li{ margin-bottom: 0; } .breadcrumb-content li a{ transition: all ease-in-out 0.3s; background-image: none; color: #666; } .breadcrumb-content li a:hover{ color: #6d77aa; background-image: none; transition: all ease-in-out 0.3s; } .breadcrumb-content .breadcrumb>.active{ color: #333a65!important; } .breadcrumb>li+li:before{ padding: 0 10px 0 5px; content: '|'; color:#666; } @media(max-width: 991px){ .breadcrumb-outer{margin-top: 0;} } /*pagination*/ .pagination__wrapper { background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, white 17%, white 83%, rgba(255, 255, 255, 0) 100%); background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, white 17%, white 83%, rgba(255, 255, 255, 0) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#00ffffff',GradientType=1 ); height: 50px; text-align: center; position: relative; float: left; width: 100%; } .pagination__wrapper:before, .pagination__wrapper:after { background: -webkit-linear-gradient(left, transparent 0%, rgba(0, 0, 0, 0.1) 17%, rgba(0, 0, 0, 0.1) 83%, transparent 100%); background: linear-gradient(to right, transparent 0%, rgba(0, 0, 0, 0.1) 17%, rgba(0, 0, 0, 0.1) 83%, transparent 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00000000', endColorstr='#00000000',GradientType=1 ); content: ""; height: 1px; left: 0; position: absolute; width: 60%; right: 0; margin: 0 auto; } .pagination__wrapper:before { top: -1px; } .pagination__wrapper:after { bottom: -1px; } @-webkit-keyframes hoverAnimation { from { opacity: 1; } to { opacity: 0; } } @keyframes hoverAnimation { from { opacity: 1; } to { opacity: 0; } } .pagination { display: inline-block; list-style: none; margin: 0; padding: 0; } .pagination li { display: block; float: left; padding: 5px; } .pagination li:first-child { border: none; } .pagination button, .pagination span { background: none; border: none; border-radius: 50%; box-sizing: border-box; color: rgba(0, 0, 0, 0.6); display: block; font-size: 16px; height: 40px; line-height: 40px; min-width: 40px; padding: 0; } .pagination button { outline: none; position: relative; -webkit-transition: all 170ms linear; transition: all 170ms linear; } .pagination button:before { background: rgba(0, 0, 0, 0.2); border-radius: 50%; content: ""; cursor: pointer; height: 0; left: 50%; opacity: 0; position: absolute; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); -webkit-transition: all 170ms linear; transition: all 170ms linear; top: 50%; width: 0; } .pagination button:hover:not(.active) { color: black; } .pagination button:hover:not(.active):before { -webkit-animation: hoverAnimation 510ms linear forwards; animation: hoverAnimation 510ms linear forwards; height: 40px; width: 40px; } .pagination button.active { background: rgba(0, 0, 0, 0.1); color: black; } .pagination .prev, .pagination .next { font-size: 14px; } label.error { color: red; margin-top: 5px; font-size: 14px; } .alert-success { background: #3c763d; border: none; color: #fff; } .alert-success h3{margin-bottom: 5px; color: #fbfbfb;} .alert-success p{color: #fbfbfb;}
18.927665
159
0.636473
f45d76356d2c5d2f14f730b1126be36142ffc196
1,286
ts
TypeScript
src/functions/functions.ts
Ankomahene/ms-react-progress
1dfcd64c706e5508f5be7769dc27e98ee0abe7e3
[ "MIT" ]
1
2022-03-25T02:52:44.000Z
2022-03-25T02:52:44.000Z
src/functions/functions.ts
Ankomahene/ms-react-progress
1dfcd64c706e5508f5be7769dc27e98ee0abe7e3
[ "MIT" ]
null
null
null
src/functions/functions.ts
Ankomahene/ms-react-progress
1dfcd64c706e5508f5be7769dc27e98ee0abe7e3
[ "MIT" ]
null
null
null
import { AlignmentType, BackgroundType, IProgressOptions } from '../models/models'; export const getPercentageValue = (value: number, maxValue: number) => { return isNaN(value) ? 0 : (value / (isNaN(maxValue) ? 100 : maxValue)) * 100; }; export const getLabelAlignment = (alignment: AlignmentType) => { return alignment === 'right' ? 'flex-end' : alignment === 'center' ? alignment : 'flex-start'; }; export const getProgressBackgroundStyle = ( backgroundType: BackgroundType, barColor: string ): { [key: string]: string } => { if (barColor.startsWith('#')) { return backgroundType === 'striped' ? { backgroundImage: `repeating-linear-gradient( 135deg, ${barColor}66, ${barColor}66 5px, ${barColor} 5px, ${barColor} 10px)`, } : { background: barColor }; } return { background: barColor }; }; export const getDefaultOptions = (): IProgressOptions => ({ type: 'regular', maxValue: 100, containerColor: '#dddddd', containerStyle: 'bg', barColor: '#2c43ac', customLabel: '', labelVisibility: true, labelAlignment: 'left', labelColor: 'white', labelSize: '12px', height: '15px', borderRadius: '10px', stripeAnimation: false, stripeAnimationDuration: '10s', labelPosition: 'center', showMaxValue: false, });
29.906977
133
0.661742
05a8f5f8b34eb3b45b0057c688d35f1991141703
2,822
py
Python
granite/utils.py
frenchtoast747/granite
294da4c0ba18ed6d8b5a862ddf0ce5fb767101c0
[ "MIT" ]
1
2018-07-03T07:46:07.000Z
2018-07-03T07:46:07.000Z
granite/utils.py
frenchtoast747/granite
294da4c0ba18ed6d8b5a862ddf0ce5fb767101c0
[ "MIT" ]
1
2021-10-18T23:08:02.000Z
2021-10-18T23:08:02.000Z
granite/utils.py
frenchtoast747/granite
294da4c0ba18ed6d8b5a862ddf0ce5fb767101c0
[ "MIT" ]
null
null
null
""" Utility for internal library use. """ import os def cached_property(fn): """ Converts a class's method into property and cache's the getter value. Simple decorator a method with this function and it will be converted into a property (attribute access) and the calculation to retrieve the value will be cached so that the initial call performs the calculation, but subsequent calls will use the cache. """ attr_name = '_' + fn.__name__ def _wrapper(self): value = getattr(self, attr_name, None) if value is None: value = fn(self) setattr(self, attr_name, value) return value _wrapper.__name__ = fn.__name__ _wrapper.__doc__ = fn.__doc__ return property(_wrapper) def path_as_key(path, relative_to=None): """ Converts a path to a unique key. Paths can take on several unique forms but all describe the same node on the file system. This function will take a path and produce a key that is unique such that several paths that point to the same node on the file system will all be converted to the same path. This is useful for converting file paths to keys for a dictionary. Note: all paths will be separated by forward slashes. Args: path (str): the path to convert. relative_to (str): make the key relative to this path Returns: str: the unique key from the path Examples:: >>> path_as_key('./file.txt') == path_as_key('file.txt') True """ # if it's not already absolute, make it so. path = os.path.abspath(path) # convert it relative to the CWD path = os.path.relpath(path, start=relative_to) # normalize it by removing all instances of "." and ".." path = os.path.normpath(path) # convert all backslashes to forward to normalized the path separators path = path.replace('\\', '/') return path def _dummy_function(): """Used by the get_mock_patcher_types() function""" _dummy_dict = {} def get_mock_patcher_types(): """ Gets the Classes of the mock.patcher functions. We're using this for the automatic mocking mixin in order to determine if a class-level attribute is a patcher instance. Returns: tuple: a unique list of the patcher types used by mock. """ if get_mock_patcher_types.types is not None: return get_mock_patcher_types.types try: from unittest import mock except ImportError: import mock types = tuple({ type(mock.patch(__name__ + '._dummy_function')), type(mock.patch.object(_dummy_function, 'some_method')), type(mock.patch.dict(_dummy_dict)), }) get_mock_patcher_types.types = types return types get_mock_patcher_types.types = None
26.87619
78
0.66832
3fabc2d02fcedcb979770f79c21149b56a1f03ab
25,048
sql
SQL
bemo_consulting.sql
masanam/BeMoConsulting
803c955326db3a144782c5a8b9824546d6ca3958
[ "MIT" ]
null
null
null
bemo_consulting.sql
masanam/BeMoConsulting
803c955326db3a144782c5a8b9824546d6ca3958
[ "MIT" ]
null
null
null
bemo_consulting.sql
masanam/BeMoConsulting
803c955326db3a144782c5a8b9824546d6ca3958
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Nov 14, 2020 at 01:33 AM -- Server version: 5.7.24 -- PHP Version: 7.3.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `bemo_consulting` -- -- -------------------------------------------------------- -- -- Table structure for table `contacts` -- DROP TABLE IF EXISTS `contacts`; CREATE TABLE IF NOT EXISTS `contacts` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `country` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `content` text COLLATE utf8mb4_unicode_ci, `status` int(11) DEFAULT NULL, `created_by` int(11) DEFAULT NULL, `updated_by` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `contacts` -- INSERT INTO `contacts` (`id`, `name`, `email`, `phone`, `country`, `title`, `content`, `status`, `created_by`, `updated_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 'masanam', '[email protected]', NULL, NULL, NULL, 'test', NULL, NULL, NULL, '2020-11-13 10:21:34', '2020-11-13 10:21:34', NULL), (2, 'Test', '[email protected]', NULL, NULL, NULL, 'test', NULL, NULL, NULL, '2020-11-13 10:30:44', '2020-11-13 10:30:44', NULL); -- -------------------------------------------------------- -- -- Table structure for table `contents` -- DROP TABLE IF EXISTS `contents`; CREATE TABLE IF NOT EXISTS `contents` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `category_id` int(11) DEFAULT NULL, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `seotitle` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `summary` text COLLATE utf8mb4_unicode_ci, `content` text COLLATE utf8mb4_unicode_ci, `picture` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `picture_description` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `tag` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `active` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `published_at` timestamp NULL DEFAULT NULL, `headline` int(11) DEFAULT NULL, `hits` int(11) DEFAULT NULL, `status` int(11) DEFAULT NULL, `created_by` int(11) DEFAULT NULL, `updated_by` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `contents` -- INSERT INTO `contents` (`id`, `category_id`, `title`, `seotitle`, `summary`, `content`, `picture`, `picture_description`, `tag`, `active`, `published_at`, `headline`, `hits`, `status`, `created_by`, `updated_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 1, 'Ultimate Guide to CDA Structured Interview: Tips & Proven Strategies to Help You Prepare & Ace Your CDA Interview', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:46:07', '2020-11-13 07:46:07', NULL), (2, 1, 'Overview:', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\">The purpose of the dental school interview<br />History and rationale of the CDA interview <br />Types of Questions <br />The Seven Competencies<br />Structure of the CDA interview <br /></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a title=\"How To Prepare\" href=\"https://cdainterview.com/how-to-prepare-for-cda-interview.html\" rel=\"self\">How to prepare for your CDA Interview</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><br /></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a title=\"CDA Interview Questions\" href=\"https://cdainterview.com/sample-cda-interview-questions.html\" rel=\"self\">Sample CDA interview questions</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><br /></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a href=\"http://bemoacademicconsulting.com/Dental-School-Interview-Preparation.html\" target=\"_blank\" rel=\"external noopener\">BeMo CDA-structured interview prep program</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><br /></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a title=\"Contact Us\" href=\"https://cdainterview.com/contact-us.php\" rel=\"self\">Contact us</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><br /></span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:47:18', '2020-11-13 07:47:18', NULL), (3, 1, 'What is the purpose of the dental school interview?', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\">Regardless of the format of dental school interview (e.g. CDA structured interview, MMI, or Panel interview), the purpose of the interview is rather straightforward and remains constant across the board: to assess the personality and Non-Cognitive Skills (NCSs) of the candidate. <br /><br />What are NCSs? By these we mean the following: Communication skills, interpersonal skills, ethical and moral decision making capacity, maturity, professionalism, sense of social responsibility, service to community, leadership, initiative, scholarship, ability to collaborate with others, conflict resolution skills, etc. <br /><br />Research has shown that, although academic performance (i.e. GPA and DAT scores) is a great indicator of didactic abilities in the first and second years of dental school, it provides, however, a very poor predictive value when it comes to future clinical performance. In fact, research shows that, an effective interview process is the best indicator of future clinical performance in the upper years, as it gives insight into the characteristics of the candidate and whether or not there will be a likelihood of future behavioural problems (an issue that dental schools constantly encounter and struggle to overcome). For example, it has been shown that those candidates who are \"conscientious\" and \"open to new experiences\" perform more effectively in the third and fourth years of dental school studies, where the education takes place in a clinical setting for the most part. <br /><br />Thus, dental schools, much like other professional schools, have over the past decade spent a lot of resources to devise the most effective interview process that will give them insight into the NCSs of their future candidates. And of course, for Canadian dental schools the answer has been the Canadian Dental Association\'s structured interview or CDA structured interviews. </span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:47:45', '2020-11-13 07:47:45', NULL), (4, 1, 'Regardless of the format of dental school interview (e.g. CDA structured interview, MMI, or Panel interview), the purpose of the interview is rather straightforward and remains constant acro', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><br />Recall from our discussion above that we said an effective interview process is the most reliable way to select candidates who perform well clinically. Well in an attempt to test this theory, in 2004, Smithers et al. conducted a study, which produced results that were so shocking, that it unequivocally reinforced the Canadian Dental Association\'s earlier decision to commission a \"new structured interview based on state-of-the-art contemporary interview techniques\" (i.e. CDA structured interview) <br /><br />What were these shocking results you may ask? The evidence gathered by Smithers et al. (2004) simply reinforced earlier suspicions about the ineffectiveness of traditional interview processes. They showed that, \"a typical [traditional] admissions interview was in fact worse than neutral in that it was negatively associated with students\' performance in the first year of dental training, did not predict academic performance, and may have led to poor selection decisions.\" Thus, it should come as no surprise that the traditional panel interview has been replaced by most dental school with the CDA structured interview, which is a more reliable and valid future predictor of clinical performance. <br /><br />The CDA interview was not only re-structured in its format of delivery, but it was also restructured in terms of the type of questions that would be ask, and how they would be rated or scored by the interviewers. Let us first talk about the type of questions that you may encounter on your CDA structured interview. </span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:48:05', '2020-11-13 07:48:05', NULL), (5, 1, 'Recall from our discussion above that we said an effective interview process is the most reliable way to select candidates who perform well clinically. Well in an attempt to test this theory', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><br />The types of questions that you may be asked during your dental school interview can be divided into two categories: (1) Situational Interview (SI) questions and (2) Patterned Behaviour Descriptive Interview (PBDI) questions. SI questions are those in which the candidates is placed in a hypothetical situations (i.e. vignette) and is asked what they would react in that given situation. For example, <br /><br />\"You are babysitting your sister&rsquo;s young child, who is nervous and upset about his mother being away. You are trying to calm him down and offer him some ice cream. As you are dishing out the ice cream, the child bites down hard on your hand. How would you react?\" <br /><br />Conversely, PBDI type questions, ask the candidates \"about past behaviour with the assumption that past behaviour is the best predictor of future behaviour.\" An example of a PBDI type questions is: <br /><br /><br />Many of us have had to deal with juggling busy schedules. Think of a time in the past when an important but unscheduled situation arose that required your attention, but you had a number of prior commitments on your agenda. What did you do? What was the outcome? <br /><br />Notice how SI questions are typically future-oriented, as opposed to PBDI questions, which are past-oriented. The specific and actual SI and PBDI questions are devised according to seven competencies, that the CDA has found to be reliable and valid indicators of future performance. In other words, every question that is asked during a dental school interview, regardless of being a SI or PBDI question, will address one or more than one of the seven competencies. </span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:48:31', '2020-11-13 07:48:31', NULL), (6, 1, 'The types of questions that you may be asked during your dental school interview can be divided into two categories: (1) Situational Interview (SI) questions and (2) Patterned Behaviour Desc', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\">1. Communication: does the applicant have excellent communication skills?<br />2. Conscientiousness: is the applicant thorough, careful to do tasks well?<br />3. Integrity : is the applicant honest with themselves and others?<br />4. Judgment and analysis: does the applicant have the capability to make sound judgments? Do they gather all the facts before making a decision?<br />5. self-control : Does the applicant remain calm and in control in difficult situations?<br />6. sensitivity to others : Does the applicant show empathy towards others? Do they take the feelings of others into consideration?<br />7. Tact and diplomacy : Does the applicant show sensitivity in dealing with difficult issues? Does the applicant possess the necessary skills to deal with others without causing negative feelings?<br /><br />Notice in the above examples that the SI sample question is addressing the competencies of self-control, sensitivity to others, communication, while the PBDI question addresses the competencies of conscientiousness, Integrity, and judgement and analysis. In all of the questions that will be asked of you during your interview, the competency of communication is a constant that is continuously tested and retested. In order to be successful, however, you will have to be able to know which other competencies also apply to the question so that you can formulate an appropriate response, which touches on the key factors essential for the interviewers. </span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:48:51', '2020-11-13 07:48:51', NULL), (7, 1, '1. Communication: does the applicant have excellent communication skills? 2. Conscientiousness: is the applicant thorough, careful to do tasks well? 3. Integrity : is the applicant honest wi', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\">The CDA structured interview is comprised of seven questions, one for each of the seven competencies described above. Each question, which can either be a SI or a PBDI type, is scored on a 5-point scale for a total and a maximum of 35 points by two interviewers who are either a pair of dentists, or senior dental students. The interview usually takes about 20-30 minutes to be completed. <br /><br />Click </span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a title=\"How To Prepare\" href=\"https://cdainterview.com/how-to-prepare-for-cda-interview.html\" rel=\"self\">here</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"> to learn how to prepare for your CDA interview<br /><br />Click </span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a title=\"CDA Interview Questions\" href=\"https://cdainterview.com/sample-cda-interview-questions.html\" rel=\"self\">here</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"> to practice with our sample CDA interview questions<br /><br />Click </span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"><a href=\"http://bemoacademicconsulting.com/Dental-School-Interview-Preparation.html\" target=\"_blank\" rel=\"external noopener\">here</a></span><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\"> to learn more about our money-back guarantee CDA interview preparation programs. </span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:49:10', '2020-11-13 07:49:10', NULL), (8, 1, 'to learn more about our money-back guarantee CDA interview preparation programs. Reference:', NULL, NULL, '<p><span style=\"font: 16px Arial, Verdana, Helvetica, sans-serif;\">Poole A., Catano, VM., and Cunningham, DP. Predicting performance in Canadian dental schools: the new CDA structured interview, a new personality assessment, and the DAT. Journal of Dental Education. 2007; 71: 664 - 676.</span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 07:49:26', '2020-11-13 07:49:26', NULL), (9, 2, 'BeMo Academic Consulting Inc.', NULL, NULL, '<p><span style=\"font-size: 13px; font-weight: bold;\"><u>Toll Free</u></span><span style=\"font-size: 13px;\">: </span><span style=\"font-size: 14px;\">1-855-900-BeMo (2366)</span><span style=\"font-size: 13px;\"><br /></span><span style=\"font-size: 13px; font-weight: bold;\"><u>Email</u></span><span style=\"font-size: 13px;\">: </span><span style=\"font-size: 14px;\">[email protected]</span></p>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2020-11-13 09:30:28', '2020-11-13 09:30:28', NULL); -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- DROP TABLE IF EXISTS `failed_jobs`; CREATE TABLE IF NOT EXISTS `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `menus` -- DROP TABLE IF EXISTS `menus`; CREATE TABLE IF NOT EXISTS `menus` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `parent_id` int(11) DEFAULT NULL, `type` int(11) DEFAULT NULL, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `content` text COLLATE utf8mb4_unicode_ci, `picture` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `meta_title` text COLLATE utf8mb4_unicode_ci, `meta_keyword` text COLLATE utf8mb4_unicode_ci, `description` text COLLATE utf8mb4_unicode_ci, `link` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `orderid` int(11) DEFAULT NULL, `status` int(11) DEFAULT NULL, `created_by` int(11) DEFAULT NULL, `updated_by` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `menus` -- INSERT INTO `menus` (`id`, `parent_id`, `type`, `title`, `content`, `picture`, `meta_title`, `meta_keyword`, `description`, `link`, `orderid`, `status`, `created_by`, `updated_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 1, 1, 'Main', NULL, NULL, 'FREE Ultimate Guide to CDA Interviews: Tips & Proven Strategies to Help You Prepare & Ace Your CDA Structured Interview', 'FREE Ultimate Guide to CDA Interviews: Tips & Proven Strategies to Help You Prepare & Ace Your CDA Structured Interview', NULL, 'main', 1, 1, NULL, NULL, '2020-11-13 07:34:37', '2020-11-13 09:11:37', NULL), (2, 1, 1, 'Contact Us', NULL, NULL, NULL, NULL, NULL, 'contact-us', 2, NULL, NULL, NULL, '2020-11-13 07:35:07', '2020-11-13 09:11:48', NULL); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- DROP TABLE IF EXISTS `migrations`; CREATE TABLE IF NOT EXISTS `migrations` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- DROP TABLE IF EXISTS `password_resets`; CREATE TABLE IF NOT EXISTS `password_resets` ( `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, KEY `password_resets_email_index` (`email`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `settings` -- DROP TABLE IF EXISTS `settings`; CREATE TABLE IF NOT EXISTS `settings` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `facebook` text COLLATE utf8mb4_unicode_ci, `google` text COLLATE utf8mb4_unicode_ci, `ads` text COLLATE utf8mb4_unicode_ci, `disclaimer` text COLLATE utf8mb4_unicode_ci, `created_by` int(11) DEFAULT NULL, `updated_by` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `settings` -- INSERT INTO `settings` (`id`, `title`, `facebook`, `google`, `ads`, `disclaimer`, `created_by`, `updated_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, NULL, '<script>(function() {\r\n var _fbq = window._fbq || (window._fbq = []);\r\n if (!_fbq.loaded) {\r\n var fbds = document.createElement(\'script\');\r\n fbds.async = true;\r\n fbds.src = \'//connect.facebook.net/en_US/fbds.js\';\r\n var s = document.getElementsByTagName(\'script\')[0];\r\n s.parentNode.insertBefore(fbds, s);\r\n _fbq.loaded = true;\r\n }\r\n _fbq.push([\'addPixelId\', \'235586069975455\']);\r\n})();\r\nwindow._fbq = window._fbq || [];\r\nwindow._fbq.push([\'track\', \'PixelInitialized\', {}]);\r\n</script>\r\n<noscript><img height=\"1\" width=\"1\" alt=\"\" style=\"display:none\" src=\"https://www.facebook.com/tr?id=235586069975455&ev=NoScript\" /></noscript><!-- End Google Analytics -->', '<!-- Start Google Analytics -->\r\n<script>\r\n (function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){\r\n (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\r\n m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\r\n })(window,document,\'script\',\'//www.google-analytics.com/analytics.js\',\'ga\');\r\n\r\n ga(\'create\', \'UA-56991678-1\', \'auto\');\r\n ga(\'send\', \'pageview\');\r\n\r\n</script>', NULL, NULL, NULL, NULL, '2020-11-13 17:56:51', '2020-11-13 17:56:51', NULL); -- -------------------------------------------------------- -- -- Table structure for table `sliders` -- DROP TABLE IF EXISTS `sliders`; CREATE TABLE IF NOT EXISTS `sliders` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `description` text COLLATE utf8mb4_unicode_ci, `picture` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `orderid` int(11) DEFAULT NULL, `status` int(11) DEFAULT NULL, `created_by` int(11) DEFAULT NULL, `updated_by` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `sliders` -- INSERT INTO `sliders` (`id`, `title`, `description`, `picture`, `orderid`, `status`, `created_by`, `updated_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 'CDA Interview Guide', NULL, 'storage/files/shares/pictture/cda-interview-guide.jpg', 1, NULL, NULL, NULL, '2020-11-13 07:55:11', '2020-11-13 08:08:40', NULL), (2, 'Contact Us', NULL, 'storage/files/shares/pictture/contact-us.png', 2, NULL, NULL, NULL, '2020-11-13 09:24:20', '2020-11-13 09:26:59', NULL); -- -------------------------------------------------------- -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; CREATE TABLE IF NOT EXISTS `users` ( `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `users_email_unique` (`email`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 'Administrator', '[email protected]', NULL, '$2y$10$Sb3.8WIUzsww7j9c4SwxJeceqVZSp0y8Z8nRCor1VLHD6HkIOr3Wq', NULL, '2020-11-13 03:42:54', '2020-11-13 03:42:54', NULL); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
88.508834
2,170
0.72421
917ddbf7613697996da34de8fb614b67a6316b21
2,610
lua
Lua
lua/FTerm/termlist.lua
winter233/FTerm.nvim
d550da9472037eceaf17f0cdf6112116576abd45
[ "MIT" ]
null
null
null
lua/FTerm/termlist.lua
winter233/FTerm.nvim
d550da9472037eceaf17f0cdf6112116576abd45
[ "MIT" ]
null
null
null
lua/FTerm/termlist.lua
winter233/FTerm.nvim
d550da9472037eceaf17f0cdf6112116576abd45
[ "MIT" ]
null
null
null
local terminal = require("FTerm.terminal") local TermList = {} function TermList:new() local tl = { term_list = {}, selected_term = 0, active = false, cnt = 0, opts = {} } self.__index = self return setmetatable(tl, self) end function TermList:setup(opts) self.opts = opts end function TermList:toggle() if self.selected_term == 0 then self:create() else if self.active then self.term_list[self.selected_term]:close() self.active = false else self.active = true self.term_list[self.selected_term]:open() end end end function TermList:create(opts) if self.active then if self.selected_term ~= 0 then self.term_list[self.selected_term]:close() end end local new_term = terminal:new() local opts = opts or self.opts new_term:setup(opts) self.cnt = self.cnt + 1 self.term_list[self.cnt] = new_term self.selected_term = self.cnt self.active = true new_term:open() vim.api.nvim_command("autocmd! TermClose <buffer> lua require('FTerm').close()") end function TermList:close() self.active = false self.term_list[self.selected_term] = nil self.cnt = self.cnt - 1 if self.cnt ~= 0 then if self.selected_term > self.cnt then self.selected_term = self.cnt end local index = 1 local new_list = {} for _, term in pairs(self.term_list) do new_list[index] = term index = index + 1 end self.term_list = new_list else self.selected_term = 0 end end function TermList:find_prev() repeat if self.selected_term > 1 then self.selected_term = self.selected_term - 1 else self.selected_term = self.cnt end until self.term_list[self.selected_term] end function TermList:select_prev() if self.cnt <= 1 then return end self.term_list[self.selected_term]:close() self:find_prev() self.term_list[self.selected_term]:open() end function TermList:find_next() repeat if self.selected_term < self.cnt then self.selected_term = self.selected_term + 1 else self.selected_term = 1 end until self.term_list[self.selected_term] end function TermList:select_next() if self.cnt <= 1 then return end self.term_list[self.selected_term]:close() self:find_next() self.term_list[self.selected_term]:open() end return TermList
23.303571
84
0.61341
d2e6aab98ebf22243a604b2e81478795b5e5cd9f
190
rb
Ruby
db/migrate/20121030135622_log_entries_indexes.rb
dumitru-tap-at-endava/porta
7fabcc4ef1b25e498f76511f2a0b42c04170bdf2
[ "Apache-2.0" ]
53
2018-09-19T18:06:10.000Z
2022-02-21T18:01:48.000Z
db/migrate/20121030135622_log_entries_indexes.rb
dumitru-tap-at-endava/porta
7fabcc4ef1b25e498f76511f2a0b42c04170bdf2
[ "Apache-2.0" ]
1,552
2018-09-20T04:08:15.000Z
2022-03-31T16:37:19.000Z
db/migrate/20121030135622_log_entries_indexes.rb
dumitru-tap-at-endava/porta
7fabcc4ef1b25e498f76511f2a0b42c04170bdf2
[ "Apache-2.0" ]
62
2018-09-20T09:45:13.000Z
2022-03-06T07:07:24.000Z
class LogEntriesIndexes < ActiveRecord::Migration def self.up add_index :log_entries, [ :provider_id ] end def self.down remove_index :log_entries, [ :provider_id ] end end
19
49
0.721053
cd56d6f08d407437de6b0036167547d49452d294
2,431
cs
C#
packaging/windows/Dotnet.Cli.Msi.Tests/MsiManager.cs
robmen/dotnetcli
0d210cab9166261b5051ec6469e338e5ee2f1276
[ "MIT" ]
null
null
null
packaging/windows/Dotnet.Cli.Msi.Tests/MsiManager.cs
robmen/dotnetcli
0d210cab9166261b5051ec6469e338e5ee2f1276
[ "MIT" ]
null
null
null
packaging/windows/Dotnet.Cli.Msi.Tests/MsiManager.cs
robmen/dotnetcli
0d210cab9166261b5051ec6469e338e5ee2f1276
[ "MIT" ]
1
2019-02-27T07:19:45.000Z
2019-02-27T07:19:45.000Z
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Deployment.WindowsInstaller; using Microsoft.Deployment.WindowsInstaller.Package; namespace Dotnet.Cli.Msi.Tests { public class MsiManager { private string _msiFile; private string _productCode; private InstallPackage _installPackage; public ProductInstallation Installation { get { return ProductInstallation.AllProducts.SingleOrDefault(p => p.ProductCode == _productCode); } } public string InstallLocation { get { return IsInstalled ? Installation.InstallLocation : null; } } public bool IsInstalled { get { var prodInstall = Installation; return Installation == null ? false : prodInstall.IsInstalled; } } public string UpgradeCode { get { return _installPackage.Property["UpgradeCode"]; } } public MsiManager(string msiFile) { _msiFile = msiFile; var ispackage = Installer.VerifyPackage(msiFile); if (!ispackage) { throw new ArgumentException("Not a valid MSI file", msiFile); } _installPackage = new InstallPackage(msiFile, DatabaseOpenMode.ReadOnly); _productCode = _installPackage.Property["ProductCode"]; } public bool Install(string customLocation = null) { string dotnetHome = ""; if (!string.IsNullOrEmpty(customLocation)) { dotnetHome = $"DOTNETHOME={customLocation}"; } Installer.SetInternalUI(InstallUIOptions.Silent); Installer.InstallProduct(_msiFile, $"ACTION=INSTALL ALLUSERS=2 ACCEPTEULA=1 {dotnetHome}"); return IsInstalled; } public bool UnInstall() { if (!IsInstalled) { throw new InvalidOperationException($"UnInstall Error: Msi at {_msiFile} is not installed."); } Installer.SetInternalUI(InstallUIOptions.Silent); Installer.InstallProduct(_msiFile, "REMOVE=ALL"); return !IsInstalled; } } }
27.011111
109
0.555738
38db8c1e859abf02cf0cf5d49a053a9d811a7852
358
php
PHP
app/Models/Ecs_ticket.php
PIScrew/Nawarin-API
aada72890f5411a62368ec86daef3bc3cfe8557c
[ "MIT" ]
null
null
null
app/Models/Ecs_ticket.php
PIScrew/Nawarin-API
aada72890f5411a62368ec86daef3bc3cfe8557c
[ "MIT" ]
null
null
null
app/Models/Ecs_ticket.php
PIScrew/Nawarin-API
aada72890f5411a62368ec86daef3bc3cfe8557c
[ "MIT" ]
null
null
null
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Ecs_ticket extends BaseModel { use SoftDeletes; public function ticketType(){ return $this->belongsTo(Ecs_ticket_type::class); } public function user(){ return $this->belongsTo(Ecs_user::class); } }
19.888889
56
0.706704
3894ecdd928b79825abf54a007693472dcb8727b
2,478
php
PHP
modx.loc/core/lexicon/nl/element.inc.php
MCRen88/domains
9507e7896627653f25afb968232f571892b80313
[ "MIT" ]
null
null
null
modx.loc/core/lexicon/nl/element.inc.php
MCRen88/domains
9507e7896627653f25afb968232f571892b80313
[ "MIT" ]
null
null
null
modx.loc/core/lexicon/nl/element.inc.php
MCRen88/domains
9507e7896627653f25afb968232f571892b80313
[ "MIT" ]
null
null
null
<?php /** * English language strings for Elements * * @package modx * @subpackage lexicon */ $_lang['element'] = 'Element'; $_lang['element_err_nf'] = 'Element niet gevonden.'; $_lang['element_err_ns'] = 'Element niet gespecificeerd.'; $_lang['element_err_staticfile_exists'] = 'A static file already exists within the specified path.'; $_lang['element_static_source_immutable'] = 'Het statisch gespecificeerde bestand als bron voor het element is niet schrijfbaar! Je kunt de inhoud van dit element niet bewerken in de manager.'; $_lang['element_static_source_protected_invalid'] = 'Je kunt jouw element niet wijzen naar de MODX configuratie map; dit is een beveiligde, niet toegankelijke map.'; $_lang['is_static'] = 'Extern Bestand'; $_lang['is_static_msg'] = 'Geeft aan of de bron van dit element in een extern bestand is opgeslagen.'; $_lang['quick_create'] = 'Snel aanmaken'; $_lang['quick_create_chunk'] = 'Snel chunk aanmaken'; $_lang['quick_create_plugin'] = 'Nieuwe plugin'; $_lang['quick_create_snippet'] = 'Snel snippet aanmaken'; $_lang['quick_create_template'] = 'Snel template aanmaken'; $_lang['quick_create_tv'] = 'Snel TV aanmaken'; $_lang['quick_update_chunk'] = 'Snel chunk updaten'; $_lang['quick_update_plugin'] = 'Plugin snel bewerken'; $_lang['quick_update_snippet'] = 'Snippet snel bewerken'; $_lang['quick_update_template'] = 'Template snel aanpassen'; $_lang['quick_update_tv'] = 'TV snel bewerken'; $_lang['properties_export'] = 'Exporteer Properties'; $_lang['properties_import'] = 'Importeer Properties'; $_lang['property_preprocess'] = 'Tags uitvoeren in Property waardes'; $_lang['property_preprocess_msg'] = 'Wanneer ingeschakeld zullen tags in de Properties uitgevoerd worden voordat het element ze gebruikt.'; $_lang['static_file'] = 'Static Bestand'; $_lang['static_file_msg'] = 'Een externe bestandslocatie waar de element bron is opgeslagen.'; $_lang['static_source'] = 'Media Source voor Static Bestand'; $_lang['static_source_msg'] = 'MODX zal deze Media Source gebruiken wanner gezocht word naar het Static Bestand voor dit element. Wanneer je "Geen" gebruikt dien je een absoluut pad op de bestandsserver in te voeren.'; $_lang['tv_elements'] = 'Invoer Optie Waarden'; $_lang['tv_default'] = 'Standaard Waarde'; $_lang['tv_type'] = 'Invoer Type'; $_lang['tv_output_type'] = 'Uitvoer Type'; $_lang['tv_output_type_properties'] = 'Uitvoer Type Eigenschappen'; $_lang['static_file_ns'] = 'Een statisch bestand moet opgegeven worden.';
61.95
218
0.755851
b96eec57b16ec5371f7edac8868a7c4725cfc2df
5,246
css
CSS
public/css/style.css
JB-Doffemont/Tre_local
4e998572b5a8593f011a9b266ca234974860edd5
[ "MIT" ]
null
null
null
public/css/style.css
JB-Doffemont/Tre_local
4e998572b5a8593f011a9b266ca234974860edd5
[ "MIT" ]
null
null
null
public/css/style.css
JB-Doffemont/Tre_local
4e998572b5a8593f011a9b266ca234974860edd5
[ "MIT" ]
null
null
null
body { background-color: #26acff; } .fontStyle { font-family: "Lobster", cursive; color: whitesmoke; font-size: 25px; margin-bottom: 10px; } p { margin: 0; padding: 0; text-align: center; } .btncss { display: flex; justify-content: center; align-items: center; width: 25px; height: 25px; background: none; border: none; margin: 0; padding: 0; } .btnCssWhite { display: flex; justify-content: center; align-items: center; width: 25px; height: 25px; background: #0280ced6; margin: 0; padding: 0; box-shadow: 1px 1px 2px whitesmoke; } .imgcss { width: 20px; margin: 0; } /* * NAV BAR */ .navbar { background-color: #0280ced6; color: whitesmoke; } #navbarDropdown { color: whitesmoke; } .navbar-brand { text-decoration: none; color: whitesmoke; } /* * CONTAINER BOARD HOME */ .boardContainer { display: flex; flex-wrap: wrap; margin: 26px 0; } .boardContain { display: flex; justify-content: center; align-items: center; width: 28%; height: 100px; background: url("../img/imgTab.jpg"); background-repeat: no-repeat; background-size: auto; margin: 10px auto; text-transform: uppercase; font-size: 18px; font-weight: 600; text-decoration: none; color: whitesmoke; text-shadow: black 1px 1px; border-radius: 20px; } .boardContain:hover { text-decoration: none; color: #3cb9fc; transform: rotate(2deg); transition: 0.7s; } .card-header { background-color: #0c97ed; color: whitesmoke; font-size: 20px; } .btn { font-family: "Lobster", cursive; font-size: 20px; color: whitesmoke; background-color: #0280ced6; border-color: #0280ced6; height: 50px; } .btn:hover { color: whitesmoke; background-color: #5c1bfff8; border-color: #5c1bfff8; } .btn-css-board { background: none; border: none; } /* * MODALE */ .modal-header { font-family: "Lobster", cursive; background-color: #0280ced6; } .premium { font-weight: 800; } /* * LIST CONTAINER BOARD PAGE */ .listContainer { display: flex; flex-wrap: wrap; margin-top: 26px; margin-bottom: 26px; font-family: "Lobster", cursive; font-size: 20px; } .listTitle { font-size: 35px; } .display-4 { font-family: "Lobster", cursive; color: whitesmoke; font-weight: 500; } .inputModify { height: 25px; width: 119px; display: flex; margin: 0 0 0 5px; padding: 0; justify-content: center; align-items: center; } .btnSave { height: 25px; width: 59px; display: flex; margin: 0; padding: 0; justify-content: center; align-items: center; } .card { box-shadow: 4px 4px 8px rgb(22, 7, 142); } /* * WELCOME PAGE */ .containerWelcome { position: relative; width: auto; height: 760px; background: url("../img/welcome.JPG"); background-repeat: no-repeat; background-size: contain; } .textTrello { font-family: "Lobster", cursive; color: whitesmoke; font-size: 80px; width: 500px; margin: 15px; } .titleTrello { position: absolute; bottom: 302px; right: 11px; color: whitesmoke; font-size: 80px; } .defileParent { display: block; color: whitesmoke; overflow: hidden; position: relative; table-layout: fixed; width: auto; font-size: 20px; } .defile { display: block; -webkit-animation: linear marqueelike 20s infinite; -moz-animation: linear marqueelike 20s infinite; -o-animation: linear marqueelike 20s infinite; -ms-animation: linear marqueelike 20s infinite; animation: linear marqueelike 20s infinite; margin-left: -100%; padding: 0 5px; text-align: left; height: 25px; } .defile:after { content: attr(data-text); position: absolute; white-space: nowrap; padding-left: 10px; } @-webkit-keyframes marqueelike { 0%, 100% { margin-left: 0; } 99.99% { margin-left: -100%; } } @-moz-keyframes marqueelike { 0%, 100% { margin-left: 0; } 99.99% { margin-left: -100%; } } @-o-keyframes marqueelike { 0%, 100% { margin-left: 0; } 99.99% { margin-left: -100%; } } @-ms-keyframes marqueelike { 0%, 100% { margin-left: 0; } 99.99% { margin-left: -100%; } } @keyframes marqueelike { 0%, 100% { margin-left: 0; } 99.99% { margin-left: -100%; } } @media only screen and (max-width: 860px) { .defileParent { display: block; margin: 3em auto; overflow: hidden; position: relative; table-layout: fixed; width: 100%; } .defile { display: block; -webkit-animation: linear marqueelike 15s infinite; -moz-animation: linear marqueelike 15s infinite; -o-animation: linear marqueelike 15s infinite; -ms-animation: linear marqueelike 15s infinite; animation: linear marqueelike 15s infinite; margin-left: -100%; padding: 0 5px; text-align: left; height: 25px; } }
17.087948
59
0.591689
dd97379f1b0a63f375be07321d5d6661164eaeef
7,847
py
Python
v0/auto_predict.py
rexzhang2014/Easi-ML
5ff084b81b2c516d0ebea75f1dc0db1ebcb775db
[ "Apache-2.0" ]
1
2018-01-29T08:41:23.000Z
2018-01-29T08:41:23.000Z
v0/auto_predict.py
rexzhang2014/Easi-ML
5ff084b81b2c516d0ebea75f1dc0db1ebcb775db
[ "Apache-2.0" ]
null
null
null
v0/auto_predict.py
rexzhang2014/Easi-ML
5ff084b81b2c516d0ebea75f1dc0db1ebcb775db
[ "Apache-2.0" ]
2
2018-04-04T04:24:31.000Z
2019-02-11T09:01:51.000Z
#external data science packages import numpy as np import pandas as pd from sklearn import tree from sklearn.externals import joblib #external plotting packages import matplotlib.pyplot as plt #system packages import os import logging from sys import argv from datetime import datetime #User defined packages from preprocessing import hash_col from preprocessing import onehot from preprocessing import normalize from preprocessing import discretize from input_args import * #------------------------------------------------------------------------------ #predict : overall workflow of prediction phase, after the models are already trained. def predict(*args , **kwargs) : # Mandatory Args wkdir, dump_path, data_path, out_path = kwargs["path_list"] file_p, file_n, file_c = kwargs["filenames"] colList_float, colList_cnt, colList_days, colList_unicode = kwargs["column_lists"] model_name = kwargs["model_name"] keys = kwargs["keys"] # Optional Args # Setup paths and start logging os.chdir(wkdir) logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.info("START Predicting") try: ###Data Loading data_pred = pd.read_csv(data_path + "/" + file_p , low_memory=False, encoding=u'utf-8') .drop_duplicates(subset=keys,keep='first') data_pred.index = data_pred[keys] meanstd_n = pd.read_csv(data_path + "/" + file_n) meanstd_c = pd.read_csv(data_path + "/" + file_c) #For numeric features including float, cnt and days, we fill NaN and normalize clients_discretized = data_pred.copy() features_num = clients_discretized[[keys]+colList_float + colList_days + colList_cnt].drop_duplicates( keep='first') features_num = features_num[colList_float + colList_days + colList_cnt] \ .applymap(discretize.clean_cell) \ .applymap(lambda x : np.float64(x)) \ .apply(lambda x : (x - meanstd_n[x.name][0]) / (meanstd_n[x.name][1]+1e-5),axis=0) \ .fillna(0) logger.info("numeric features processed, shaped as : " + str(features_num.shape)) features_cat=clients_discretized[[keys]+colList_unicode].drop_duplicates(keep='first') features_cat=features_cat[colList_unicode].fillna("0") \ .apply(lambda x: x.astype('category',ordered=True) \ .factorize()[0],axis=0) \ .apply(lambda x : (np.float64(x) - meanstd_c[x.name][0]) /(meanstd_c[x.name][1]+1e-5),axis=0) \ .fillna(0) logger.info("categorical features processed, shaped as : " + str(features_cat.shape)) assert sum([features_num.isnull().sum().sum(), features_cat.isnull().sum().sum() == 0]) , "There is NaN in features" data_all = pd.concat([features_num.loc[features_num.index.sort_values(),], features_cat.loc[features_cat.index.sort_values(),]], axis=1) logger.info("merging features processed, shaped as : " + str(data_all.shape)) assert data_all.isnull().sum().sum() == 0, "There is NaN in data_all" logger.info("data_all built with shape:"+str(data_all.shape)) # Double confirm no NaN exists after merging assert data_all.isnull().sum().sum() == 0 , "There is NaN in data_all" #print(data_all.isnull().sum().sum()) # Get feature names features = data_all.columns.values.tolist() # Load pre-trained model, GBDT by default clf = joblib.load(dump_path+"/" + model_name + ".m") logger.info("model loaded from :" + dump_path+"/" + model_name + ".m") #rf = joblib.load("dumped_models/rf.m") data_prd = data_all[features] #data_prd.index = data_all.index # pred_prd = clf.predict_proba(data_prd) # Prediction output will be an list of pairs, the position 1 indicates the Class-1 # If the prediction distribution is abnormal, check this 0/1 positions pred_df = pd.DataFrame(pred_prd[:,1], index = data_prd.index, columns=['pred']) output = pred_df logger.info("Scoring done") # Reorganize as an output format # output predicted scores and some basic information. ' # Got information from original dataset without transforming # That's why we need a copy of data_pred. data_tmp2 = data_pred.drop_duplicates(keep='first') output_col = [] output = data_tmp2.loc[pred_df.index, output_col] output = pd.concat([pred_df, output], axis=1) #output.to_csv(out_path + "/pred_all.csv") output.to_excel(out_path + "/pred_all.xlsx") logger.info("Output with common features to: " + out_path + "/pred_all.xlsx") #logger.info("Prediction Succeeded.") logger.info("Start plotting histogram of scores") #Prediction Histogram thres = 0.5 hist, bins = np.histogram(np.array(output.loc[output["pred"] > thres, "pred"]), bins=20, density=False) width = 0.5 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) def fivenum(x) : return [ round(np.min(x),2) , round(np.percentile(x, 25),2) , round(np.median(x),2) , round(np.percentile(x, 75),2) , round(np.max(x),2)] plt.title("fivenum are {0[0]:.2}, {0[1]:.2}, {0[2]:.2}, {0[3]:.2}, {0[4]:.2}".format(fivenum(output.loc[output["pred"]>thres, "pred"]))) plt.savefig(out_path + "/score_histogram.png") plt.close() logger.info("Plotting done") logger.info("Prediction process finished") #cut off clients def clientsAtCutoff(output, cutoff, colname = "pred") : clients = [] for cf in cutoff : clients.append( output.loc[output[colname] > cf , [colname]].shape[0] ) return clients cutoffs = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.97, 0.99, 0.995, 0.999, 0.9999] clients_at = clientsAtCutoff(output, cutoffs) print("Clients at cutoffs are:" + str(clients_at)) pd.Series(clients_at, index=cutoffs).to_excel(out_path+"/score_distr.xlsx") except Exception as err: logger.error(str(err)) #print(err) finally: logger.removeHandler(handler) if __name__ == '__main__' : wkdir = u'' #set parameters dump_path = wkdir + "/model" data_path = wkdir + "/data" out_path = wkdir + "/output" colList_float = [] colList_cnt = [] colList_days = [] colList_unicode = [] model_name='' keys = '' os.chdir(wkdir) tic = datetime.now() predict(path_list=[wkdir, dump_path, data_path, out_path], filenames=["", "", ""], column_lists=[colList_float, colList_cnt, colList_days, colList_unicode], model_name=model_name, keys=keys) toc = datetime.now() print("predict time:" + str(toc-tic))
36.840376
144
0.577546
669cbcbfa4448afbdd876db00c7b407bb1e5fc8a
148
asm
Assembly
other.7z/SFC.7z/SFC/ソースデータ/ゼルダの伝説神々のトライフォース/ドイツ_PAL/Ger_asm1/zel_enmy4.asm
prismotizm/gigaleak
d082854866186a05fec4e2fdf1def0199e7f3098
[ "MIT" ]
null
null
null
other.7z/SFC.7z/SFC/ソースデータ/ゼルダの伝説神々のトライフォース/ドイツ_PAL/Ger_asm1/zel_enmy4.asm
prismotizm/gigaleak
d082854866186a05fec4e2fdf1def0199e7f3098
[ "MIT" ]
null
null
null
other.7z/SFC.7z/SFC/ソースデータ/ゼルダの伝説神々のトライフォース/ドイツ_PAL/Ger_asm1/zel_enmy4.asm
prismotizm/gigaleak
d082854866186a05fec4e2fdf1def0199e7f3098
[ "MIT" ]
null
null
null
Name: zel_enmy4.asm Type: file Size: 273311 Last-Modified: '2016-05-13T04:23:03Z' SHA-1: 6409065C13097BCCFAFA438EA44AE4EDE1E10688 Description: null
21.142857
47
0.817568
0551164c600ba9e4e95ce46b185387af204c7695
5,852
rb
Ruby
deploy/chef/chef-repo/cookbooks/databag_item/libraries/default.rb
akondasif/open-hackathon-bak_01
d60ad764edf689a95b6ffcc56815338b380801de
[ "MIT" ]
null
null
null
deploy/chef/chef-repo/cookbooks/databag_item/libraries/default.rb
akondasif/open-hackathon-bak_01
d60ad764edf689a95b6ffcc56815338b380801de
[ "MIT" ]
null
null
null
deploy/chef/chef-repo/cookbooks/databag_item/libraries/default.rb
akondasif/open-hackathon-bak_01
d60ad764edf689a95b6ffcc56815338b380801de
[ "MIT" ]
1
2019-04-03T19:47:22.000Z
2019-04-03T19:47:22.000Z
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd.  All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require 'json' module MSOpentechCN module Chef # A Mash that could fallback to databag class MashWithFallBack < ::Mash extend Forwardable def_delegators(:@data, *(::Mash.instance_methods-[:object_id, :__send__, :[]])) def initialize(data, fallback_data) @data = data @fallback_data = fallback_data end def self.wrap(data, fallback_data) if data == nil then data = fallback_data fallback_data = nil return data if data == nil end return data unless data.is_a?(::Mash) return MashWithFallBack.new(data, fallback_data) end def [](key) return get_data_with_fallback(key, @data, @fallback_data) end private def get_data_with_fallback(key, data, fallback_data) result = data[key] fallback_result = fallback_data[key] if fallback_data != nil return MashWithFallBack.wrap(result, fallback_result) end end class DatabagItem def initialize(secret, environment, bag_id) raise 'Missing bag_id parameter' unless bag_id raise 'Missing environment' unless environment ::Chef::Log.info("Load databag '#{bag_id}' for environment #{environment}") begin if secret == nil data_bag = ::Chef::DataBagItem.load(environment, bag_id) else data_bag = ::Chef::EncryptedDataBagItem.load(environment, bag_id, secret) end @attributes = ::Chef::Node::Attribute.new(data_bag.to_hash, {}, {}, {}) rescue Exception => e # Capture the exception so the chef script could continue executing. # # Fall-back to use values in environment if the failed to load databag # This is for backward compatibility that some environment may not have databag available # ::Chef::Log.warn "Failed to load databag for environment #{environment}. Because of '#{e}'. It may because the databag does not exist for the environment." end end def [](attrib) (@attributes == nil)? nil : @attributes[attrib] end end module ChefDSL include Chef::DataBagSecret @@initialized = false def initialize_chef_dsl return if @@initialized @@databag_items = Hash.new @@secret = load_databag_secret(node) @@initialized = true end def databag_item(bag_id=nil) initialize_chef_dsl bag_id = (bag_id or 'default') unless @@databag_items.has_key? bag_id @@databag_items[bag_id] = DatabagItem.new(@@secret, node.chef_environment, bag_id) end @@databag_items[bag_id] end end end end # Patch our DSL extension into Chef class Chef # Monkey patch the node[] method so we can access databag item from there # class Node include MSOpentechCN::Chef::ChefDSL old_accesser = instance_method(:[]) Chef::Log.info define_method(:[]) do |key| node_data = old_accesser.bind(self).(key) # Put all dependence cookbooks as blacklist to avoid indefinite recursive # if %w(databag_item citadel chef_solo).include?(key.to_s) return node_data end # directly return data if the databag_item cookbook is not loaded yet # This could happen during the chef environment loading phase # if old_accesser.bind(self).('databag_item') == nil return node_data end # Now we are working ... # Make sure data from databag has higher priority then environment # return MSOpentechCN::Chef::MashWithFallBack.wrap(databag_item[key], node_data) end end # Make sure we can access to databagItem with databag_item[] interface from recipe # class Recipe include MSOpentechCN::Chef::ChefDSL end # Make sure we can access to databagItem with databag_item[] interface from resource # class Resource include MSOpentechCN::Chef::ChefDSL end # Make sure we can access to databagItem with databag_item[] interface from provider # class Provider include MSOpentechCN::Chef::ChefDSL end # Make sure we can access to databagItem with databag_item[] interface from recipe # module Mixin module Template module ChefContext include MSOpentechCN::Chef::ChefDSL end ::Erubis::Context.send(:include, ChefContext) end end end
30.962963
166
0.651572
1b462e32fd79d3993add7e6d813abe14477ea64b
1,771
dart
Dart
generators_common/lib/src/fieldset.dart
kevmoo/dart_framework
e8a6fcedb7596f706c0abcdd72d016d864235298
[ "MIT" ]
null
null
null
generators_common/lib/src/fieldset.dart
kevmoo/dart_framework
e8a6fcedb7596f706c0abcdd72d016d864235298
[ "MIT" ]
null
null
null
generators_common/lib/src/fieldset.dart
kevmoo/dart_framework
e8a6fcedb7596f706c0abcdd72d016d864235298
[ "MIT" ]
null
null
null
part of 'class_element_extensions.dart'; class _FieldSet implements Comparable<_FieldSet> { final FieldElement field; _FieldSet._(this.field); factory _FieldSet(FieldElement? classField, FieldElement? superField) { // At least one of these will != null, perhaps both. final fields = [classField, superField].where((fe) => fe != null).toList(); // Prefer the class field over the inherited field when sorting. final sortField = fields.first!; return _FieldSet._(sortField); } @override int compareTo(_FieldSet other) => _sortByLocation(field, other.field); static int _sortByLocation(FieldElement a, FieldElement b) { final checkerA = TypeChecker.fromStatic( // ignore: unnecessary_cast (a.enclosingElement as ClassElement).thisType); if (!checkerA.isExactly(b.enclosingElement)) { // in this case, you want to prioritize the enclosingElement that is more // "super". if (checkerA.isAssignableFrom(b.enclosingElement)) { return -1; } final checkerB = TypeChecker.fromStatic( // ignore: todo // TODO: remove `ignore` when min pkg:analyzer >= 0.38.0 // ignore: unnecessary_cast (b.enclosingElement as ClassElement).thisType); if (checkerB.isAssignableFrom(a.enclosingElement)) { return 1; } } /// Returns the offset of given field/property in its source file – with a /// preference for the getter if it's defined. int _offsetFor(FieldElement e) { if (e.getter != null && e.getter!.nameOffset != e.nameOffset) { assert(e.nameOffset == -1); return e.getter!.nameOffset; } return e.nameOffset; } return _offsetFor(a).compareTo(_offsetFor(b)); } }
30.534483
79
0.659514
dfb99ddab2036e8e7a017d517ef0757550fdb232
568
cs
C#
Baldr/Baldr/Models/Account.cs
CodyALohse/Baldr
fde5b25990993a4b1b2516d09d7e59b9e6dbc0fa
[ "Apache-2.0" ]
1
2017-05-06T03:55:22.000Z
2017-05-06T03:55:22.000Z
Baldr/Baldr/Models/Account.cs
CodyALohse/Baldr
fde5b25990993a4b1b2516d09d7e59b9e6dbc0fa
[ "Apache-2.0" ]
null
null
null
Baldr/Baldr/Models/Account.cs
CodyALohse/Baldr
fde5b25990993a4b1b2516d09d7e59b9e6dbc0fa
[ "Apache-2.0" ]
null
null
null
using Core; using Baldr.Models.Enums; using System.Collections.Generic; namespace Baldr.Models { public class Account : BaseModel { public virtual ICollection<Transaction> Transactions { get; set; } public string Name { get; set; } public string AccountNumber { get; set; } public decimal StartingBalance { get; set; } public decimal CurrentBalance { get; set; } public string Comment { get; set; } public decimal InterestRate { get; set; } public AccountType Type { get; set; } } }
21.846154
74
0.637324
46558199977960dd7032222dd913047e702d387d
788
php
PHP
FtpUpload.php
aciden/receiv-data
604f7be746ab88c0918bbcf4564c88ed84cab5da
[ "MIT" ]
null
null
null
FtpUpload.php
aciden/receiv-data
604f7be746ab88c0918bbcf4564c88ed84cab5da
[ "MIT" ]
null
null
null
FtpUpload.php
aciden/receiv-data
604f7be746ab88c0918bbcf4564c88ed84cab5da
[ "MIT" ]
null
null
null
<?php namespace aciden\receivData; use yii2mod\ftp\FtpClient; use aciden\receivData\ErrorException; class FtpUpload { private $_ftpObj; public function __construct($host, $login, $pass, $pasv) { $this->_ftpObj = new FtpClient; $this->_ftpObj->connect($host); $this->_ftpObj->login($login, $pass); $this->_ftpObj->pasv($pasv); } public function upload($uploadFile, $filePath, $file) { try { $f = fopen($uploadFile . '/' . $file, 'w+'); $this->_ftpObj->fget($f, $filePath . '/' . $file, FTP_BINARY); fclose($f); } catch (ErrorException $e) { return false; } } }
22.514286
74
0.48731
a3650d59f569de4422d76c8f45f081c092841ffb
792
java
Java
src/main/java/com/alipay/api/response/AlipayCommerceAntestApplistQueryResponse.java
konser1/alipaytest
b9fd8ae46fb45a87a3c06f49f1db9114c1058590
[ "Apache-2.0" ]
null
null
null
src/main/java/com/alipay/api/response/AlipayCommerceAntestApplistQueryResponse.java
konser1/alipaytest
b9fd8ae46fb45a87a3c06f49f1db9114c1058590
[ "Apache-2.0" ]
null
null
null
src/main/java/com/alipay/api/response/AlipayCommerceAntestApplistQueryResponse.java
konser1/alipaytest
b9fd8ae46fb45a87a3c06f49f1db9114c1058590
[ "Apache-2.0" ]
2
2022-03-28T08:27:16.000Z
2022-03-28T08:27:26.000Z
package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.EcoAppInfo; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.commerce.antest.applist.query response. * * @author auto create * @since 1.0, 2020-04-21 15:50:09 */ public class AlipayCommerceAntestApplistQueryResponse extends AlipayResponse { private static final long serialVersionUID = 8896393769646822264L; /** * 小程序列表 */ @ApiListField("data") @ApiField("eco_app_info") private List<EcoAppInfo> data; public void setData(List<EcoAppInfo> data) { this.data = data; } public List<EcoAppInfo> getData( ) { return this.data; } }
22.628571
79
0.715909
eff6ab88d51ae9c5f77b49c56385ac239eb730b3
792
sql
SQL
src/SFA.Apprenticeships.Data.AvmsPlus/dbo/Stored Procedures/ProofConceptMethod1GIS.sql
BugsUK/FindApprenticeship
cd261c9199c3563031aab66582c0a10ecc055f8a
[ "MIT" ]
2
2019-02-14T17:06:44.000Z
2021-02-22T13:02:31.000Z
src/SFA.Apprenticeships.Data.AvmsPlus/dbo/Stored Procedures/ProofConceptMethod1GIS.sql
BugsUK/FindApprenticeship
cd261c9199c3563031aab66582c0a10ecc055f8a
[ "MIT" ]
1
2020-03-13T15:39:54.000Z
2020-03-13T15:39:54.000Z
src/SFA.Apprenticeships.Data.AvmsPlus/dbo/Stored Procedures/ProofConceptMethod1GIS.sql
BugsUK/FindApprenticeship
cd261c9199c3563031aab66582c0a10ecc055f8a
[ "MIT" ]
2
2020-03-13T15:27:47.000Z
2020-11-04T04:39:21.000Z
CREATE PROCEDURE [dbo].[ProofConceptMethod1GIS] @Latitude decimal(30,15), @Longitude decimal(30,15), @Eastin decimal(30,15), @Northin decimal(30,15), @Distance int --SET @Latitude = 52.477818110072185 --SET @Longitude = -1.9028135272556475 --SET @Eastin = 406600 --SET @Northin = 286700 AS BEGIN SET NOCOUNT ON BEGIN TRY Select dbo.fnx_CalcDistance (@Latitude,@Longitude, v.Latitude,v.Longitude) as Distance, v.Postcode,V.Latitude,V.Longitude ,VacancyId, VacancyReferenceNumber from Vacancy v wHERE dbo.fnx_CalcDistance (@Latitude,@Longitude, v.Latitude,v.Longitude) < @Distance Order By VacancyId END TRY BEGIN CATCH EXEC RethrowError; END CATCH SET NOCOUNT OFF END
23.294118
48
0.659091
02be76086ccef99a5f863463431c62b50b535cad
1,209
hh
C++
examples/ScatteringExample/include/SEDetectorConstruction.hh
QTNM/Electron-Tracking
b9dff0232af5a99fd795fd504dbddde71f4dd31c
[ "MIT" ]
2
2022-03-16T22:30:19.000Z
2022-03-16T22:30:26.000Z
examples/ScatteringExample/include/SEDetectorConstruction.hh
QTNM/Electron-Tracking
b9dff0232af5a99fd795fd504dbddde71f4dd31c
[ "MIT" ]
18
2021-03-02T15:14:11.000Z
2022-02-14T08:12:20.000Z
examples/ScatteringExample/include/SEDetectorConstruction.hh
QTNM/Electron-Tracking
b9dff0232af5a99fd795fd504dbddde71f4dd31c
[ "MIT" ]
null
null
null
#ifndef SEDetectorConstruction_h #define SEDetectorConstruction_h 1 #include "G4Cache.hh" #include "G4GenericMessenger.hh" #include "G4VUserDetectorConstruction.hh" #include "globals.hh" class G4VPhysicalVolume; class G4GlobalMagFieldMessenger; class SEGasSD; class SEWatchSD; class SEDetectorConstruction : public G4VUserDetectorConstruction { public: SEDetectorConstruction(); ~SEDetectorConstruction(); public: virtual G4VPhysicalVolume* Construct(); virtual void ConstructSDandField(); void SetGeometry(const G4String& name); void SetDensity(G4double d); private: void DefineCommands(); void DefineMaterials(); G4VPhysicalVolume* SetupBaseline(); G4VPhysicalVolume* SetupBunches(); G4VPhysicalVolume* SetupShort(); G4GenericMessenger* fDetectorMessenger = nullptr; G4String fGeometryName = "baseline"; G4double fdensity; G4Cache<G4GlobalMagFieldMessenger*> fFieldMessenger = nullptr; G4Cache<SEGasSD*> fSD1 = nullptr; G4Cache<SEWatchSD*> fSD2 = nullptr; }; #endif
27.477273
76
0.659222
2febfc93c5aee54f3532447f7d16f306d692bcc0
695
py
Python
solutions/solution523.py
Satily/leetcode_python_solution
3f05fff7758d650469862bc28df9e4aa7b1d3203
[ "MIT" ]
3
2018-11-22T10:31:09.000Z
2019-05-05T15:53:48.000Z
solutions/solution523.py
Satily/leetcode_python_solution
3f05fff7758d650469862bc28df9e4aa7b1d3203
[ "MIT" ]
null
null
null
solutions/solution523.py
Satily/leetcode_python_solution
3f05fff7758d650469862bc28df9e4aa7b1d3203
[ "MIT" ]
null
null
null
class Solution: def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ sums = [0] s = 0 for num in nums: s += num sums.append(s) for i in range(len(sums)): for j in range(i + 2, len(sums)): r = (sums[j] - sums[i]) if k != 0 and r % k == 0 or k == 0 and r == 0: return True return False if __name__ == "__main__": print(Solution().checkSubarraySum([23, 2, 4, 6, 7], 6)) print(Solution().checkSubarraySum([23, 4, 2, 6, 7], 6)) print(Solution().checkSubarraySum([0, 0], 0))
27.8
62
0.457554
c302441a4d44041b3306aa4e5cadf9ae817ba0ce
1,920
swift
Swift
Sources/Apollo/ServiceCoreDataContext.swift
nallick/Apollo
57c6e508932e6d25bc01caf22dcf7f7ff565219e
[ "MIT" ]
null
null
null
Sources/Apollo/ServiceCoreDataContext.swift
nallick/Apollo
57c6e508932e6d25bc01caf22dcf7f7ff565219e
[ "MIT" ]
null
null
null
Sources/Apollo/ServiceCoreDataContext.swift
nallick/Apollo
57c6e508932e6d25bc01caf22dcf7f7ff565219e
[ "MIT" ]
null
null
null
// // ServiceCoreDataContext.swift // // Copyright © 2022 Purgatory Design. Licensed under the MIT License. // #if !os(macOS) import CoreData import Foundation public struct ServiceCoreDataContext<Service: ServiceModule> { public let persistentContainer: NSPersistentContainer public let managedObjectContext: NSManagedObjectContext public init(bundle: Bundle = Bundle.main, containerName: String = Service.name, modelName: String? = nil, persistentContainer: NSPersistentContainer? = nil) { self.persistentContainer = persistentContainer ?? PersistentContainer(bundle: bundle, containerName: containerName, modelName: modelName ?? containerName) self.managedObjectContext = self.persistentContainer.viewContext } public func loadPersistentStores(completion: @escaping (NSPersistentStoreDescription, Error?) -> Void) { persistentContainer.loadPersistentStores(completionHandler: completion) } public func saveDatabaseContext() throws { let context = persistentContainer.viewContext if context.hasChanges { try context.save() } } } extension ServiceCoreDataContext { public class PersistentContainer: NSPersistentContainer { public convenience init(bundle: Bundle, containerName: String, modelName: String) { guard let modelURL = bundle.url(forResource: modelName, withExtension: "momd"), let model = NSManagedObjectModel(contentsOf: modelURL) else { self.init(name: containerName) return } self.init(name: containerName, managedObjectModel: model) } public override class func defaultDirectoryURL() -> URL { let applicationSupportDirectory = try? Service.applicationSupportDirectory() return applicationSupportDirectory ?? super.defaultDirectoryURL() } } } #endif
34.909091
162
0.707292
7970b590e9a1b4a06ce37f7a3c6d3e403e228a62
2,246
php
PHP
web/app/plugins/wordpress-seo/admin/views/tabs/network/integrations.php
frogspark/lookingglass
90e56599adf4371cb8a906e71e83665ce65ac9c9
[ "MIT" ]
1
2022-03-21T13:33:12.000Z
2022-03-21T13:33:12.000Z
wp-content/plugins/wordpress-seo/admin/views/tabs/network/integrations.php
fakhar-ali/mysocceracademy.com
b9e0c2f9cc45546274747d6200640315d467099a
[ "Unlicense" ]
1
2021-10-01T07:18:15.000Z
2021-10-01T07:18:15.000Z
wp-content/plugins/wordpress-seo/admin/views/tabs/network/integrations.php
fakhar-ali/mysocceracademy.com
b9e0c2f9cc45546274747d6200640315d467099a
[ "Unlicense" ]
null
null
null
<?php /** * WPSEO plugin file. * * @package WPSEO\Admin\Views * * @uses Yoast_Form $yform Form object. */ if ( ! defined( 'WPSEO_VERSION' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); } $integration_toggles = Yoast_Integration_Toggles::instance()->get_all(); ?> <h2><?php esc_html_e( 'Integrations', 'wordpress-seo' ); ?></h2> <div class="yoast-measure"> <?php echo sprintf( /* translators: %1$s expands to Yoast SEO */ esc_html__( 'This tab allows you to selectively disable %1$s integrations with third-party products for all sites in the network. By default all integrations are enabled, which allows site admins to choose for themselves if they want to toggle an integration on or off for their site. When you disable an integration here, site admins will not be able to use that integration at all.', 'wordpress-seo' ), 'Yoast SEO' ); foreach ( $integration_toggles as $integration ) { $help_text = esc_html( $integration->label ); if ( ! empty( $integration->extra ) ) { $help_text .= ' ' . $integration->extra; } if ( ! empty( $integration->read_more_label ) ) { $help_text .= ' '; $help_text .= sprintf( '<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>', esc_url( WPSEO_Shortlinker::get( $integration->read_more_url ) ), esc_html( $integration->read_more_label ) ); } $feature_help = new WPSEO_Admin_Help_Panel( WPSEO_Option::ALLOW_KEY_PREFIX . $integration->setting, /* translators: %s expands to an integration's name */ sprintf( esc_html__( 'Help on: %s', 'wordpress-seo' ), esc_html( $integration->name ) ), $help_text ); $yform->toggle_switch( WPSEO_Option::ALLOW_KEY_PREFIX . $integration->setting, [ 'on' => __( 'Allow Control', 'wordpress-seo' ), 'off' => __( 'Disable', 'wordpress-seo' ), ], $integration->name, $feature_help->get_button_html() . $feature_help->get_panel_html() ); } ?> </div> <?php /* * Required to prevent our settings framework from saving the default because the field isn't * explicitly set when saving the Dashboard page. */ $yform->hidden( 'show_onboarding_notice', 'wpseo_show_onboarding_notice' );
32.550725
407
0.667409
33ece952ca7cfe030ac2ab9db6da6fc480bbf8c9
780
h
C
nanomq/include/web_server.h
Swilder-M/nanomq
7cf17a2b5768952910e2688fa4adb7d11678540d
[ "MIT" ]
347
2020-04-27T04:17:15.000Z
2022-03-30T17:17:28.000Z
nanomq/include/web_server.h
Swilder-M/nanomq
7cf17a2b5768952910e2688fa4adb7d11678540d
[ "MIT" ]
197
2020-09-08T10:25:24.000Z
2022-03-31T16:54:42.000Z
nanomq/include/web_server.h
Swilder-M/nanomq
7cf17a2b5768952910e2688fa4adb7d11678540d
[ "MIT" ]
52
2020-09-03T01:30:34.000Z
2022-03-28T07:43:45.000Z
// // Copyright 2020 NanoMQ Team, Inc. <[email protected]> // // This software is supplied under the terms of the MIT License, a // copy of which should be located in the distribution where this // file was obtained (LICENSE.txt). A copy of the license may also be // found online at https://opensource.org/licenses/MIT. // #ifndef WEB_SERVER_H #define WEB_SERVER_H #include <conf.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define HTTP_DEFAULT_USER "admin" #define HTTP_DEFAULT_PASSWORD "public" #define HTTP_DEFAULT_PORT 8081 extern int start_rest_server(conf *conf); extern void stop_rest_server(void); extern void set_http_server_conf(conf_http_server *conf); extern conf_http_server *get_http_server_conf(void); #endif
26
70
0.755128
ae585b3952dc053710cb4dee4276ca2b90df9f2f
7,427
cs
C#
Player.cs
wajeehanwar/Startrek-Catan-Console-Build
8b4b7486d7e876e099481c17515adcd7cb8dc506
[ "MIT" ]
null
null
null
Player.cs
wajeehanwar/Startrek-Catan-Console-Build
8b4b7486d7e876e099481c17515adcd7cb8dc506
[ "MIT" ]
null
null
null
Player.cs
wajeehanwar/Startrek-Catan-Console-Build
8b4b7486d7e876e099481c17515adcd7cb8dc506
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; namespace CatanConsoleBuild { public class Player { readonly int order; readonly string name; private int points; private bool longestSupplyRoute; private bool largestStarfleet; private bool active; private PlayerResources resources; private List<Outpost> outposts; private List<Starship> starShips; //public PlayerDevelopmentCards developmentCards; public Player(int order, string name) { this.order = order; this.name = name; points = 0; longestSupplyRoute = false; largestStarfleet = false; active = false; resources = new PlayerResources(); } public int GetOrder() { return order; } public string GetName() { return name; } public PlayerResources GetResources() { return resources; } public void SetPoints(int points) { this.points = points; } public int GetPoints() { return points; } public void SetLongestSupplyRoute() { longestSupplyRoute = true; points += 2; } public bool GetLongestSupplyRoute() { return longestSupplyRoute; } public void SetLargestStarfleet(bool toggle) { largestStarfleet = toggle; } public bool GetLargestStarfleet() { return largestStarfleet; } public void SetActive(bool toggle) { active = toggle; } public bool GetActive() { return active; } public bool SetFirstOutpost(Player player, BoardVertice vertice) { if (vertice.HasOutpost()) { return false; } else { //create outpost Outpost newOutpost = new Outpost(player, vertice); // add outpost to player outposts.Add(newOutpost); // add outpost to vertice vertice.SetOutpost(newOutpost); //add points points++; return true; } } public bool SetOutpost(Player player, BoardVertice vertice) { // Disqualify if insufficiant resources. if (resources.GetDilithium() < 1 || resources.GetTritanium() < 1 || resources.GetFood() < 1 || resources.GetOxygen() < 1) { return false; } // Disqualify if outpost already present. if (vertice.HasOutpost()) { return false; } // Disqualify if outpost at adjacent vertices and no starship present. bool hasStarship = false; foreach (BoardVerticePath path in vertice.GetPaths()) { if (path.HasStarship() && path.GetStarship().GetOwner().GetOrder() == order) { hasStarship = true; } if (path.GetToVertice().HasOutpost()) { return false; } } if (!hasStarship) { return false; } // Evaluate second degree starship foreach (BoardVerticePath path in vertice.GetPaths()) { if (path.HasStarship()) { foreach (BoardVerticePath nextDegreePath in path.GetToVertice().GetPaths()) { if (nextDegreePath.HasStarship() && nextDegreePath.GetStarship().GetOwner().GetOrder() == order && nextDegreePath.GetToVertice().GetLocation() != vertice.GetLocation()) { //create outpost Outpost newOutpost = new Outpost(player, vertice); // Add outpost to player outposts.Add(newOutpost); // Add outpost to vertice vertice.SetOutpost(newOutpost); // Remove resources from player resources.RemoveDilithium(1); resources.RemoveTritanium(1); resources.RemoveFood(1); resources.RemoveOxygen(1); // Add points points++; return true; } } } } // No second degree starship present. return false; } public bool SetStarship(Player player, BoardVerticePath path) { // Disqualify if insufficiant resources. if (resources.GetDilithium() < 1 || resources.GetTritanium() < 1) { return false; } // Disqualify if starship already present if (path.HasStarship()) { return false; } // Qualify if player owns an outpost at either end of the path. if ((path.GetFromVertice().HasOutpost() && path.GetFromVertice().GetOutpost().GetOwner().GetOrder() == order) || (path.GetToVertice().HasOutpost() && path.GetToVertice().GetOutpost().GetOwner().GetOrder() == order)) { // Add new starship Starship newStarship = new Starship(player, path); path.SetStarship(newStarship); // Remove resources from player resources.RemoveDilithium(1); resources.RemoveTritanium(1); return true; } // Qualify if player owns an existing starship on leading paths bool ownsExistingStarship = false; foreach (BoardVerticePath nextDegreePath in path.GetFromVertice().GetPaths()) { if (nextDegreePath.HasStarship() && nextDegreePath.GetStarship().GetOwner().GetOrder() == order) { ownsExistingStarship = true; } } foreach (BoardVerticePath nextDegreePath in path.GetToVertice().GetPaths()) { if (nextDegreePath.HasStarship() && nextDegreePath.GetStarship().GetOwner().GetOrder() == order) { ownsExistingStarship = true; } } if (ownsExistingStarship) { // Add new starship Starship newStarship = new Starship(player, path); path.SetStarship(newStarship); // Remove resources from player resources.RemoveDilithium(1); resources.RemoveTritanium(1); return true; } return false; } //private bool GameOver() //{ // if (points >= Constants.WINNINGPOINTS) // { // return true; // } // return false; //} } }
31.875536
192
0.477043
bedf9698b47dc3accf9db483defccfce1553b3b3
3,259
ts
TypeScript
babyonboard/src/app/app.component.spec.ts
BabyOnBoard/BabyOnBoard-Web
0ed9ac913c552955fecefce7e03216f041785502
[ "MIT" ]
null
null
null
babyonboard/src/app/app.component.spec.ts
BabyOnBoard/BabyOnBoard-Web
0ed9ac913c552955fecefce7e03216f041785502
[ "MIT" ]
null
null
null
babyonboard/src/app/app.component.spec.ts
BabyOnBoard/BabyOnBoard-Web
0ed9ac913c552955fecefce7e03216f041785502
[ "MIT" ]
null
null
null
import { TestBed, async, fakeAsync, ComponentFixture } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { Observable } from "rxjs"; import { APIService } from './api.service'; class MockAPIService { public getBeats():Observable<any>{ return Observable.throw('Erro de teste'); } public getTemperature():Observable<any>{ return Observable.throw('Erro de teste'); } public getBreath():Observable<any>{ return Observable.throw('Erro de teste'); } } describe('AppComponent', () => { let component: AppComponent; let mockAPIService: MockAPIService; let fixture: ComponentFixture<AppComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).overrideComponent(AppComponent, { set: { providers: [ { provide: APIService, useClass: MockAPIService } ] } }).compileComponents().then(() => { fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; mockAPIService = fixture.debugElement.injector.get(APIService); }); })); it('should create', () => { expect(component).toBeTruthy(); }); it('getBeats should get the result', fakeAsync(() => { const spy = spyOn(mockAPIService, 'getBeats').and.returnValue(Observable.of( { "beats": 110 } )); fixture.detectChanges(); component.getBeats(); expect(component.results_h).toEqual(110); expect(mockAPIService.getBeats).toHaveBeenCalled(); })); it('getBeats should get the error', fakeAsync(() => { const spy = spyOn(mockAPIService, 'getBeats').and.callThrough(); fixture.detectChanges(); component.getBeats(); expect(component.results_h).toEqual('API não encontrada'); expect(mockAPIService.getBeats).toHaveBeenCalled(); })); it('getTemperature should get the result', fakeAsync(() => { const spy = spyOn(mockAPIService, 'getTemperature').and.returnValue(Observable.of( { "temperature": 37 } )); fixture.detectChanges(); component.getTemperature(); expect(component.results_t).toEqual(37); expect(mockAPIService.getTemperature).toHaveBeenCalled(); })); it('getTemperature should get the error', fakeAsync(() => { const spy = spyOn(mockAPIService, 'getTemperature').and.callThrough(); fixture.detectChanges(); component.getTemperature(); expect(component.results_t).toEqual('API não encontrada'); expect(mockAPIService.getTemperature).toHaveBeenCalled(); })); it('getBreath should get the result', fakeAsync(() => { const spy = spyOn(mockAPIService, 'getBreath').and.returnValue(Observable.of( { "is_breathing": true } )); fixture.detectChanges(); component.getBreath(); expect(component.results_b).toEqual(true); expect(mockAPIService.getBreath).toHaveBeenCalled(); })); it('getBreath should get the error', fakeAsync(() => { const spy = spyOn(mockAPIService, 'getBreath').and.callThrough(); fixture.detectChanges(); component.getBeats(); expect(component.results_b).toEqual('API não encontrada'); expect(mockAPIService.getBreath).toHaveBeenCalled(); })); });
30.457944
86
0.667383
baf35f920a97be0bcdbde965be59dc86a6638fc6
115
dart
Dart
contacts/lib/data/models/avatar.dart
rv-kansagara/contacts
dc272c74c2eb5ec93d38338a6144a65a145d0f8f
[ "Apache-2.0" ]
null
null
null
contacts/lib/data/models/avatar.dart
rv-kansagara/contacts
dc272c74c2eb5ec93d38338a6144a65a145d0f8f
[ "Apache-2.0" ]
null
null
null
contacts/lib/data/models/avatar.dart
rv-kansagara/contacts
dc272c74c2eb5ec93d38338a6144a65a145d0f8f
[ "Apache-2.0" ]
null
null
null
class Avatar { final int id; final String avatar; const Avatar({required this.id, required this.avatar}); }
16.428571
57
0.704348
217c3a3f4d4b872c3c6c3a8c926d81214ef07f8f
3,027
js
JavaScript
components/guest/Form/SignUpForm.js
jackomo007/Uphoto
a3229850d29e6a2576590d296e9173e3443bed73
[ "MIT" ]
1
2020-07-07T17:19:49.000Z
2020-07-07T17:19:49.000Z
components/guest/Form/SignUpForm.js
jackomo007/Uphoto
a3229850d29e6a2576590d296e9173e3443bed73
[ "MIT" ]
null
null
null
components/guest/Form/SignUpForm.js
jackomo007/Uphoto
a3229850d29e6a2576590d296e9173e3443bed73
[ "MIT" ]
null
null
null
import React from 'react'; import {View, Text, StyleSheet, TextInput, Button} from 'react-native'; import { Field, reduxForm} from 'redux-form'; const fieldName = (props) => { return ( <View style={styles.textInput}> <TextInput placeholder={props.ph} onChangeText={props.input.onChange} value={props.input.value} keyboardType={props.input.name === 'email'? 'email-address': 'default'} autoCapitalize='none' secureTextEntry={!!(props.input.name === 'password' || props.input.name === 'confirm_password')} onBlur={props.input.onBlur} /> <View style={styles.linea} /> {props.meta.touched && props.meta.error && <Text style={styles.errors}>{props.meta.error}</Text>} </View> ); }; const fieldImage = props => <View> <View> {props.meta.touched && props.meta.error && <Text style={styles.errors}>{props.meta.error}</Text>} </View> </View>; const validate = (values,props) => { const errors = {}; if(!props.image){ errors.image = 'image required'; } if(!values.name){ errors.name = 'required'; }else if (values.name.length < 5){ errors.name = 'must be at least 5 characters'; }else if (values.name.length > 10){ errors.name = 'must be less than 10 characters'; } if(!values.email){ errors.email = 'required'; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)){ errors.email = 'wrong format email' } if(!values.password){ errors.password = 'required'; } else if(values.password.length < 5){ errors.password = 'must be at least 5 characters'; } else if(values.password.length > 15){ errors.password = 'must be less than 15 characters'; } if(!values.confirm_password){ errors.confirm_password = 'required'; } else if(values.password !== values.confirm_password){ errors.confirm_password = 'failed password confirmation'; } return errors; } const SignUpForm = (props) => { return( <View style={styles.container}> <Field name="image" component={fieldImage} /> <Field name="name" component={fieldName} ph='Name' /> <Field name="email" component={fieldName} ph='Email' /> <Field name="password" component={fieldName} ph='******' /> <Field name="confirm_password" component={fieldName} ph='******' /> <Button title="Register" onPress={props.handleSubmit( props.register, )} /> </View> ); }; const styles = StyleSheet.create({ container:{ flex: 2, }, textInput: { marginBottom: 16, }, linea: { backgroundColor: '#2196f3', height: 2, }, errors: { color: '#bf405f', } }); export default reduxForm({ form: 'SignUpForm', validate})(SignUpForm);
30.27
109
0.560291
07e2949194defb56ae3a9b59b8f345080021e424
502
css
CSS
demo/app/app.css
xuhcc/nativescript-floatingactionbutton
929fb0a62ce8d99567e877c3c4d476aea69934c2
[ "MIT" ]
null
null
null
demo/app/app.css
xuhcc/nativescript-floatingactionbutton
929fb0a62ce8d99567e877c3c4d476aea69934c2
[ "MIT" ]
null
null
null
demo/app/app.css
xuhcc/nativescript-floatingactionbutton
929fb0a62ce8d99567e877c3c4d476aea69934c2
[ "MIT" ]
null
null
null
.title { font-size: 28; horizontal-align: center; margin: 20; } button { font-size: 24; horizontal-align: center; } .message { font-size: 20; color: #284848; horizontal-align: center; } .fab-button-bottom { height: 60; width: 60; margin: 15; horizontal-align: right; vertical-align: bottom; color: #fff; background-color: #ff4081; } .commands { padding: 10 5; background-color: #f0f0f0; } .commands button { font-size: 14; }
13.944444
29
0.595618
388dd2b8cf3badf35ba59a5e05cebc9040376f58
441
php
PHP
resources/views/mails/mail-reset-password-student.blade.php
quangbaond/japanes-study
101cf08e9a0bb2b1c0808282f7814d98ed42b28c
[ "MIT" ]
null
null
null
resources/views/mails/mail-reset-password-student.blade.php
quangbaond/japanes-study
101cf08e9a0bb2b1c0808282f7814d98ed42b28c
[ "MIT" ]
null
null
null
resources/views/mails/mail-reset-password-student.blade.php
quangbaond/japanes-study
101cf08e9a0bb2b1c0808282f7814d98ed42b28c
[ "MIT" ]
null
null
null
<div> <p>{{$data['nickname']}}<br></p> <p>The administrator has reset the password for your account.<br></p> <p>Login information:<br> Email: {{$data['email']}}<br> Password: {{$data['password']}}<br> Link login: <a href="{{ $data['url'] }}">{{ $data['url'] }}</a><br> </p> <p>With love,<br> The Student Japanese Team.<br> 31 Tran Phu Street, Da Nang, Viet Nam<br> </p> </div>
31.5
75
0.521542
60242a53d321aadd82aa566454eb1ec8c249881e
4,827
swift
Swift
ICKit/Classes/TextureEx/ICNestedScrollContext.swift
IvanChan/ICKit
87b109f0b1ce980205b320455f58ee0c1b1f54ab
[ "MIT" ]
null
null
null
ICKit/Classes/TextureEx/ICNestedScrollContext.swift
IvanChan/ICKit
87b109f0b1ce980205b320455f58ee0c1b1f54ab
[ "MIT" ]
null
null
null
ICKit/Classes/TextureEx/ICNestedScrollContext.swift
IvanChan/ICKit
87b109f0b1ce980205b320455f58ee0c1b1f54ab
[ "MIT" ]
null
null
null
// // ICNestedScrollContext.swift // ICKit // // Created by _ivanc on 2019/2/16. // Copyright © 2019 ivanC. All rights reserved. // import UIKit import AsyncDisplayKit public class ICNestedMainScrollView: UIScrollView, UIGestureRecognizerDelegate { //底层tableView实现这个UIGestureRecognizerDelegate的方法,从而可以接收并响应上层tabelView的滑动手势,otherGestureRecognizer就是它上层View也持有的Gesture,这里在它上层的有scrollView和顶层tableView public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // 保证其它手势的View存在 guard let otherView = otherGestureRecognizer.view else { return false } //如果其它手势的View是scrollView的手势,肯定是不能同时响应的 if otherView.isMember(of: UIScrollView.self) { return false } // 其它手势是collectionView 或者tableView的pan手势 ,那么就让它们同时响应 let isPan = gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) if isPan && otherView.isKind(of: UIScrollView.self) { return true } return false } } public protocol ICNestedScrollContextDataSource:NSObjectProtocol { func mainScrollView() -> ICNestedMainScrollView? func embeddedScrollView() -> UIScrollView? func triggerOffset() -> CGPoint } public class ICNestedScrollContext: NSObject, UIScrollViewDelegate { weak var dataSource:ICNestedScrollContextDataSource? private var mainScrollView:ICNestedMainScrollView? { return dataSource?.mainScrollView() } private var embeddedScrollView:UIScrollView? { return dataSource?.embeddedScrollView() } private var triggerOffset:CGPoint { return dataSource?.triggerOffset() ?? .zero } private(set) var isMainScrollViewDragging:Bool = false private(set) var isEmbeddedScrollViewDragging:Bool = false public var deceleratingFactor:CGFloat = 120 public init(dataSource:ICNestedScrollContextDataSource) { self.dataSource = dataSource super.init() } private var fixTriggerOffsetY:CGFloat = 0 @objc public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if scrollView == mainScrollView { mainContentOffset = scrollView.contentOffset isMainScrollViewDragging = true fixTriggerOffsetY = triggerOffset.y // var mainScrollViewContentInset = scrollView.contentInset // if #available(iOS 11.0, *) { // mainScrollViewContentInset = scrollView.adjustedContentInset // } // // let mainScrollViewMaxContentOffsetY = scrollView.contentSize.height - scrollView.bounds.height + mainScrollViewContentInset.bottom // if fixTriggerOffsetY > mainScrollViewMaxContentOffsetY { // fixTriggerOffsetY = mainScrollViewMaxContentOffsetY // } } else if scrollView == embeddedScrollView { embeddedContentOffset = scrollView.contentOffset isEmbeddedScrollViewDragging = true } } private var mainContentOffset:CGPoint = .zero private var embeddedContentOffset:CGPoint = .zero private var isMainScrolling = false private var isEmbeddedScrolling = false @objc public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == mainScrollView { let isScrollingDown = mainContentOffset.y > scrollView.contentOffset.y if scrollView.contentOffset.y > fixTriggerOffsetY || (isScrollingDown && embeddedContentOffset.y > 0 && isEmbeddedScrolling) { scrollView.contentOffset.y = fixTriggerOffsetY isMainScrolling = false } else { isMainScrolling = true } mainContentOffset = scrollView.contentOffset } else if scrollView == embeddedScrollView { if mainContentOffset.y < fixTriggerOffsetY && isMainScrolling { scrollView.contentOffset = embeddedContentOffset isEmbeddedScrolling = false } else { isEmbeddedScrolling = true } if scrollView.contentOffset.y < 0 { scrollView.contentOffset.y = 0 } embeddedContentOffset = scrollView.contentOffset } } @objc public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView == mainScrollView { isMainScrollViewDragging = false } else if scrollView == embeddedScrollView { isEmbeddedScrollViewDragging = false } } }
36.293233
164
0.665009
c9b08186aa72bdb2f82ac75c977459ef683bf7b1
6,362
ts
TypeScript
src/kusama/lib/claims.ts
consenlabs/polkadot-staking-dapp
09f1fbf6f73c9179a87359a1a7573f02c0989322
[ "Apache-2.0" ]
4
2020-08-31T07:49:42.000Z
2021-12-07T07:19:40.000Z
src/kusama/lib/claims.ts
consenlabs/polkadot-staking-dapp
09f1fbf6f73c9179a87359a1a7573f02c0989322
[ "Apache-2.0" ]
null
null
null
src/kusama/lib/claims.ts
consenlabs/polkadot-staking-dapp
09f1fbf6f73c9179a87359a1a7573f02c0989322
[ "Apache-2.0" ]
3
2020-08-26T06:46:39.000Z
2020-09-24T17:36:51.000Z
import { ApiPromise } from '@polkadot/api'; import { WsProvider } from '@polkadot/rpc-provider'; import { web3Accounts, web3Enable } from '@polkadot/extension-dapp' import { pubsub } from './event'; import { web3FromSource } from '@polkadot/extension-dapp'; import toast from './toast'; import { BN_ZERO } from './format' import { u8aToHex, u8aToString } from '@polkadot/util' import { decodeAddress } from '@polkadot/util-crypto' import { StatementKind } from '@polkadot/types/interfaces' import { isPolkadot } from './is' export let ready = false let _api: ApiPromise export const initClient = () => { if (_api) return _api const endpoint = isPolkadot() ? 'wss://polkadot-mainnet.token.im/ws' : 'wss://kusama-mainnet.token.im/ws' const provider = new WsProvider(endpoint) const api = new ApiPromise({ provider }); api.rpc.chain.subscribeNewHeads((header) => { console.log(`Chain is at #${header.number}`); if (!ready) { ready = true pubsub.emit('api-ready') } }).catch((error) => { toast.error(error.message) }); _api = api return api } export const getAPI = () => { return _api } function sendCallback(result) { const { status, events } = result if (status._index === 1) { pubsub.emit('sendingTx', { txHash: status.hash.toString() }) } if (status.isInBlock || status.isFinalized) { events // find/filter for failed events .filter(({ section, method }) => section === 'system' && method === 'ExtrinsicFailed' ) // we know that data for system.ExtrinsicFailed is // (DispatchError, DispatchInfo) .forEach(({ data: [error, info] }) => { if (error.isModule) { // for module errors, we have the section indexed, lookup const decoded = _api.registry.findMetaError(error.asModule); const { documentation, name, section } = decoded; console.log(`${section}.${name}: ${documentation.join(' ')}`); } else { // Other, CannotLookup, BadOrigin, no extra info console.log(error.toString()); const hash = status.hash.toString() pubsub.emit('sendTxWrong', { hash, error: error }) } }); } if (result.isCompleted) { const hash = status.hash.toString() pubsub.emit('sendTxSuccess', { hash }) } } const signAndSend = async (tx, account) => { const injected = await web3FromSource(account.meta.source) return tx.signAndSend(account.address, { signer: injected.signer, tip: BN_ZERO, }, sendCallback) } const send = async (tx, account) => { // const injected = await web3FromSource(account.meta.source); return tx.send(sendCallback) } export const getAccount = async () => { try { await web3Enable('imtoken-polkadot-staking') const accounts = await web3Accounts() if (accounts.length) { return accounts } // throw new Error('account_not_found') return [] } catch (error) { console.log(error) throw error } } /** * =================================== Claims start =================================== */ export const getPreclaimAddress = async (accountId): Promise<string | null> => { if (_api) { if (!_api.query.claims || !_api.query.claims.preclaims) { return null } return await _api.query.claims .preclaims(accountId) .then(preclaim => { const address = preclaim && preclaim.toString() return address || null }).catch(() => { return null }) } return null } export const getClaimsBalance = async (ethereumAddress): Promise<string | null> => { if (_api) { return await _api.query.claims .claims<any>(ethereumAddress) .then((claim): string => { return claim && claim.toString() }) .catch(e => { return null }) } return null } interface ConstructTx { params?: any[] tx?: string } export interface Statement { sentence: string; url: string; } // Depending on isOldClaimProcess, construct the correct tx. export function constructTx(systemChain: string, accountId: string, ethereumSignature: string | null, kind: StatementKind | undefined, isOldClaimProcess: boolean): ConstructTx { if (!ethereumSignature) { return {}; } return isOldClaimProcess || !kind ? { params: [accountId, ethereumSignature], tx: 'claims.claim' } : { params: [accountId, ethereumSignature, getStatement(systemChain, kind)?.sentence], tx: 'claims.claimAttest' }; } export function claims(constructTx: ConstructTx, account: any) { const { tx = '', params } = constructTx console.log(tx, params) if (_api) { const [section, method] = tx.split('.') const claimsTx = _api.tx[section][method](...params) return send(claimsTx, account) } } export function attestOnly(statementSentence, account) { if (_api) { const attestTx = _api.tx.claims.attest(...[statementSentence]) return signAndSend(attestTx, account) } } export function getClaimsToSigndMessage(accountId: string, statementSentence: string) { if (_api) { const prefix = u8aToString(_api.consts.claims.prefix.toU8a(true)); return accountId ? `${prefix}${u8aToHex(decodeAddress(accountId), -1, false)}${statementSentence}` : '' } return '' } export function getStatement(network: string = 'Polkadot CC1', kind?: StatementKind | null): Statement | undefined { switch (network) { case 'Polkadot CC1': { if (!kind) { return undefined; } const url = kind.isRegular ? 'https://statement.polkadot.network/regular.html' : 'https://statement.polkadot.network/saft.html'; const hash = kind.isRegular ? 'Qmc1XYqT6S39WNp2UeiRUrZichUWUPpGEThDE6dAb3f6Ny' : 'QmXEkMahfhHJPzT3RjkXiZVFi77ZeVeuxtAjhojGRNYckz'; return { sentence: `I hereby agree to the terms of the statement whose SHA-256 multihash is ${hash}. (This may be found at the URL: ${url})`, url }; } default: return undefined; } } export function getIsOldClaimProcess() { if (!ready) return false if (_api) { return !_api.tx.claims.claimAttest } // TODO: fix api not ready return false } /** * =================================== Claims end =================================== */
26.843882
177
0.621031
a43eb7fd73cf9c3eea74d97500c7e7fe57e847d4
268
php
PHP
app/metier/Presentation.php
Glmart69/ProjetGSB
1f24b8c1a729681cc387b815e5865c871f9c29c9
[ "MIT" ]
null
null
null
app/metier/Presentation.php
Glmart69/ProjetGSB
1f24b8c1a729681cc387b815e5865c871f9c29c9
[ "MIT" ]
1
2021-02-02T18:24:42.000Z
2021-02-02T18:24:42.000Z
app/metier/Presentation.php
Glmart69/ProjetGSB
1f24b8c1a729681cc387b815e5865c871f9c29c9
[ "MIT" ]
null
null
null
<?php namespace App\metier; use Illuminate\Database\Eloquent\Model; class Presentation extends Model { protected $table = 'PRESENTATION'; public $timestamps = false; protected $fillable = [ 'ID_PRESENTATION', 'LIB_PRESENTATION' ]; }
16.75
39
0.66791
db72292cf784b7a254ee436e226f29ba2b988bd0
299
php
PHP
app/ExpenseCategory.php
iamginofernando/Gino-Fernando
d64b65468d87bf2cbf38c085efb6eb482f8defd4
[ "MIT" ]
null
null
null
app/ExpenseCategory.php
iamginofernando/Gino-Fernando
d64b65468d87bf2cbf38c085efb6eb482f8defd4
[ "MIT" ]
null
null
null
app/ExpenseCategory.php
iamginofernando/Gino-Fernando
d64b65468d87bf2cbf38c085efb6eb482f8defd4
[ "MIT" ]
null
null
null
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ExpenseCategory extends Model { protected $table = 'expense_categ'; protected $primaryKey = 'expense_categ_id'; public function getExpense() { return $this->hasMany('App\Expense','expense_id'); } }
18.6875
58
0.682274
bdaefc4d4c99de2aa4c4c315e002db0556a521e5
305
sql
SQL
dashboard/src/main/webapp/WEB-INF/schemaUpdates/2015-03-10-submit-block-next-document.sql
stori-es/stories
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
2
2016-06-02T22:29:19.000Z
2019-06-12T18:51:01.000Z
dashboard/src/main/webapp/WEB-INF/schemaUpdates/2015-03-10-submit-block-next-document.sql
stori-es/stories
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
43
2016-04-05T19:01:50.000Z
2016-12-22T00:35:19.000Z
dashboard/src/main/webapp/WEB-INF/schemaUpdates/2015-03-10-submit-block-next-document.sql
stori-es/stori_es
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
null
null
null
ALTER TABLE submitBlock ADD COLUMN nextDocument INT, ADD CONSTRAINT fk_submitBlock_document FOREIGN KEY (nextDocument) REFERENCES document (id); UPDATE submitBlock s SET s.nextDocument = (SELECT confirmation FROM questionnaire q WHERE q.id = s.questionnaire);
33.888889
91
0.704918
174eb4298d82665fb7af00a550ed4c4e55fc7ac2
87,277
cpp
C++
src/devices/cpu/psx/psx.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/cpu/psx/psx.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/cpu/psx/psx.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:smf /* * PlayStation CPU emulator * * Copyright 2003-2017 smf * * Known chip id's * CXD8530AQ * CXD8530BQ * CXD8530CQ * CXD8661R * CXD8606BQ * CXD8606CQ * * The PlayStation CPU is based on the LSI CoreWare CW33300 library, this was available packaged as an LSI LR33300. * * Differences from the LR33300: * * There is only 1k of data cache ram ( the LR33300 has 2k ) * * There is no data cache tag ram, so the data cache ram can only be used as a fast area * of ram ( which is a standard LR33300 feature ). * * If COP0 is disabled in user mode you get a coprocessor unusable exception, while * the LR33300 is documented to generate a reserved instruction exception. * * MDEC is based on the LSI Jpeg CoreWare library (CW702?). * * Known limitations of the emulation: * * Program counter, read data & write data break points are emulated, trace break points are not. * * Load/Store timings are based on load scheduling turned off & no write cache. This affects when * bus error exceptions occur and also when the read & write handlers are called. A scheduled * load will complete if a load breakpoint fires, but an unscheduled load will not. * * Reading from the data and instruction cache at the same time causes a bus conflict that * corrupts the data in a reliable but strange way, which is not emulated. * * Values written to COP1 & COP3 can be read back by the next instruction, which is not emulated. * Because of loadscheduling the value loaded with LWC1/LWC3 can be read by more than the next * instruction. * * SWC0 writes stale data from a previous operation, this is only partially emulated as the timing * is complicated. Left over instruction fetches are currently emulated as they are the most * 'interesting' and have no impact on the rest of the emulation. * * MTC0 timing is not emulated, switching to user mode while in kernel space continues * execution for another two instructions before taking an exception. Using RFE to do the same * thing causes the exception straight away, unless the RFE is the first instruction that follows * an MTC0 instruction. * * The PRId register should be 1 on some revisions of the CPU ( there might be other values too ). * * Moving to the HI/LO register after a multiply or divide, but before reading the results will * always abort the operation as if you did it immediately. In reality it should complete on it's * own, and aborting before it completes would result in returning the working results. * * Running code in cached address space does not use or update the instruction cache. * * Wait states are not emulated. * * Bus errors caused by instruction burst fetches are not supported. * */ #include "emu.h" #include "psx.h" #include "mdec.h" #include "rcnt.h" #include "sound/spu.h" #include "debugger.h" #include "psxdefs.h" #define LOG_BIOSCALL ( 0 ) #define EXC_INT ( 0 ) #define EXC_ADEL ( 4 ) #define EXC_ADES ( 5 ) #define EXC_IBE ( 6 ) #define EXC_DBE ( 7 ) #define EXC_SYS ( 8 ) #define EXC_BP ( 9 ) #define EXC_RI ( 10 ) #define EXC_CPU ( 11 ) #define EXC_OVF ( 12 ) #define CP0_INDEX ( 0 ) #define CP0_RANDOM ( 1 ) #define CP0_ENTRYLO ( 2 ) #define CP0_CONTEXT ( 4 ) #define CP0_ENTRYHI ( 10 ) #define CP0_BPC ( 3 ) #define CP0_BDA ( 5 ) #define CP0_TAR ( 6 ) #define CP0_DCIC ( 7 ) #define CP0_BADA ( 8 ) #define CP0_BDAM ( 9 ) #define CP0_BPCM ( 11 ) #define CP0_SR ( 12 ) #define CP0_CAUSE ( 13 ) #define CP0_EPC ( 14 ) #define CP0_PRID ( 15 ) #define DCIC_DB ( 1L << 0 ) #define DCIC_PC ( 1L << 1 ) #define DCIC_DA ( 1L << 2 ) #define DCIC_R ( 1L << 3 ) #define DCIC_W ( 1L << 4 ) #define DCIC_T ( 1L << 5 ) // not emulated // unknown ( 1L << 12 ) // unknown ( 1L << 13 ) // unknown ( 1L << 14 ) // unknown ( 1L << 15 ) #define DCIC_DE ( 1L << 23 ) #define DCIC_PCE ( 1L << 24 ) #define DCIC_DAE ( 1L << 25 ) #define DCIC_DR ( 1L << 26 ) #define DCIC_DW ( 1L << 27 ) #define DCIC_TE ( 1L << 28 ) // not emulated #define DCIC_KD ( 1L << 29 ) #define DCIC_UD ( 1L << 30 ) #define DCIC_TR ( 1L << 31 ) #define SR_IEC ( 1L << 0 ) #define SR_KUC ( 1L << 1 ) #define SR_ISC ( 1L << 16 ) #define SR_SWC ( 1L << 17 ) #define SR_BEV ( 1L << 22 ) #define SR_CU0 ( 1L << 28 ) #define SR_CU1 ( 1L << 29 ) #define SR_CU2 ( 1L << 30 ) #define SR_CU3 ( 1L << 31 ) #define CAUSE_EXC ( 31L << 2 ) #define CAUSE_IP ( 255L << 8 ) // software interrupts #define CAUSE_IP0 ( 1L << 8 ) #define CAUSE_IP1 ( 1L << 9 ) // hardware interrupts #define CAUSE_IP2 ( 1L << 10 ) #define CAUSE_IP3 ( 1L << 11 ) #define CAUSE_IP4 ( 1L << 12 ) #define CAUSE_IP5 ( 1L << 13 ) #define CAUSE_IP6 ( 1L << 14 ) #define CAUSE_IP7 ( 1L << 15 ) #define CAUSE_CE ( 3L << 28 ) #define CAUSE_BT ( 1L << 30 ) #define CAUSE_BD ( 1L << 31 ) #define BIU_LOCK ( 0x00000001 ) #define BIU_INV ( 0x00000002 ) #define BIU_TAG ( 0x00000004 ) #define BIU_RAM ( 0x00000008 ) #define BIU_DS ( 0x00000080 ) #define BIU_IS1 ( 0x00000800 ) #define TAG_MATCH_MASK ( 0 - ( ICACHE_ENTRIES * 4 ) ) #define TAG_MATCH ( 0x10 ) #define TAG_VALID ( 0x0f ) #define MULTIPLIER_OPERATION_IDLE ( 0 ) #define MULTIPLIER_OPERATION_MULT ( 1 ) #define MULTIPLIER_OPERATION_MULTU ( 2 ) #define MULTIPLIER_OPERATION_DIV ( 3 ) #define MULTIPLIER_OPERATION_DIVU ( 4 ) static const char *const delayn[] = { "", "at", "v0", "v1", "a0", "a1", "a2", "a3", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra", "pc", "!pc" }; // device type definition DEFINE_DEVICE_TYPE(CXD8530AQ, cxd8530aq_device, "cxd8530aq", "Sony CXD8530AQ") DEFINE_DEVICE_TYPE(CXD8530BQ, cxd8530bq_device, "cxd8530bq", "Sony CXD8530BQ") DEFINE_DEVICE_TYPE(CXD8530CQ, cxd8530cq_device, "cxd8530cq", "Sony CXD8530CQ") DEFINE_DEVICE_TYPE(CXD8661R, cxd8661r_device, "cxd8661r", "Sony CXD8661R") DEFINE_DEVICE_TYPE(CXD8606BQ, cxd8606bq_device, "cxd8606bq", "Sony CXD8606BQ") DEFINE_DEVICE_TYPE(CXD8606CQ, cxd8606cq_device, "cxd8606cq", "Sony CXD8606CQ") static const uint32_t mtc0_writemask[]= { 0x00000000, /* !INDEX */ 0x00000000, /* !RANDOM */ 0x00000000, /* !ENTRYLO */ 0xffffffff, /* BPC */ 0x00000000, /* !CONTEXT */ 0xffffffff, /* BDA */ 0x00000000, /* TAR */ 0xff80f03f, /* DCIC */ 0x00000000, /* BADA */ 0xffffffff, /* BDAM */ 0x00000000, /* !ENTRYHI */ 0xffffffff, /* BPCM */ 0xf04fff3f, /* SR */ 0x00000300, /* CAUSE */ 0x00000000, /* EPC */ 0x00000000 /* PRID */ }; uint32_t psxcpu_device::berr_r() { if( !machine().side_effects_disabled() ) m_berr = 1; return 0; } void psxcpu_device::berr_w(uint32_t data) { if( !machine().side_effects_disabled() ) m_berr = 1; } uint32_t psxcpu_device::exp_base_r() { return m_exp_base; } void psxcpu_device::exp_base_w(offs_t offset, uint32_t data, uint32_t mem_mask) { COMBINE_DATA( &m_exp_base ); // TODO: check byte writes m_exp_base = 0x1f000000 | ( m_exp_base & 0xffffff ); } uint32_t psxcpu_device::exp_base() { return m_exp_base; } uint32_t psxcpu_device::exp_config_r() { return m_exp_config; } void psxcpu_device::exp_config_w(offs_t offset, uint32_t data, uint32_t mem_mask) { COMBINE_DATA( &m_exp_config ); // TODO: check byte writes m_exp_config &= 0xaf1fffff; } uint32_t psxcpu_device::ram_config_r() { return m_ram_config; } void psxcpu_device::ram_config_w(offs_t offset, uint32_t data, uint32_t mem_mask) { uint32_t old = m_ram_config; COMBINE_DATA( &m_ram_config ); // TODO: check byte writes if( ( ( m_ram_config ^ old ) & 0xff00 ) != 0 ) { update_ram_config(); } } uint32_t psxcpu_device::rom_config_r() { return m_rom_config; } void psxcpu_device::rom_config_w(offs_t offset, uint32_t data, uint32_t mem_mask) { uint32_t old = m_rom_config; COMBINE_DATA( &m_rom_config ); // TODO: check byte writes if( ( ( m_rom_config ^ old ) & 0x001f0000 ) != 0 ) { update_rom_config(); } } uint32_t psxcpu_device::com_delay_r(offs_t offset, uint32_t mem_mask) { //verboselog( p_psx, 1, "psx_com_delay_r( %08x )\n", mem_mask ); return m_com_delay; } void psxcpu_device::com_delay_w(offs_t offset, uint32_t data, uint32_t mem_mask) { COMBINE_DATA( &m_com_delay ); // TODO: check byte writes //verboselog( p_psx, 1, "psx_com_delay_w( %08x %08x )\n", data, mem_mask ); } uint32_t psxcpu_device::biu_r() { return m_biu; } void psxcpu_device::biu_w(offs_t offset, uint32_t data, uint32_t mem_mask) { uint32_t old = m_biu; COMBINE_DATA( &m_biu ); // TODO: check byte writes if( ( old & ( BIU_RAM | BIU_DS ) ) != ( m_biu & ( BIU_RAM | BIU_DS ) ) ) { update_scratchpad(); } } void psxcpu_device::stop() { machine().debug_break(); debugger_instruction_hook( m_pc ); } uint32_t psxcpu_device::cache_readword( uint32_t offset ) { uint32_t data = 0; if( ( m_biu & BIU_TAG ) != 0 ) { if( ( m_biu & BIU_IS1 ) != 0 ) { uint32_t tag = m_icacheTag[ ( offset / 16 ) % ( ICACHE_ENTRIES / 4 ) ]; data |= tag & TAG_VALID; if( ( ( tag ^ offset ) & TAG_MATCH_MASK ) == 0 ) { data |= TAG_MATCH; } } } else if( ( m_biu & ( BIU_LOCK | BIU_INV ) ) != 0 ) { } else { if( ( m_biu & BIU_IS1 ) == BIU_IS1 ) { data |= m_icache[ ( offset / 4 ) % ICACHE_ENTRIES ]; } if( ( m_biu & BIU_DS ) == BIU_DS ) { data |= m_dcache[ ( offset / 4 ) % DCACHE_ENTRIES ]; } } return data; } void psxcpu_device::cache_writeword( uint32_t offset, uint32_t data ) { if( ( m_biu & BIU_TAG ) != 0 ) { if( ( m_biu & BIU_IS1 ) != 0 ) { m_icacheTag[ ( offset / 16 ) % ( ICACHE_ENTRIES / 4 ) ] = ( data & TAG_VALID ) | ( offset & TAG_MATCH_MASK ); } } else if( ( m_biu & ( BIU_LOCK | BIU_INV ) ) != 0 ) { if( ( m_biu & BIU_IS1 ) != 0 ) { m_icacheTag[ ( offset / 16 ) % ( ICACHE_ENTRIES / 4 ) ] = ( offset & TAG_MATCH_MASK ); } } else { if( ( m_biu & BIU_IS1 ) != 0 ) { m_icache[ ( offset / 4 ) % ICACHE_ENTRIES ] = data; } if( ( m_biu & BIU_DS ) != 0 ) { m_dcache[ ( offset / 4 ) % DCACHE_ENTRIES ] = data; } } } uint8_t psxcpu_device::readbyte( uint32_t address ) { if( m_bus_attached ) { return m_data.read_byte( address ); } return cache_readword( address ) >> ( ( address & 3 ) * 8 ); } uint16_t psxcpu_device::readhalf( uint32_t address ) { if( m_bus_attached ) { return m_data.read_word( address ); } return cache_readword( address ) >> ( ( address & 2 ) * 8 ); } uint32_t psxcpu_device::readword( uint32_t address ) { if( m_bus_attached ) { return m_data.read_dword( address ); } return cache_readword( address ); } uint32_t psxcpu_device::readword_masked( uint32_t address, uint32_t mask ) { if( m_bus_attached ) { return m_data.read_dword( address, mask ); } return cache_readword( address ); } void psxcpu_device::writeword( uint32_t address, uint32_t data ) { if( m_bus_attached ) { m_data.write_dword( address, data ); } else { cache_writeword( address, data ); } } void psxcpu_device::writeword_masked( uint32_t address, uint32_t data, uint32_t mask ) { if( m_bus_attached ) { m_data.write_dword( address, data, mask ); } else { cache_writeword( address, data ); } } static const struct { int address; int operation; const char *prototype; } bioscalls[] = { { 0xa0, 0x00, "int open(const char *name, int mode)" }, { 0xa0, 0x01, "int lseek(int fd, int offset, int whence)" }, { 0xa0, 0x02, "int read(int fd, void *buf, int nbytes)" }, { 0xa0, 0x03, "int write(int fd, void *buf, int nbytes)" }, { 0xa0, 0x04, "int close(int fd)" }, { 0xa0, 0x05, "int ioctl(int fd, int cmd, int arg)" }, { 0xa0, 0x06, "void exit(int code)" }, { 0xa0, 0x07, "sys_a0_07()" }, { 0xa0, 0x08, "char getc(int fd)" }, { 0xa0, 0x09, "void putc(char c, int fd)" }, { 0xa0, 0x0a, "todigit()" }, { 0xa0, 0x0b, "double atof(const char *s)" }, { 0xa0, 0x0c, "long strtoul(const char *s, char **ptr, int base)" }, { 0xa0, 0x0d, "unsigned long strtol(const char *s, char **ptr, int base)" }, { 0xa0, 0x0e, "int abs(int val)" }, { 0xa0, 0x0f, "long labs(long lval)" }, { 0xa0, 0x10, "long atoi(const char *s)" }, { 0xa0, 0x11, "int atol(const char *s)" }, { 0xa0, 0x12, "atob()" }, { 0xa0, 0x13, "int setjmp(jmp_buf *ctx)" }, { 0xa0, 0x14, "void longjmp(jmp_buf *ctx, int value)" }, { 0xa0, 0x15, "char *strcat(char *dst, const char *src)" }, { 0xa0, 0x16, "char *strncat(char *dst, const char *src, size_t n)" }, { 0xa0, 0x17, "int strcmp(const char *dst, const char *src)" }, { 0xa0, 0x18, "int strncmp(const char *dst, const char *src, size_t n)" }, { 0xa0, 0x19, "char *strcpy(char *dst, const char *src)" }, { 0xa0, 0x1a, "char *strncpy(char *dst, const char *src, size_t n)" }, { 0xa0, 0x1b, "size_t strlen(const char *s)" }, { 0xa0, 0x1c, "int index(const char *s, int c)" }, { 0xa0, 0x1d, "int rindex(const char *s, int c)" }, { 0xa0, 0x1e, "char *strchr(const char *s, int c)" }, { 0xa0, 0x1f, "char *strrchr(const char *s, int c)" }, { 0xa0, 0x20, "char *strpbrk(const char *dst, const char *src)" }, { 0xa0, 0x21, "size_t strspn(const char *s, const char *set)" }, { 0xa0, 0x22, "size_t strcspn(const char *s, const char *set)" }, { 0xa0, 0x23, "char *strtok(char *s, const char *set)" }, { 0xa0, 0x24, "char *strstr(const char *s, const char *set)" }, { 0xa0, 0x25, "int toupper(int c)" }, { 0xa0, 0x26, "int tolower(int c)" }, { 0xa0, 0x27, "void bcopy(const void *src, void *dst, size_t len)" }, { 0xa0, 0x28, "void bzero(void *ptr, size_t len)" }, { 0xa0, 0x29, "int bcmp(const void *ptr1, const void *ptr2, int len)" }, { 0xa0, 0x2a, "void *memcpy(void *dst, const void *src, size_t n)" }, { 0xa0, 0x2b, "void *memset(void *dst, char c, size_t n)" }, { 0xa0, 0x2c, "void *memmove(void *dst, const void *src, size_t n)" }, { 0xa0, 0x2d, "int memcmp(const void *dst, const void *src, size_t n)" }, { 0xa0, 0x2e, "void *memchr(const void *s, int c, size_t n)" }, { 0xa0, 0x2f, "int rand()" }, { 0xa0, 0x30, "void srand(unsigned int seed)" }, { 0xa0, 0x31, "void qsort(void *base, int nel, int width, int (*cmp)(void *, void *))" }, { 0xa0, 0x32, "double strtod(const char *s, char **endptr)" }, { 0xa0, 0x33, "void *malloc(int size)" }, { 0xa0, 0x34, "void free(void *buf)" }, { 0xa0, 0x35, "void *lsearch(void *key, void *base, int belp, int width, int (*cmp)(void *, void *))" }, { 0xa0, 0x36, "void *bsearch(void *key, void *base, int nel, int size, int (*cmp)(void *, void *))" }, { 0xa0, 0x37, "void *calloc(int size, int n)" }, { 0xa0, 0x38, "void *realloc(void *buf, int n)" }, { 0xa0, 0x39, "InitHeap(void *block, int size)" }, { 0xa0, 0x3a, "void _exit(int code)" }, { 0xa0, 0x3b, "char getchar(void)" }, { 0xa0, 0x3c, "void putchar(char c)" }, { 0xa0, 0x3d, "char *gets(char *s)" }, { 0xa0, 0x3e, "void puts(const char *s)" }, { 0xa0, 0x3f, "int printf(const char *fmt, ...)" }, { 0xa0, 0x40, "sys_a0_40()" }, { 0xa0, 0x41, "int LoadTest(const char *name, struct EXEC *header)" }, { 0xa0, 0x42, "int Load(const char *name, struct EXEC *header)" }, { 0xa0, 0x43, "int Exec(struct EXEC *header, int argc, char **argv)" }, { 0xa0, 0x44, "void FlushCache()" }, { 0xa0, 0x45, "void InstallInterruptHandler()" }, { 0xa0, 0x46, "GPU_dw(int x, int y, int w, int h, long *data)" }, { 0xa0, 0x47, "mem2vram(int x, int y, int w, int h, long *data)" }, { 0xa0, 0x48, "SendGPU(int status)" }, { 0xa0, 0x49, "GPU_cw(long cw)" }, { 0xa0, 0x4a, "GPU_cwb(long *pkt, int len)" }, { 0xa0, 0x4b, "SendPackets(void *ptr)" }, { 0xa0, 0x4c, "sys_a0_4c()" }, { 0xa0, 0x4d, "int GetGPUStatus()" }, { 0xa0, 0x4e, "GPU_sync()" }, { 0xa0, 0x4f, "sys_a0_4f()" }, { 0xa0, 0x50, "sys_a0_50()" }, { 0xa0, 0x51, "int LoadExec(const char *name, int, int)" }, { 0xa0, 0x52, "GetSysSp()" }, { 0xa0, 0x53, "sys_a0_53()" }, { 0xa0, 0x54, "_96_init()" }, { 0xa0, 0x55, "_bu_init()" }, { 0xa0, 0x56, "_96_remove()" }, { 0xa0, 0x57, "sys_a0_57()" }, { 0xa0, 0x58, "sys_a0_58()" }, { 0xa0, 0x59, "sys_a0_59()" }, { 0xa0, 0x5a, "sys_a0_5a()" }, { 0xa0, 0x5b, "dev_tty_init()" }, { 0xa0, 0x5c, "dev_tty_open()" }, { 0xa0, 0x5d, "dev_tty_5d()" }, { 0xa0, 0x5e, "dev_tty_ioctl()" }, { 0xa0, 0x5f, "dev_cd_open()" }, { 0xa0, 0x60, "dev_cd_read()" }, { 0xa0, 0x61, "dev_cd_close()" }, { 0xa0, 0x62, "dev_cd_firstfile()" }, { 0xa0, 0x63, "dev_cd_nextfile()" }, { 0xa0, 0x64, "dev_cd_chdir()" }, { 0xa0, 0x65, "dev_card_open()" }, { 0xa0, 0x66, "dev_card_read()" }, { 0xa0, 0x67, "dev_card_write()" }, { 0xa0, 0x68, "dev_card_close()" }, { 0xa0, 0x69, "dev_card_firstfile()" }, { 0xa0, 0x6a, "dev_card_nextfile()" }, { 0xa0, 0x6b, "dev_card_erase()" }, { 0xa0, 0x6c, "dev_card_undelete()" }, { 0xa0, 0x6d, "dev_card_format()" }, { 0xa0, 0x6e, "dev_card_rename()" }, { 0xa0, 0x6f, "dev_card_6f()" }, { 0xa0, 0x70, "_bu_init()" }, { 0xa0, 0x71, "_96_init()" }, { 0xa0, 0x72, "_96_remove()" }, { 0xa0, 0x73, "sys_a0_73()" }, { 0xa0, 0x74, "sys_a0_74()" }, { 0xa0, 0x75, "sys_a0_75()" }, { 0xa0, 0x76, "sys_a0_76()" }, { 0xa0, 0x77, "sys_a0_77()" }, { 0xa0, 0x78, "_96_CdSeekL()" }, { 0xa0, 0x79, "sys_a0_79()" }, { 0xa0, 0x7a, "sys_a0_7a()" }, { 0xa0, 0x7b, "sys_a0_7b()" }, { 0xa0, 0x7c, "_96_CdGetStatus()" }, { 0xa0, 0x7d, "sys_a0_7d()" }, { 0xa0, 0x7e, "_96_CdRead()" }, { 0xa0, 0x7f, "sys_a0_7f()" }, { 0xa0, 0x80, "sys_a0_80()" }, { 0xa0, 0x81, "sys_a0_81()" }, { 0xa0, 0x82, "sys_a0_82()" }, { 0xa0, 0x83, "sys_a0_83()" }, { 0xa0, 0x84, "sys_a0_84()" }, { 0xa0, 0x85, "_96_CdStop()" }, { 0xa0, 0x84, "sys_a0_84()" }, { 0xa0, 0x85, "sys_a0_85()" }, { 0xa0, 0x86, "sys_a0_86()" }, { 0xa0, 0x87, "sys_a0_87()" }, { 0xa0, 0x88, "sys_a0_88()" }, { 0xa0, 0x89, "sys_a0_89()" }, { 0xa0, 0x8a, "sys_a0_8a()" }, { 0xa0, 0x8b, "sys_a0_8b()" }, { 0xa0, 0x8c, "sys_a0_8c()" }, { 0xa0, 0x8d, "sys_a0_8d()" }, { 0xa0, 0x8e, "sys_a0_8e()" }, { 0xa0, 0x8f, "sys_a0_8f()" }, { 0xa0, 0x90, "sys_a0_90()" }, { 0xa0, 0x91, "sys_a0_91()" }, { 0xa0, 0x92, "sys_a0_92()" }, { 0xa0, 0x93, "sys_a0_93()" }, { 0xa0, 0x94, "sys_a0_94()" }, { 0xa0, 0x95, "sys_a0_95()" }, { 0xa0, 0x96, "AddCDROMDevice()" }, { 0xa0, 0x97, "AddMemCardDevice()" }, { 0xa0, 0x98, "DisableKernelIORedirection()" }, { 0xa0, 0x99, "EnableKernelIORedirection()" }, { 0xa0, 0x9a, "sys_a0_9a()" }, { 0xa0, 0x9b, "sys_a0_9b()" }, { 0xa0, 0x9c, "void SetConf(int Event, int TCB, int Stack)" }, { 0xa0, 0x9d, "void GetConf(int *Event, int *TCB, int *Stack)" }, { 0xa0, 0x9e, "sys_a0_9e()" }, { 0xa0, 0x9f, "void SetMem(int size)" }, { 0xa0, 0xa0, "_boot()" }, { 0xa0, 0xa1, "SystemError()" }, { 0xa0, 0xa2, "EnqueueCdIntr()" }, { 0xa0, 0xa3, "DequeueCdIntr()" }, { 0xa0, 0xa4, "sys_a0_a4()" }, { 0xa0, 0xa5, "ReadSector(int count, int sector, void *buffer)" }, { 0xa0, 0xa6, "get_cd_status()" }, { 0xa0, 0xa7, "bufs_cb_0()" }, { 0xa0, 0xa8, "bufs_cb_1()" }, { 0xa0, 0xa9, "bufs_cb_2()" }, { 0xa0, 0xaa, "bufs_cb_3()" }, { 0xa0, 0xab, "_card_info()" }, { 0xa0, 0xac, "_card_load()" }, { 0xa0, 0xad, "_card_auto()" }, { 0xa0, 0xae, "bufs_cb_4()" }, { 0xa0, 0xaf, "sys_a0_af()" }, { 0xa0, 0xb0, "sys_a0_b0()" }, { 0xa0, 0xb1, "sys_a0_b1()" }, { 0xa0, 0xb2, "do_a_long_jmp()" }, { 0xa0, 0xb3, "sys_a0_b3()" }, { 0xa0, 0xb4, "GetKernelInfo(int sub_function)" }, { 0xb0, 0x00, "SysMalloc()" }, { 0xb0, 0x01, "sys_b0_01()" }, { 0xb0, 0x02, "sys_b0_02()" }, { 0xb0, 0x03, "sys_b0_03()" }, { 0xb0, 0x04, "sys_b0_04()" }, { 0xb0, 0x05, "sys_b0_05()" }, { 0xb0, 0x06, "sys_b0_06()" }, { 0xb0, 0x07, "void DeliverEvent(u_long class, u_long event)" }, { 0xb0, 0x08, "long OpenEvent(u_long class, long spec, long mode, long (*func)())" }, { 0xb0, 0x09, "long CloseEvent(long event)" }, { 0xb0, 0x0a, "long WaitEvent(long event)" }, { 0xb0, 0x0b, "long TestEvent(long event)" }, { 0xb0, 0x0c, "long EnableEvent(long event)" }, { 0xb0, 0x0d, "long DisableEvent(long event)" }, { 0xb0, 0x0e, "OpenTh()" }, { 0xb0, 0x0f, "CloseTh()" }, { 0xb0, 0x10, "ChangeTh()" }, { 0xb0, 0x11, "sys_b0_11()" }, { 0xb0, 0x12, "int InitPAD(char *buf1, int len1, char *buf2, int len2)" }, { 0xb0, 0x13, "int StartPAD(void)" }, { 0xb0, 0x14, "int StopPAD(void)" }, { 0xb0, 0x15, "PAD_init(u_long nazo, u_long *pad_buf)" }, { 0xb0, 0x16, "u_long PAD_dr()" }, { 0xb0, 0x17, "void ReturnFromException(void)" }, { 0xb0, 0x18, "ResetEntryInt()" }, { 0xb0, 0x19, "HookEntryInt()" }, { 0xb0, 0x1a, "sys_b0_1a()" }, { 0xb0, 0x1b, "sys_b0_1b()" }, { 0xb0, 0x1c, "sys_b0_1c()" }, { 0xb0, 0x1d, "sys_b0_1d()" }, { 0xb0, 0x1e, "sys_b0_1e()" }, { 0xb0, 0x1f, "sys_b0_1f()" }, { 0xb0, 0x20, "UnDeliverEvent(int class, int event)" }, { 0xb0, 0x21, "sys_b0_21()" }, { 0xb0, 0x22, "sys_b0_22()" }, { 0xb0, 0x23, "sys_b0_23()" }, { 0xb0, 0x24, "sys_b0_24()" }, { 0xb0, 0x25, "sys_b0_25()" }, { 0xb0, 0x26, "sys_b0_26()" }, { 0xb0, 0x27, "sys_b0_27()" }, { 0xb0, 0x28, "sys_b0_28()" }, { 0xb0, 0x29, "sys_b0_29()" }, { 0xb0, 0x2a, "sys_b0_2a()" }, { 0xb0, 0x2b, "sys_b0_2b()" }, { 0xb0, 0x2c, "sys_b0_2c()" }, { 0xb0, 0x2d, "sys_b0_2d()" }, { 0xb0, 0x2e, "sys_b0_2e()" }, { 0xb0, 0x2f, "sys_b0_2f()" }, { 0xb0, 0x2f, "sys_b0_30()" }, { 0xb0, 0x31, "sys_b0_31()" }, { 0xb0, 0x32, "int open(const char *name, int access)" }, { 0xb0, 0x33, "int lseek(int fd, long pos, int seektype)" }, { 0xb0, 0x34, "int read(int fd, void *buf, int nbytes)" }, { 0xb0, 0x35, "int write(int fd, void *buf, int nbytes)" }, { 0xb0, 0x36, "close(int fd)" }, { 0xb0, 0x37, "int ioctl(int fd, int cmd, int arg)" }, { 0xb0, 0x38, "exit(int exitcode)" }, { 0xb0, 0x39, "sys_b0_39()" }, { 0xb0, 0x3a, "char getc(int fd)" }, { 0xb0, 0x3b, "putc(int fd, char ch)" }, { 0xb0, 0x3c, "char getchar(void)" }, { 0xb0, 0x3d, "putchar(char ch)" }, { 0xb0, 0x3e, "char *gets(char *s)" }, { 0xb0, 0x3f, "puts(const char *s)" }, { 0xb0, 0x40, "int cd(const char *path)" }, { 0xb0, 0x41, "int format(const char *fs)" }, { 0xb0, 0x42, "struct DIRENTRY* firstfile(const char *name, struct DIRENTRY *dir)" }, { 0xb0, 0x43, "struct DIRENTRY* nextfile(struct DIRENTRY *dir)" }, { 0xb0, 0x44, "int rename(const char *oldname, const char *newname)" }, { 0xb0, 0x45, "int delete(const char *name)" }, { 0xb0, 0x46, "undelete()" }, { 0xb0, 0x47, "AddDevice()" }, { 0xb0, 0x48, "RemoveDevice()" }, { 0xb0, 0x49, "PrintInstalledDevices()" }, { 0xb0, 0x4a, "InitCARD()" }, { 0xb0, 0x4b, "StartCARD()" }, { 0xb0, 0x4c, "StopCARD()" }, { 0xb0, 0x4d, "sys_b0_4d()" }, { 0xb0, 0x4e, "_card_write()" }, { 0xb0, 0x4f, "_card_read()" }, { 0xb0, 0x50, "_new_card()" }, { 0xb0, 0x51, "void *Krom2RawAdd(int code)" }, { 0xb0, 0x52, "sys_b0_52()" }, { 0xb0, 0x53, "sys_b0_53()" }, { 0xb0, 0x54, "long _get_errno(void)" }, { 0xb0, 0x55, "long _get_error(long fd)" }, { 0xb0, 0x56, "GetC0Table()" }, { 0xb0, 0x57, "GetB0Table()" }, { 0xb0, 0x58, "_card_chan()" }, { 0xb0, 0x59, "sys_b0_59()" }, { 0xb0, 0x5a, "sys_b0_5a()" }, { 0xb0, 0x5b, "ChangeClearPAD(int, int)" }, { 0xb0, 0x5c, "_card_status()" }, { 0xb0, 0x5d, "_card_wait()" }, { 0xc0, 0x00, "InitRCnt()" }, { 0xc0, 0x01, "InitException()" }, { 0xc0, 0x02, "SysEnqIntRP(int index, long *queue)" }, { 0xc0, 0x03, "SysDeqIntRP(int index, long *queue)" }, { 0xc0, 0x04, "int get_free_EvCB_slot(void)" }, { 0xc0, 0x05, "get_free_TCB_slot()" }, { 0xc0, 0x06, "ExceptionHandler()" }, { 0xc0, 0x07, "InstallExceptionHandlers()" }, { 0xc0, 0x08, "SysInitMemory()" }, { 0xc0, 0x09, "SysInitKMem()" }, { 0xc0, 0x0a, "ChangeClearRCnt()" }, { 0xc0, 0x0b, "SystemError()" }, { 0xc0, 0x0c, "InitDefInt()" }, { 0xc0, 0x0d, "sys_c0_0d()" }, { 0xc0, 0x0e, "sys_c0_0e()" }, { 0xc0, 0x0f, "sys_c0_0f()" }, { 0xc0, 0x10, "sys_c0_10()" }, { 0xc0, 0x11, "sys_c0_11()" }, { 0xc0, 0x12, "InstallDevices()" }, { 0xc0, 0x13, "FlushStdInOutPut()" }, { 0xc0, 0x14, "sys_c0_14()" }, { 0xc0, 0x15, "_cdevinput()" }, { 0xc0, 0x16, "_cdevscan()" }, { 0xc0, 0x17, "char _circgetc(struct device_buf *circ)" }, { 0xc0, 0x18, "_circputc(char c, struct device_buf *circ)" }, { 0xc0, 0x19, "ioabort(const char *str)" }, { 0xc0, 0x1a, "sys_c0_1a()" }, { 0xc0, 0x1b, "KernelRedirect(int flag)" }, { 0xc0, 0x1c, "PatchA0Table()" }, { 0x00, 0x00, nullptr } }; uint32_t psxcpu_device::log_bioscall_parameter( int parm ) { if( parm < 4 ) { return m_r[ 4 + parm ]; } return readword( m_r[ 29 ] + ( parm * 4 ) ); } const char *psxcpu_device::log_bioscall_string( int parm ) { int pos; uint32_t address; static char string[ 1024 ]; address = log_bioscall_parameter( parm ); if( address == 0 ) { return "NULL"; } pos = 0; string[ pos++ ] = '\"'; for( ;; ) { uint8_t c = readbyte( address ); if( c == 0 ) { break; } else if( c == '\t' ) { string[ pos++ ] = '\\'; string[ pos++ ] = 't'; } else if( c == '\r' ) { string[ pos++ ] = '\\'; string[ pos++ ] = 'r'; } else if( c == '\n' ) { string[ pos++ ] = '\\'; string[ pos++ ] = 'n'; } else if( c < 32 || c > 127 ) { string[ pos++ ] = '\\'; string[ pos++ ] = ( ( c / 64 ) % 8 ) + '0'; string[ pos++ ] = ( ( c / 8 ) % 8 ) + '0'; string[ pos++ ] = ( ( c / 1 ) % 8 ) + '0'; } else { string[ pos++ ] = c; } address++; } string[ pos++ ] = '\"'; string[ pos++ ] = 0; return string; } const char *psxcpu_device::log_bioscall_hex( int parm ) { static char string[ 1024 ]; sprintf( string, "0x%08x", log_bioscall_parameter( parm ) ); return string; } const char *psxcpu_device::log_bioscall_char( int parm ) { int c; static char string[ 1024 ]; c = log_bioscall_parameter( parm ); if( c < 32 || c > 127 ) { sprintf( string, "0x%02x", c ); } else { sprintf( string, "'%c'", c ); } return string; } void psxcpu_device::log_bioscall() { int address = m_pc - 0x04; if( address == 0xa0 || address == 0xb0 || address == 0xc0 ) { char buf[ 1024 ]; int operation = m_r[ 9 ] & 0xff; int bioscall = 0; if( ( address == 0xa0 && operation == 0x3c ) || ( address == 0xb0 && operation == 0x3d ) ) { putchar( log_bioscall_parameter( 0 ) ); } if( ( address == 0xa0 && operation == 0x03 ) || ( address == 0xb0 && operation == 0x35 ) ) { int fd = log_bioscall_parameter( 0 ); int buffer = log_bioscall_parameter( 1 ); int nbytes = log_bioscall_parameter( 2 ); if( fd == 1 ) { while( nbytes > 0 ) { uint8_t c = readbyte( buffer ); putchar( c ); nbytes--; buffer++; } } } while( bioscalls[ bioscall ].prototype != nullptr && ( bioscalls[ bioscall ].address != address || bioscalls[ bioscall ].operation != operation ) ) { bioscall++; } if( bioscalls[ bioscall ].prototype != nullptr ) { const char *prototype = bioscalls[ bioscall ].prototype; const char *parmstart = nullptr; int parm = 0; int parmlen = -1; int brackets = 0; int pos = 0; while( *( prototype ) != 0 ) { int ch = *( prototype ); switch( ch ) { case '(': brackets++; prototype++; if( brackets == 1 ) { buf[ pos++ ] = ch; parmstart = prototype; } break; case ')': if( brackets == 1 ) { parmlen = prototype - parmstart; } prototype++; brackets--; break; case ',': if( brackets == 1 ) { parmlen = prototype - parmstart; } prototype++; break; default: if( brackets == 0 ) { buf[ pos++ ] = ch; } prototype++; break; } if( parmlen >= 0 ) { while( parmlen > 0 && parmstart[ 0 ] == ' ' ) { parmstart++; parmlen--; } while( parmlen > 0 && parmstart[ parmlen - 1 ] == ' ' ) { parmlen--; } if( parmlen == 0 || ( parmlen == 4 && memcmp( parmstart, "void", 4 ) == 0 ) ) { parm = -1; } else if( parmlen == 3 && memcmp( parmstart, "...", 3 ) == 0 ) { if( parm > 0 ) { uint32_t format = log_bioscall_parameter( parm - 1 ); const char *parmstr = nullptr; int percent = 0; for( ;; ) { uint8_t c = readbyte( format ); if( c == 0 ) { break; } if( percent == 0 ) { if( c == '%' ) { percent = 1; } } else { if( c == '%' ) { percent = 0; } else if( c == '*' ) { parmstr = log_bioscall_hex( parm ); } else if( c == 's' ) { parmstr = log_bioscall_string( parm ); percent = 0; } else if( c == 'c' ) { parmstr = log_bioscall_char( parm ); percent = 0; } else if( c != '-' && c != '.' && c != 'l' && ( c < '0' || c > '9' ) ) { parmstr = log_bioscall_hex( parm ); percent = 0; } } if( parmstr != nullptr ) { if( parm > 0 ) { buf[ pos++ ] = ','; } buf[ pos++ ] = ' '; strcpy( &buf[ pos ], parmstr ); pos += strlen( parmstr ); parmstr = nullptr; parm++; } format++; } } } else if( parmlen > 0 ) { const char *parmstr; int typelen = parmlen; while( typelen > 0 && parmstart[ typelen - 1 ] != ' ' && parmstart[ typelen - 1 ] != '*' ) { typelen--; } if( typelen == 5 && memcmp( parmstart, "char ", 5 ) == 0 ) { parmstr = log_bioscall_char( parm ); } else if( typelen == 12 && memcmp( parmstart, "const char *", 12 ) == 0 ) { parmstr = log_bioscall_string( parm ); } else { parmstr = log_bioscall_hex( parm ); } if( parm > 0 ) { buf[ pos++ ] = ','; } buf[ pos++ ] = ' '; strcpy( &buf[ pos ], parmstr ); pos += strlen( parmstr ); } parmlen = -1; parm++; if( ch == ',' ) { parmstart = prototype; } else { if( parm > 0 ) { buf[ pos++ ] = ' '; } buf[ pos++ ] = ch; } } } buf[ pos ] = 0; } else { sprintf( buf, "unknown_%02x_%02x", address, operation ); } logerror( "%08x: bioscall %s\n", (unsigned int)m_r[ 31 ] - 8, buf ); } } void psxcpu_device::log_syscall() { char buf[ 1024 ]; int operation = m_r[ 4 ]; switch( operation ) { case 0: strcpy( buf, "void Exception()" ); break; case 1: strcpy( buf, "void EnterCriticalSection()" ); break; case 2: strcpy( buf, "void ExitCriticalSection()" ); break; default: sprintf( buf, "unknown_%02x", operation ); break; } logerror( "%08x: syscall %s\n", (unsigned int)m_r[ 31 ] - 8, buf ); } void psxcpu_device::update_memory_handlers() { if( ( m_cp0r[ CP0_SR ] & SR_ISC ) != 0 ) { m_bus_attached = 0; } else { m_bus_attached = 1; } } void psxcpu_device::funct_mthi() { m_multiplier_operation = MULTIPLIER_OPERATION_IDLE; m_hi = m_r[ INS_RS( m_op ) ]; } void psxcpu_device::funct_mtlo() { m_multiplier_operation = MULTIPLIER_OPERATION_IDLE; m_lo = m_r[ INS_RS( m_op ) ]; } void psxcpu_device::funct_mult() { m_multiplier_operation = MULTIPLIER_OPERATION_MULT; m_multiplier_operand1 = m_r[ INS_RS( m_op ) ]; m_multiplier_operand2 = m_r[ INS_RT( m_op ) ]; m_lo = m_multiplier_operand1; } void psxcpu_device::funct_multu() { m_multiplier_operation = MULTIPLIER_OPERATION_MULTU; m_multiplier_operand1 = m_r[ INS_RS( m_op ) ]; m_multiplier_operand2 = m_r[ INS_RT( m_op ) ]; m_lo = m_multiplier_operand1; } void psxcpu_device::funct_div() { m_multiplier_operation = MULTIPLIER_OPERATION_DIV; m_multiplier_operand1 = m_r[ INS_RS( m_op ) ]; m_multiplier_operand2 = m_r[ INS_RT( m_op ) ]; m_lo = m_multiplier_operand1; m_hi = 0; } void psxcpu_device::funct_divu() { m_multiplier_operation = MULTIPLIER_OPERATION_DIVU; m_multiplier_operand1 = m_r[ INS_RS( m_op ) ]; m_multiplier_operand2 = m_r[ INS_RT( m_op ) ]; m_lo = m_multiplier_operand1; m_hi = 0; } void psxcpu_device::multiplier_update() { switch( m_multiplier_operation ) { case MULTIPLIER_OPERATION_MULT: { int64_t result = mul_32x32( (int32_t)m_multiplier_operand1, (int32_t)m_multiplier_operand2 ); m_lo = extract_64lo( result ); m_hi = extract_64hi( result ); } break; case MULTIPLIER_OPERATION_MULTU: { uint64_t result = mulu_32x32( m_multiplier_operand1, m_multiplier_operand2 ); m_lo = extract_64lo( result ); m_hi = extract_64hi( result ); } break; case MULTIPLIER_OPERATION_DIV: if( m_multiplier_operand1 == 0x80000000 && m_multiplier_operand2 == 0xffffffff) { m_hi = 0x00000000; m_lo = 0x80000000; } else if( m_multiplier_operand2 == 0 ) { if( (int32_t)m_multiplier_operand1 < 0 ) { m_lo = 1; } else { m_lo = 0xffffffff; } m_hi = m_multiplier_operand1; } else { m_lo = (int32_t)m_multiplier_operand1 / (int32_t)m_multiplier_operand2; m_hi = (int32_t)m_multiplier_operand1 % (int32_t)m_multiplier_operand2; } break; case MULTIPLIER_OPERATION_DIVU: if( m_multiplier_operand2 == 0 ) { m_lo = 0xffffffff; m_hi = m_multiplier_operand1; } else { m_lo = m_multiplier_operand1 / m_multiplier_operand2; m_hi = m_multiplier_operand1 % m_multiplier_operand2; } break; } m_multiplier_operation = MULTIPLIER_OPERATION_IDLE; } uint32_t psxcpu_device::get_hi() { if( m_multiplier_operation != MULTIPLIER_OPERATION_IDLE ) { multiplier_update(); } return m_hi; } uint32_t psxcpu_device::get_lo() { if( m_multiplier_operation != MULTIPLIER_OPERATION_IDLE ) { multiplier_update(); } return m_lo; } int psxcpu_device::execute_unstoppable_instructions( int executeCop2 ) { switch( INS_OP( m_op ) ) { case OP_SPECIAL: switch( INS_FUNCT( m_op ) ) { case FUNCT_MTHI: funct_mthi(); break; case FUNCT_MTLO: funct_mtlo(); break; case FUNCT_MULT: funct_mult(); break; case FUNCT_MULTU: funct_multu(); break; case FUNCT_DIV: funct_div(); break; case FUNCT_DIVU: funct_divu(); break; } break; case OP_COP2: if( executeCop2 ) { switch( INS_CO( m_op ) ) { case 1: if( ( m_cp0r[ CP0_SR ] & SR_CU2 ) == 0 ) { return 0; } if( !m_gte.docop2( m_pc, INS_COFUN( m_op ) ) ) { stop(); } break; } } } return 1; } void psxcpu_device::update_address_masks() { if( ( m_cp0r[ CP0_SR ] & SR_KUC ) != 0 ) { m_bad_byte_address_mask = 0x80000000; m_bad_half_address_mask = 0x80000001; m_bad_word_address_mask = 0x80000003; } else { m_bad_byte_address_mask = 0; m_bad_half_address_mask = 1; m_bad_word_address_mask = 3; } } void psxcpu_device::update_scratchpad() { if( ( m_biu & BIU_RAM ) == 0 ) { m_program->install_readwrite_handler( 0x1f800000, 0x1f8003ff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); } else if( ( m_biu & BIU_DS ) == 0 ) { m_program->install_read_handler( 0x1f800000, 0x1f8003ff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)) ); m_program->nop_write( 0x1f800000, 0x1f8003ff ); } else { m_program->install_ram( 0x1f800000, 0x1f8003ff, m_dcache ); } } void psxcpu_device::update_ram_config() { /// TODO: find out what these values really control and confirm they are the same on each cpu type. int window_size = 0; switch( ( m_ram_config >> 8 ) & 0xf ) { case 0x8: // konami gv window_size = 0x0200000; break; case 0xc: // zn1/konami gq/namco system 11/twinkle/system 573 window_size = 0x0400000; break; case 0x3: // zn2 case 0xb: // console/primal rage 2 window_size = 0x0800000; break; case 0xf: // namco system 10/namco system 12 window_size = 0x1000000; break; } uint32_t ram_size = m_ram->size(); uint8_t *pointer = m_ram->pointer(); if( ram_size > window_size ) { ram_size = window_size; } if( ram_size > 0 ) { int start = 0; while( start < window_size ) { m_program->install_ram( start + 0x00000000, start + 0x00000000 + ram_size - 1, pointer ); m_program->install_ram( start + 0x80000000, start + 0x80000000 + ram_size - 1, pointer ); m_program->install_ram( start + 0xa0000000, start + 0xa0000000 + ram_size - 1, pointer ); start += ram_size; } } m_program->install_readwrite_handler( 0x00000000 + window_size, 0x1effffff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); m_program->install_readwrite_handler( 0x80000000 + window_size, 0x9effffff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); m_program->install_readwrite_handler( 0xa0000000 + window_size, 0xbeffffff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); } void psxcpu_device::update_rom_config() { int window_size = 1 << ( ( m_rom_config >> 16 ) & 0x1f ); int max_window_size = 0x400000; if( window_size > max_window_size ) { window_size = max_window_size; } uint32_t rom_size = m_rom->bytes(); uint8_t *pointer = m_rom->base(); if( rom_size > window_size ) { rom_size = window_size; } if( rom_size > 0 ) { int start = 0; while( start < window_size ) { m_program->install_rom( start + 0x1fc00000, start + 0x1fc00000 + rom_size - 1, pointer ); m_program->install_rom( start + 0x9fc00000, start + 0x9fc00000 + rom_size - 1, pointer ); m_program->install_rom( start + 0xbfc00000, start + 0xbfc00000 + rom_size - 1, pointer ); start += rom_size; } } if( window_size < max_window_size && !m_disable_rom_berr) { m_program->install_readwrite_handler( 0x1fc00000 + window_size, 0x1fffffff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); m_program->install_readwrite_handler( 0x9fc00000 + window_size, 0x9fffffff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); m_program->install_readwrite_handler( 0xbfc00000 + window_size, 0xbfffffff, read32smo_delegate(*this, FUNC(psxcpu_device::berr_r)), write32smo_delegate(*this, FUNC(psxcpu_device::berr_w)) ); } } void psxcpu_device::update_cop0(int reg) { if (reg == CP0_SR) { update_memory_handlers(); update_address_masks(); } if ((reg == CP0_SR || reg == CP0_CAUSE) && (m_cp0r[CP0_SR] & SR_IEC) != 0) { uint32_t ip = m_cp0r[CP0_SR] & m_cp0r[CP0_CAUSE] & CAUSE_IP; if (ip != 0) { if (ip & CAUSE_IP0) debugger_exception_hook(EXC_INT); if (ip & CAUSE_IP1) debugger_exception_hook(EXC_INT); //if (ip & CAUSE_IP2) debugger_interrupt_hook(PSXCPU_IRQ0); //if (ip & CAUSE_IP3) debugger_interrupt_hook(PSXCPU_IRQ1); //if (ip & CAUSE_IP4) debugger_interrupt_hook(PSXCPU_IRQ2); //if (ip & CAUSE_IP5) debugger_interrupt_hook(PSXCPU_IRQ3); //if (ip & CAUSE_IP6) debugger_interrupt_hook(PSXCPU_IRQ4); //if (ip & CAUSE_IP7) debugger_interrupt_hook(PSXCPU_IRQ5); m_op = m_instruction.read_dword(m_pc); execute_unstoppable_instructions(1); exception(EXC_INT); } } } void psxcpu_device::commit_delayed_load() { if( m_delayr != 0 ) { m_r[ m_delayr ] = m_delayv; m_delayr = 0; m_delayv = 0; } } void psxcpu_device::set_pc( unsigned pc ) { m_pc = pc; } void psxcpu_device::fetch_next_op() { if( m_delayr == PSXCPU_DELAYR_PC ) { uint32_t safepc = m_delayv & ~m_bad_word_address_mask; m_op = m_instruction.read_dword( safepc ); } else { m_op = m_instruction.read_dword( m_pc + 4 ); } } void psxcpu_device::advance_pc() { if( m_delayr == PSXCPU_DELAYR_PC ) { m_pc = m_delayv; m_delayr = 0; m_delayv = 0; } else if( m_delayr == PSXCPU_DELAYR_NOTPC ) { m_delayr = 0; m_delayv = 0; m_pc += 4; } else { commit_delayed_load(); m_pc += 4; } } void psxcpu_device::load( uint32_t reg, uint32_t value ) { advance_pc(); if( reg != 0 ) { m_r[ reg ] = value; } } void psxcpu_device::delayed_load( uint32_t reg, uint32_t value ) { if( m_delayr == reg ) { m_delayr = 0; m_delayv = 0; } advance_pc(); m_delayr = reg; m_delayv = value; } void psxcpu_device::branch( uint32_t address ) { advance_pc(); m_delayr = PSXCPU_DELAYR_PC; m_delayv = address; } void psxcpu_device::conditional_branch( int takeBranch ) { advance_pc(); if( takeBranch ) { m_delayr = PSXCPU_DELAYR_PC; m_delayv = m_pc + ( PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ) << 2 ); } else { m_delayr = PSXCPU_DELAYR_NOTPC; m_delayv = 0; } } void psxcpu_device::unconditional_branch() { advance_pc(); m_delayr = PSXCPU_DELAYR_PC; m_delayv = ( m_pc & 0xf0000000 ) + ( INS_TARGET( m_op ) << 2 ); } void psxcpu_device::common_exception( int exception, uint32_t romOffset, uint32_t ramOffset ) { int cause = ( exception << 2 ) | ( ( ( m_op >> 26 ) & 3 ) << 28 ); if( m_delayr == PSXCPU_DELAYR_PC ) { cause |= CAUSE_BT; m_cp0r[ CP0_TAR ] = m_delayv; } else if( m_delayr == PSXCPU_DELAYR_NOTPC ) { m_cp0r[ CP0_TAR ] = m_pc + 4; } else { commit_delayed_load(); } if( m_delayr == PSXCPU_DELAYR_PC || m_delayr == PSXCPU_DELAYR_NOTPC ) { cause |= CAUSE_BD; m_cp0r[ CP0_EPC ] = m_pc - 4; } else { m_cp0r[ CP0_EPC ] = m_pc; } if (exception != EXC_INT) { if (LOG_BIOSCALL) logerror("%08x: Exception %d\n", m_pc, exception); debugger_exception_hook(exception); } m_delayr = 0; m_delayv = 0; m_berr = 0; if( m_cp0r[ CP0_SR ] & SR_BEV ) { set_pc( romOffset ); } else { set_pc( ramOffset ); } m_cp0r[ CP0_SR ] = ( m_cp0r[ CP0_SR ] & ~0x3f ) | ( ( m_cp0r[ CP0_SR ] << 2 ) & 0x3f ); m_cp0r[ CP0_CAUSE ] = ( m_cp0r[ CP0_CAUSE ] & ~( CAUSE_EXC | CAUSE_BD | CAUSE_BT | CAUSE_CE ) ) | cause; update_cop0( CP0_SR ); } void psxcpu_device::exception( int exception ) { common_exception( exception, 0xbfc00180, 0x80000080 ); } void psxcpu_device::breakpoint_exception() { fetch_next_op(); execute_unstoppable_instructions( 1 ); common_exception( EXC_BP, 0xbfc00140, 0x80000040 ); } void psxcpu_device::fetch_bus_error_exception() { common_exception( EXC_IBE, 0xbfc00180, 0x80000080 ); } void psxcpu_device::load_bus_error_exception() { fetch_next_op(); execute_unstoppable_instructions( 0 ); common_exception( EXC_DBE, 0xbfc00180, 0x80000080 ); } void psxcpu_device::store_bus_error_exception() { fetch_next_op(); if( execute_unstoppable_instructions( 1 ) ) { advance_pc(); if( ( m_pc & m_bad_word_address_mask ) != 0 ) { load_bad_address( m_pc ); return; } fetch_next_op(); execute_unstoppable_instructions( 0 ); } common_exception( EXC_DBE, 0xbfc00180, 0x80000080 ); } void psxcpu_device::load_bad_address( uint32_t address ) { m_cp0r[ CP0_BADA ] = address; exception( EXC_ADEL ); } void psxcpu_device::store_bad_address( uint32_t address ) { m_cp0r[ CP0_BADA ] = address; exception( EXC_ADES ); } int psxcpu_device::data_address_breakpoint( int dcic_rw, int dcic_status, uint32_t address ) { if( address < 0x1f000000 || address > 0x1fffffff ) { if( ( m_cp0r[ CP0_DCIC ] & DCIC_DE ) != 0 && ( m_cp0r[ CP0_DCIC ] & dcic_rw ) == dcic_rw && ( ( ( m_cp0r[ CP0_DCIC ] & DCIC_KD ) != 0 && ( m_pc & 0x80000000 ) != 0 ) || ( ( m_cp0r[ CP0_DCIC ] & DCIC_UD ) != 0 && ( m_pc & 0x80000000 ) == 0 ) ) ) { if( ( address & m_cp0r[ CP0_BDAM ] ) == ( m_cp0r[ CP0_BDA ] & m_cp0r[ CP0_BDAM ] ) ) { m_cp0r[ CP0_DCIC ] |= dcic_status; if( ( m_cp0r[ CP0_DCIC ] & DCIC_TR ) != 0 ) { return 1; } } } } return 0; } int psxcpu_device::program_counter_breakpoint() { if( ( m_cp0r[ CP0_DCIC ] & DCIC_DE ) != 0 && ( m_cp0r[ CP0_DCIC ] & DCIC_PCE ) != 0 && ( ( ( m_cp0r[ CP0_DCIC ] & DCIC_KD ) != 0 && ( m_pc & 0x80000000 ) != 0 ) || ( ( m_cp0r[ CP0_DCIC ] & DCIC_UD ) != 0 && ( m_pc & 0x80000000 ) == 0 ) ) ) { if( ( m_pc & m_cp0r[ CP0_BPCM ] ) == ( m_cp0r[ CP0_BPC ] & m_cp0r[ CP0_BPCM ] ) ) { m_cp0r[ CP0_DCIC ] |= DCIC_PC | DCIC_DB; if( ( m_cp0r[ CP0_DCIC ] & DCIC_TR ) != 0 ) { return 1; } } } return 0; } int psxcpu_device::load_data_address_breakpoint( uint32_t address ) { return data_address_breakpoint( DCIC_DR | DCIC_DAE, DCIC_DB | DCIC_DA | DCIC_R, address ); } int psxcpu_device::store_data_address_breakpoint( uint32_t address ) { return data_address_breakpoint( DCIC_DW | DCIC_DAE, DCIC_DB | DCIC_DA | DCIC_W, address ); } // On-board RAM and peripherals void psxcpu_device::psxcpu_internal_map(address_map &map) { map(0x1f800000, 0x1f8003ff).noprw(); /* scratchpad */ map(0x1f800400, 0x1f800fff).rw(FUNC(psxcpu_device::berr_r), FUNC(psxcpu_device::berr_w)); map(0x1f801000, 0x1f801003).rw(FUNC(psxcpu_device::exp_base_r), FUNC(psxcpu_device::exp_base_w)); map(0x1f801004, 0x1f801007).ram(); map(0x1f801008, 0x1f80100b).rw(FUNC(psxcpu_device::exp_config_r), FUNC(psxcpu_device::exp_config_w)); map(0x1f80100c, 0x1f80100f).ram(); map(0x1f801010, 0x1f801013).rw(FUNC(psxcpu_device::rom_config_r), FUNC(psxcpu_device::rom_config_w)); map(0x1f801014, 0x1f80101f).ram(); /* 1f801014 spu delay */ /* 1f801018 dv delay */ map(0x1f801020, 0x1f801023).rw(FUNC(psxcpu_device::com_delay_r), FUNC(psxcpu_device::com_delay_w)); map(0x1f801024, 0x1f80102f).ram(); map(0x1f801040, 0x1f80104f).rw("sio0", FUNC(psxsio_device::read), FUNC(psxsio_device::write)); map(0x1f801050, 0x1f80105f).rw("sio1", FUNC(psxsio_device::read), FUNC(psxsio_device::write)); map(0x1f801060, 0x1f801063).rw(FUNC(psxcpu_device::ram_config_r), FUNC(psxcpu_device::ram_config_w)); map(0x1f801064, 0x1f80106f).ram(); map(0x1f801070, 0x1f801077).rw("irq", FUNC(psxirq_device::read), FUNC(psxirq_device::write)); map(0x1f801080, 0x1f8010ff).rw("dma", FUNC(psxdma_device::read), FUNC(psxdma_device::write)); map(0x1f801100, 0x1f80112f).rw("rcnt", FUNC(psxrcnt_device::read), FUNC(psxrcnt_device::write)); map(0x1f801800, 0x1f801803).rw(FUNC(psxcpu_device::cd_r), FUNC(psxcpu_device::cd_w)); map(0x1f801810, 0x1f801817).rw(FUNC(psxcpu_device::gpu_r), FUNC(psxcpu_device::gpu_w)); map(0x1f801820, 0x1f801827).rw("mdec", FUNC(psxmdec_device::read), FUNC(psxmdec_device::write)); map(0x1f801c00, 0x1f801dff).rw(FUNC(psxcpu_device::spu_r), FUNC(psxcpu_device::spu_w)); map(0x1f802020, 0x1f802033).ram(); /* ?? */ /* 1f802030 int 2000 */ /* 1f802040 dip switches */ map(0x1f802040, 0x1f802043).nopw(); map(0x20000000, 0x7fffffff).rw(FUNC(psxcpu_device::berr_r), FUNC(psxcpu_device::berr_w)); map(0xc0000000, 0xfffdffff).rw(FUNC(psxcpu_device::berr_r), FUNC(psxcpu_device::berr_w)); map(0xfffe0130, 0xfffe0133).rw(FUNC(psxcpu_device::biu_r), FUNC(psxcpu_device::biu_w)); } //************************************************************************** // DEVICE INTERFACE //************************************************************************** //------------------------------------------------- // psxcpu_device - constructor //------------------------------------------------- psxcpu_device::psxcpu_device( const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock ) : cpu_device( mconfig, type, tag, owner, clock ), m_program_config( "program", ENDIANNESS_LITTLE, 32, 32, 0, address_map_constructor(FUNC(psxcpu_device::psxcpu_internal_map), this)), m_gpu_read_handler( *this ), m_gpu_write_handler( *this ), m_spu_read_handler( *this ), m_spu_write_handler( *this ), m_cd_read_handler( *this ), m_cd_write_handler( *this ), m_ram( *this, "ram" ) { m_disable_rom_berr = false; } cxd8530aq_device::cxd8530aq_device( const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock ) : psxcpu_device( mconfig, CXD8530AQ, tag, owner, clock) { } cxd8530bq_device::cxd8530bq_device( const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock ) : psxcpu_device( mconfig, CXD8530BQ, tag, owner, clock) { } cxd8530cq_device::cxd8530cq_device( const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock ) : psxcpu_device( mconfig, CXD8530CQ, tag, owner, clock) { } cxd8661r_device::cxd8661r_device( const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock ) : psxcpu_device( mconfig, CXD8661R, tag, owner, clock) { } cxd8606bq_device::cxd8606bq_device( const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock ) : psxcpu_device( mconfig, CXD8606BQ, tag, owner, clock) { } cxd8606cq_device::cxd8606cq_device( const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock ) : psxcpu_device( mconfig, CXD8606CQ, tag, owner, clock) { } //------------------------------------------------- // device_start - start up the device //------------------------------------------------- void psxcpu_device::device_start() { // get our address spaces m_program = &space( AS_PROGRAM ); m_program->cache(m_instruction); m_program->specific(m_data); save_item( NAME( m_op ) ); save_item( NAME( m_pc ) ); save_item( NAME( m_delayv ) ); save_item( NAME( m_delayr ) ); save_item( NAME( m_hi ) ); save_item( NAME( m_lo ) ); save_item( NAME( m_biu ) ); save_item( NAME( m_r ) ); save_item( NAME( m_cp0r ) ); save_item( NAME( m_gte.m_cp2cr ) ); save_item( NAME( m_gte.m_cp2dr ) ); save_item( NAME( m_icacheTag ) ); save_item( NAME( m_icache ) ); save_item( NAME( m_dcache ) ); save_item( NAME( m_multiplier_operation ) ); save_item( NAME( m_multiplier_operand1 ) ); save_item( NAME( m_multiplier_operand2 ) ); save_item( NAME( m_exp_base ) ); save_item( NAME( m_exp_config ) ); save_item( NAME( m_ram_config ) ); save_item( NAME( m_rom_config ) ); state_add( STATE_GENPC, "GENPC", m_pc ).noshow(); state_add( STATE_GENPCBASE, "CURPC", m_pc ).noshow(); state_add( PSXCPU_PC, "pc", m_pc ); state_add( PSXCPU_DELAYR, "delayr", m_delayr ).formatstr("%8s"); state_add( PSXCPU_DELAYV, "delayv", m_delayv ); state_add( PSXCPU_HI, "hi", m_hi ); state_add( PSXCPU_LO, "lo", m_lo ); state_add( PSXCPU_BIU, "biu", m_biu ); state_add( PSXCPU_R0, "zero", m_r[ 0 ] ); state_add( PSXCPU_R1, "at", m_r[ 1 ] ); state_add( PSXCPU_R2, "v0", m_r[ 2 ] ); state_add( PSXCPU_R3, "v1", m_r[ 3 ] ); state_add( PSXCPU_R4, "a0", m_r[ 4 ] ); state_add( PSXCPU_R5, "a1", m_r[ 5 ] ); state_add( PSXCPU_R6, "a2", m_r[ 6 ] ); state_add( PSXCPU_R7, "a3", m_r[ 7 ] ); state_add( PSXCPU_R8, "t0", m_r[ 8 ] ); state_add( PSXCPU_R9, "t1", m_r[ 9 ] ); state_add( PSXCPU_R10, "t2", m_r[ 10 ] ); state_add( PSXCPU_R11, "t3", m_r[ 11 ] ); state_add( PSXCPU_R12, "t4", m_r[ 12 ] ); state_add( PSXCPU_R13, "t5", m_r[ 13 ] ); state_add( PSXCPU_R14, "t6", m_r[ 14 ] ); state_add( PSXCPU_R15, "t7", m_r[ 15 ] ); state_add( PSXCPU_R16, "s0", m_r[ 16 ] ); state_add( PSXCPU_R17, "s1", m_r[ 17 ] ); state_add( PSXCPU_R18, "s2", m_r[ 18 ] ); state_add( PSXCPU_R19, "s3", m_r[ 19 ] ); state_add( PSXCPU_R20, "s4", m_r[ 20 ] ); state_add( PSXCPU_R21, "s5", m_r[ 21 ] ); state_add( PSXCPU_R22, "s6", m_r[ 22 ] ); state_add( PSXCPU_R23, "s7", m_r[ 23 ] ); state_add( PSXCPU_R24, "t8", m_r[ 24 ] ); state_add( PSXCPU_R25, "t9", m_r[ 25 ] ); state_add( PSXCPU_R26, "k0", m_r[ 26 ] ); state_add( PSXCPU_R27, "k1", m_r[ 27 ] ); state_add( PSXCPU_R28, "gp", m_r[ 28 ] ); state_add( PSXCPU_R29, "sp", m_r[ 29 ] ); state_add( PSXCPU_R30, "fp", m_r[ 30 ] ); state_add( PSXCPU_R31, "ra", m_r[ 31 ] ); state_add( PSXCPU_CP0R0, "!Index", m_cp0r[ 0 ] ); state_add( PSXCPU_CP0R1, "!Random", m_cp0r[ 1 ] ); state_add( PSXCPU_CP0R2, "!EntryLo", m_cp0r[ 2 ] ); state_add( PSXCPU_CP0R3, "BPC", m_cp0r[ 3 ] ); state_add( PSXCPU_CP0R4, "!Context", m_cp0r[ 4 ] ); state_add( PSXCPU_CP0R5, "BDA", m_cp0r[ 5 ] ); state_add( PSXCPU_CP0R6, "TAR", m_cp0r[ 6 ] ); state_add( PSXCPU_CP0R7, "DCIC", m_cp0r[ 7 ] ); state_add( PSXCPU_CP0R8, "BadA", m_cp0r[ 8 ] ); state_add( PSXCPU_CP0R9, "BDAM", m_cp0r[ 9 ] ); state_add( PSXCPU_CP0R10, "!EntryHi", m_cp0r[ 10 ] ); state_add( PSXCPU_CP0R11, "BPCM", m_cp0r[ 11 ] ); state_add( PSXCPU_CP0R12, "SR", m_cp0r[ 12 ] ).callimport(); state_add( PSXCPU_CP0R13, "Cause", m_cp0r[ 13 ] ).callimport(); state_add( PSXCPU_CP0R14, "EPC", m_cp0r[ 14 ] ); state_add( PSXCPU_CP0R15, "PRId", m_cp0r[ 15 ] ); state_add( PSXCPU_CP2DR0, "vxy0", m_gte.m_cp2dr[ 0 ].d ); state_add( PSXCPU_CP2DR1, "vz0", m_gte.m_cp2dr[ 1 ].d ); state_add( PSXCPU_CP2DR2, "vxy1", m_gte.m_cp2dr[ 2 ].d ); state_add( PSXCPU_CP2DR3, "vz1", m_gte.m_cp2dr[ 3 ].d ); state_add( PSXCPU_CP2DR4, "vxy2", m_gte.m_cp2dr[ 4 ].d ); state_add( PSXCPU_CP2DR5, "vz2", m_gte.m_cp2dr[ 5 ].d ); state_add( PSXCPU_CP2DR6, "rgb", m_gte.m_cp2dr[ 6 ].d ); state_add( PSXCPU_CP2DR7, "otz", m_gte.m_cp2dr[ 7 ].d ); state_add( PSXCPU_CP2DR8, "ir0", m_gte.m_cp2dr[ 8 ].d ); state_add( PSXCPU_CP2DR9, "ir1", m_gte.m_cp2dr[ 9 ].d ); state_add( PSXCPU_CP2DR10, "ir2", m_gte.m_cp2dr[ 10 ].d ); state_add( PSXCPU_CP2DR11, "ir3", m_gte.m_cp2dr[ 11 ].d ); state_add( PSXCPU_CP2DR12, "sxy0", m_gte.m_cp2dr[ 12 ].d ); state_add( PSXCPU_CP2DR13, "sxy1", m_gte.m_cp2dr[ 13 ].d ); state_add( PSXCPU_CP2DR14, "sxy2", m_gte.m_cp2dr[ 14 ].d ); state_add( PSXCPU_CP2DR15, "sxyp", m_gte.m_cp2dr[ 15 ].d ); state_add( PSXCPU_CP2DR16, "sz0", m_gte.m_cp2dr[ 16 ].d ); state_add( PSXCPU_CP2DR17, "sz1", m_gte.m_cp2dr[ 17 ].d ); state_add( PSXCPU_CP2DR18, "sz2", m_gte.m_cp2dr[ 18 ].d ); state_add( PSXCPU_CP2DR19, "sz3", m_gte.m_cp2dr[ 19 ].d ); state_add( PSXCPU_CP2DR20, "rgb0", m_gte.m_cp2dr[ 20 ].d ); state_add( PSXCPU_CP2DR21, "rgb1", m_gte.m_cp2dr[ 21 ].d ); state_add( PSXCPU_CP2DR22, "rgb2", m_gte.m_cp2dr[ 22 ].d ); state_add( PSXCPU_CP2DR23, "res1", m_gte.m_cp2dr[ 23 ].d ); state_add( PSXCPU_CP2DR24, "mac0", m_gte.m_cp2dr[ 24 ].d ); state_add( PSXCPU_CP2DR25, "mac1", m_gte.m_cp2dr[ 25 ].d ); state_add( PSXCPU_CP2DR26, "mac2", m_gte.m_cp2dr[ 26 ].d ); state_add( PSXCPU_CP2DR27, "mac3", m_gte.m_cp2dr[ 27 ].d ); state_add( PSXCPU_CP2DR28, "irgb", m_gte.m_cp2dr[ 28 ].d ); state_add( PSXCPU_CP2DR29, "orgb", m_gte.m_cp2dr[ 29 ].d ); state_add( PSXCPU_CP2DR30, "lzcs", m_gte.m_cp2dr[ 30 ].d ); state_add( PSXCPU_CP2DR31, "lzcr", m_gte.m_cp2dr[ 31 ].d ); state_add( PSXCPU_CP2CR0, "r11r12", m_gte.m_cp2cr[ 0 ].d ); state_add( PSXCPU_CP2CR1, "r13r21", m_gte.m_cp2cr[ 1 ].d ); state_add( PSXCPU_CP2CR2, "r22r23", m_gte.m_cp2cr[ 2 ].d ); state_add( PSXCPU_CP2CR3, "r31r32", m_gte.m_cp2cr[ 3 ].d ); state_add( PSXCPU_CP2CR4, "r33", m_gte.m_cp2cr[ 4 ].d ); state_add( PSXCPU_CP2CR5, "trx", m_gte.m_cp2cr[ 5 ].d ); state_add( PSXCPU_CP2CR6, "try", m_gte.m_cp2cr[ 6 ].d ); state_add( PSXCPU_CP2CR7, "trz", m_gte.m_cp2cr[ 7 ].d ); state_add( PSXCPU_CP2CR8, "l11l12", m_gte.m_cp2cr[ 8 ].d ); state_add( PSXCPU_CP2CR9, "l13l21", m_gte.m_cp2cr[ 9 ].d ); state_add( PSXCPU_CP2CR10, "l22l23", m_gte.m_cp2cr[ 10 ].d ); state_add( PSXCPU_CP2CR11, "l31l32", m_gte.m_cp2cr[ 11 ].d ); state_add( PSXCPU_CP2CR12, "l33", m_gte.m_cp2cr[ 12 ].d ); state_add( PSXCPU_CP2CR13, "rbk", m_gte.m_cp2cr[ 13 ].d ); state_add( PSXCPU_CP2CR14, "gbk", m_gte.m_cp2cr[ 14 ].d ); state_add( PSXCPU_CP2CR15, "bbk", m_gte.m_cp2cr[ 15 ].d ); state_add( PSXCPU_CP2CR16, "lr1lr2", m_gte.m_cp2cr[ 16 ].d ); state_add( PSXCPU_CP2CR17, "lr31g1", m_gte.m_cp2cr[ 17 ].d ); state_add( PSXCPU_CP2CR18, "lg2lg3", m_gte.m_cp2cr[ 18 ].d ); state_add( PSXCPU_CP2CR19, "lb1lb2", m_gte.m_cp2cr[ 19 ].d ); state_add( PSXCPU_CP2CR20, "lb3", m_gte.m_cp2cr[ 20 ].d ); state_add( PSXCPU_CP2CR21, "rfc", m_gte.m_cp2cr[ 21 ].d ); state_add( PSXCPU_CP2CR22, "gfc", m_gte.m_cp2cr[ 22 ].d ); state_add( PSXCPU_CP2CR23, "bfc", m_gte.m_cp2cr[ 23 ].d ); state_add( PSXCPU_CP2CR24, "ofx", m_gte.m_cp2cr[ 24 ].d ); state_add( PSXCPU_CP2CR25, "ofy", m_gte.m_cp2cr[ 25 ].d ); state_add( PSXCPU_CP2CR26, "h", m_gte.m_cp2cr[ 26 ].d ); state_add( PSXCPU_CP2CR27, "dqa", m_gte.m_cp2cr[ 27 ].d ); state_add( PSXCPU_CP2CR28, "dqb", m_gte.m_cp2cr[ 28 ].d ); state_add( PSXCPU_CP2CR29, "zsf3", m_gte.m_cp2cr[ 29 ].d ); state_add( PSXCPU_CP2CR30, "zsf4", m_gte.m_cp2cr[ 30 ].d ); state_add( PSXCPU_CP2CR31, "flag", m_gte.m_cp2cr[ 31 ].d ); // set our instruction counter set_icountptr(m_icount); m_gpu_read_handler.resolve_safe( 0 ); m_gpu_write_handler.resolve_safe(); m_spu_read_handler.resolve_safe( 0 ); m_spu_write_handler.resolve_safe(); m_cd_read_handler.resolve_safe( 0 ); m_cd_write_handler.resolve_safe(); m_rom = memregion( "rom" ); } //------------------------------------------------- // device_reset - reset the device //------------------------------------------------- void psxcpu_device::device_reset() { m_ram_config = 0x800; update_ram_config(); m_rom_config = 0x00130000; update_rom_config(); /// TODO: get dma to access ram through the memory map? psxdma_device *psxdma = subdevice<psxdma_device>( "dma" ); psxdma->m_ram = (uint32_t *)m_ram->pointer(); psxdma->m_ramsize = m_ram->size(); m_delayr = 0; m_delayv = 0; m_berr = 0; m_biu = 0; m_multiplier_operation = MULTIPLIER_OPERATION_IDLE; m_r[ 0 ] = 0; m_cp0r[ CP0_SR ] = SR_BEV; m_cp0r[ CP0_CAUSE ] = 0x00000000; m_cp0r[ CP0_PRID ] = 0x00000002; m_cp0r[ CP0_DCIC ] = 0x00000000; m_cp0r[ CP0_BPCM ] = 0xffffffff; m_cp0r[ CP0_BDAM ] = 0xffffffff; update_memory_handlers(); update_address_masks(); update_scratchpad(); set_pc( 0xbfc00000 ); } //------------------------------------------------- // device_post_load - device-specific post-load //------------------------------------------------- void psxcpu_device::device_post_load() { update_memory_handlers(); update_address_masks(); update_scratchpad(); update_ram_config(); update_rom_config(); } //------------------------------------------------- // state_import - import state into the device, // after it has been set //------------------------------------------------- void psxcpu_device::state_import( const device_state_entry &entry ) { switch( entry.index() ) { case PSXCPU_CP0R12: // SR case PSXCPU_CP0R13: // CAUSE update_cop0( entry.index() - PSXCPU_CP0R0 ); break; } } //------------------------------------------------- // state_string_export - export state as a string // for the debugger //------------------------------------------------- void psxcpu_device::state_string_export( const device_state_entry &entry, std::string &str ) const { switch( entry.index() ) { case PSXCPU_DELAYR: if( m_delayr <= PSXCPU_DELAYR_NOTPC ) { str = string_format("%02x %-3s", m_delayr, delayn[m_delayr]); } else { str = string_format("%02x ---", m_delayr); } break; } } //------------------------------------------------- // disassemble - call the disassembly // helper function //------------------------------------------------- std::unique_ptr<util::disasm_interface> psxcpu_device::create_disassembler() { return std::make_unique<psxcpu_disassembler>(static_cast<psxcpu_disassembler::config *>(this)); } uint32_t psxcpu_device::get_register_from_pipeline( int reg ) { if( m_delayr == reg ) { return m_delayv; } return m_r[ reg ]; } int psxcpu_device::cop0_usable() { if( ( m_cp0r[ CP0_SR ] & SR_KUC ) != 0 && ( m_cp0r[ CP0_SR ] & SR_CU0 ) == 0 ) { exception( EXC_CPU ); return 0; } return 1; } void psxcpu_device::lwc( int cop, int sr_cu ) { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( m_cp0r[ CP0_SR ] & sr_cu ) == 0 ) { exception( EXC_CPU ); } else if( ( address & m_bad_word_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = readword( address ); if( m_berr ) { load_bus_error_exception(); } else { int reg = INS_RT( m_op ); advance_pc(); switch( cop ) { case 0: /* lwc0 doesn't update any cop0 registers */ break; case 1: setcp1dr( reg, data ); break; case 2: m_gte.setcp2dr( m_pc, reg, data ); break; case 3: setcp3dr( reg, data ); break; } } } } void psxcpu_device::swc( int cop, int sr_cu ) { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = store_data_address_breakpoint( address ); if( ( m_cp0r[ CP0_SR ] & sr_cu ) == 0 ) { exception( EXC_CPU ); } else if( ( address & m_bad_word_address_mask ) != 0 ) { store_bad_address( address ); } else { uint32_t data = 0; switch( cop ) { case 0: { int address; if( m_delayr == PSXCPU_DELAYR_PC ) { switch( m_delayv & 0x0c ) { case 0x0c: address = m_delayv; break; default: address = m_delayv + 4; break; } } else { switch( m_pc & 0x0c ) { case 0x0: case 0xc: address = m_pc + 0x08; break; default: address = m_pc | 0x0c; break; } } data = m_program->read_dword( address ); } break; case 1: data = getcp1dr( INS_RT( m_op ) ); break; case 2: data = m_gte.getcp2dr( m_pc, INS_RT( m_op ) ); break; case 3: data = getcp3dr( INS_RT( m_op ) ); break; } writeword( address, data ); if( breakpoint ) { breakpoint_exception(); } else if( m_berr ) { store_bus_error_exception(); } else { advance_pc(); } } } void psxcpu_device::bc( int cop, int sr_cu, int condition ) { if( ( m_cp0r[ CP0_SR ] & sr_cu ) == 0 ) { exception( EXC_CPU ); } else { conditional_branch( !condition ); } } /*************************************************************************** CORE EXECUTION LOOP ***************************************************************************/ void psxcpu_device::execute_set_input( int inputnum, int state ) { uint32_t ip; switch( inputnum ) { case PSXCPU_IRQ0: ip = CAUSE_IP2; break; case PSXCPU_IRQ1: ip = CAUSE_IP3; break; case PSXCPU_IRQ2: ip = CAUSE_IP4; break; case PSXCPU_IRQ3: ip = CAUSE_IP5; break; case PSXCPU_IRQ4: ip = CAUSE_IP6; break; case PSXCPU_IRQ5: ip = CAUSE_IP7; break; default: return; } switch( state ) { case CLEAR_LINE: m_cp0r[ CP0_CAUSE ] &= ~ip; break; case ASSERT_LINE: m_cp0r[ CP0_CAUSE ] |= ip; break; } update_cop0( CP0_CAUSE ); } void psxcpu_device::execute_run() { do { if( LOG_BIOSCALL ) log_bioscall(); debugger_instruction_hook( m_pc ); int breakpoint = program_counter_breakpoint(); if( ( m_pc & m_bad_word_address_mask ) != 0 ) { load_bad_address( m_pc ); } else if( breakpoint ) { breakpoint_exception(); } else { m_op = m_instruction.read_dword(m_pc); if( m_berr ) { fetch_bus_error_exception(); } else { switch( INS_OP( m_op ) ) { case OP_SPECIAL: switch( INS_FUNCT( m_op ) ) { case FUNCT_SLL: load( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] << INS_SHAMT( m_op ) ); break; case FUNCT_SRL: load( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] >> INS_SHAMT( m_op ) ); break; case FUNCT_SRA: load( INS_RD( m_op ), (int32_t)m_r[ INS_RT( m_op ) ] >> INS_SHAMT( m_op ) ); break; case FUNCT_SLLV: load( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] << ( m_r[ INS_RS( m_op ) ] & 31 ) ); break; case FUNCT_SRLV: load( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] >> ( m_r[ INS_RS( m_op ) ] & 31 ) ); break; case FUNCT_SRAV: load( INS_RD( m_op ), (int32_t)m_r[ INS_RT( m_op ) ] >> ( m_r[ INS_RS( m_op ) ] & 31 ) ); break; case FUNCT_JR: branch( m_r[ INS_RS( m_op ) ] ); break; case FUNCT_JALR: branch( m_r[ INS_RS( m_op ) ] ); if( INS_RD( m_op ) != 0 ) { m_r[ INS_RD( m_op ) ] = m_pc + 4; } break; case FUNCT_SYSCALL: if( LOG_BIOSCALL ) log_syscall(); exception( EXC_SYS ); break; case FUNCT_BREAK: exception( EXC_BP ); break; case FUNCT_MFHI: load( INS_RD( m_op ), get_hi() ); break; case FUNCT_MTHI: funct_mthi(); advance_pc(); break; case FUNCT_MFLO: load( INS_RD( m_op ), get_lo() ); break; case FUNCT_MTLO: funct_mtlo(); advance_pc(); break; case FUNCT_MULT: funct_mult(); advance_pc(); break; case FUNCT_MULTU: funct_multu(); advance_pc(); break; case FUNCT_DIV: funct_div(); advance_pc(); break; case FUNCT_DIVU: funct_divu(); advance_pc(); break; case FUNCT_ADD: { uint32_t result = m_r[ INS_RS( m_op ) ] + m_r[ INS_RT( m_op ) ]; if( (int32_t)( ~( m_r[ INS_RS( m_op ) ] ^ m_r[ INS_RT( m_op ) ] ) & ( m_r[ INS_RS( m_op ) ] ^ result ) ) < 0 ) { exception( EXC_OVF ); } else { load( INS_RD( m_op ), result ); } } break; case FUNCT_ADDU: load( INS_RD( m_op ), m_r[ INS_RS( m_op ) ] + m_r[ INS_RT( m_op ) ] ); break; case FUNCT_SUB: { uint32_t result = m_r[ INS_RS( m_op ) ] - m_r[ INS_RT( m_op ) ]; if( (int32_t)( ( m_r[ INS_RS( m_op ) ] ^ m_r[ INS_RT( m_op ) ] ) & ( m_r[ INS_RS( m_op ) ] ^ result ) ) < 0 ) { exception( EXC_OVF ); } else { load( INS_RD( m_op ), result ); } } break; case FUNCT_SUBU: load( INS_RD( m_op ), m_r[ INS_RS( m_op ) ] - m_r[ INS_RT( m_op ) ] ); break; case FUNCT_AND: load( INS_RD( m_op ), m_r[ INS_RS( m_op ) ] & m_r[ INS_RT( m_op ) ] ); break; case FUNCT_OR: load( INS_RD( m_op ), m_r[ INS_RS( m_op ) ] | m_r[ INS_RT( m_op ) ] ); break; case FUNCT_XOR: load( INS_RD( m_op ), m_r[ INS_RS( m_op ) ] ^ m_r[ INS_RT( m_op ) ] ); break; case FUNCT_NOR: load( INS_RD( m_op ), ~( m_r[ INS_RS( m_op ) ] | m_r[ INS_RT( m_op ) ] ) ); break; case FUNCT_SLT: load( INS_RD( m_op ), (int32_t)m_r[ INS_RS( m_op ) ] < (int32_t)m_r[ INS_RT( m_op ) ] ); break; case FUNCT_SLTU: load( INS_RD( m_op ), m_r[ INS_RS( m_op ) ] < m_r[ INS_RT( m_op ) ] ); break; default: exception( EXC_RI ); break; } break; case OP_REGIMM: switch( INS_RT_REGIMM( m_op ) ) { case RT_BLTZ: conditional_branch( (int32_t)m_r[ INS_RS( m_op ) ] < 0 ); if( INS_RT( m_op ) == RT_BLTZAL ) { m_r[ 31 ] = m_pc + 4; } break; case RT_BGEZ: conditional_branch( (int32_t)m_r[ INS_RS( m_op ) ] >= 0 ); if( INS_RT( m_op ) == RT_BGEZAL ) { m_r[ 31 ] = m_pc + 4; } break; } break; case OP_J: unconditional_branch(); break; case OP_JAL: unconditional_branch(); m_r[ 31 ] = m_pc + 4; break; case OP_BEQ: conditional_branch( m_r[ INS_RS( m_op ) ] == m_r[ INS_RT( m_op ) ] ); break; case OP_BNE: conditional_branch( m_r[ INS_RS( m_op ) ] != m_r[ INS_RT( m_op ) ] ); break; case OP_BLEZ: conditional_branch( (int32_t)m_r[ INS_RS( m_op ) ] < 0 || m_r[ INS_RS( m_op ) ] == m_r[ INS_RT( m_op ) ] ); break; case OP_BGTZ: conditional_branch( (int32_t)m_r[ INS_RS( m_op ) ] >= 0 && m_r[ INS_RS( m_op ) ] != m_r[ INS_RT( m_op ) ] ); break; case OP_ADDI: { uint32_t immediate = PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); uint32_t result = m_r[ INS_RS( m_op ) ] + immediate; if( (int32_t)( ~( m_r[ INS_RS( m_op ) ] ^ immediate ) & ( m_r[ INS_RS( m_op ) ] ^ result ) ) < 0 ) { exception( EXC_OVF ); } else { load( INS_RT( m_op ), result ); } } break; case OP_ADDIU: load( INS_RT( m_op ), m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ) ); break; case OP_SLTI: load( INS_RT( m_op ), (int32_t)m_r[ INS_RS( m_op ) ] < PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ) ); break; case OP_SLTIU: load( INS_RT( m_op ), m_r[ INS_RS( m_op ) ] < (uint32_t)PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ) ); break; case OP_ANDI: load( INS_RT( m_op ), m_r[ INS_RS( m_op ) ] & INS_IMMEDIATE( m_op ) ); break; case OP_ORI: load( INS_RT( m_op ), m_r[ INS_RS( m_op ) ] | INS_IMMEDIATE( m_op ) ); break; case OP_XORI: load( INS_RT( m_op ), m_r[ INS_RS( m_op ) ] ^ INS_IMMEDIATE( m_op ) ); break; case OP_LUI: load( INS_RT( m_op ), INS_IMMEDIATE( m_op ) << 16 ); break; case OP_COP0: switch( INS_RS( m_op ) ) { case RS_MFC: { int reg = INS_RD( m_op ); if( reg == CP0_INDEX || reg == CP0_RANDOM || reg == CP0_ENTRYLO || reg == CP0_CONTEXT || reg == CP0_ENTRYHI ) { exception( EXC_RI ); } else if( reg < 16 ) { if( cop0_usable() ) { delayed_load( INS_RT( m_op ), m_cp0r[ reg ] ); } } else { advance_pc(); } } break; case RS_CFC: exception( EXC_RI ); break; case RS_MTC: { int reg = INS_RD( m_op ); if( reg == CP0_INDEX || reg == CP0_RANDOM || reg == CP0_ENTRYLO || reg == CP0_CONTEXT || reg == CP0_ENTRYHI ) { exception( EXC_RI ); } else if( reg < 16 ) { if( cop0_usable() ) { uint32_t data = ( m_cp0r[ reg ] & ~mtc0_writemask[ reg ] ) | ( m_r[ INS_RT( m_op ) ] & mtc0_writemask[ reg ] ); advance_pc(); m_cp0r[ reg ] = data; update_cop0( reg ); } } else { advance_pc(); } } break; case RS_CTC: exception( EXC_RI ); break; case RS_BC: case RS_BC_ALT: switch( INS_BC( m_op ) ) { case BC_BCF: bc( 0, SR_CU0, 0 ); break; case BC_BCT: bc( 0, SR_CU0, 1 ); break; } break; default: switch( INS_CO( m_op ) ) { case 1: switch( INS_CF( m_op ) ) { case CF_TLBR: case CF_TLBWI: case CF_TLBWR: case CF_TLBP: exception( EXC_RI ); break; case CF_RFE: if( cop0_usable() ) { advance_pc(); m_cp0r[ CP0_SR ] = ( m_cp0r[ CP0_SR ] & ~0xf ) | ( ( m_cp0r[ CP0_SR ] >> 2 ) & 0xf ); update_cop0( CP0_SR ); } break; default: advance_pc(); break; } break; default: advance_pc(); break; } break; } break; case OP_COP1: if( ( m_cp0r[ CP0_SR ] & SR_CU1 ) == 0 ) { exception( EXC_CPU ); } else { switch( INS_RS( m_op ) ) { case RS_MFC: delayed_load( INS_RT( m_op ), getcp1dr( INS_RD( m_op ) ) ); break; case RS_CFC: delayed_load( INS_RT( m_op ), getcp1cr( INS_RD( m_op ) ) ); break; case RS_MTC: setcp1dr( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] ); advance_pc(); break; case RS_CTC: setcp1cr( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] ); advance_pc(); break; case RS_BC: case RS_BC_ALT: switch( INS_BC( m_op ) ) { case BC_BCF: bc( 1, SR_CU1, 0 ); break; case BC_BCT: bc( 1, SR_CU1, 1 ); break; } break; default: advance_pc(); break; } } break; case OP_COP2: if( ( m_cp0r[ CP0_SR ] & SR_CU2 ) == 0 ) { exception( EXC_CPU ); } else { switch( INS_RS( m_op ) ) { case RS_MFC: delayed_load( INS_RT( m_op ), m_gte.getcp2dr( m_pc, INS_RD( m_op ) ) ); break; case RS_CFC: delayed_load( INS_RT( m_op ), m_gte.getcp2cr( m_pc, INS_RD( m_op ) ) ); break; case RS_MTC: m_gte.setcp2dr( m_pc, INS_RD( m_op ), m_r[ INS_RT( m_op ) ] ); advance_pc(); break; case RS_CTC: m_gte.setcp2cr( m_pc, INS_RD( m_op ), m_r[ INS_RT( m_op ) ] ); advance_pc(); break; case RS_BC: case RS_BC_ALT: switch( INS_BC( m_op ) ) { case BC_BCF: bc( 2, SR_CU2, 0 ); break; case BC_BCT: bc( 2, SR_CU2, 1 ); break; } break; default: switch( INS_CO( m_op ) ) { case 1: if( !m_gte.docop2( m_pc, INS_COFUN( m_op ) ) ) { stop(); } advance_pc(); break; default: advance_pc(); break; } break; } } break; case OP_COP3: if( ( m_cp0r[ CP0_SR ] & SR_CU3 ) == 0 ) { exception( EXC_CPU ); } else { switch( INS_RS( m_op ) ) { case RS_MFC: delayed_load( INS_RT( m_op ), getcp3dr( INS_RD( m_op ) ) ); break; case RS_CFC: delayed_load( INS_RT( m_op ), getcp3cr( INS_RD( m_op ) ) ); break; case RS_MTC: setcp3dr( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] ); advance_pc(); break; case RS_CTC: setcp3cr( INS_RD( m_op ), m_r[ INS_RT( m_op ) ] ); advance_pc(); break; case RS_BC: case RS_BC_ALT: switch( INS_BC( m_op ) ) { case BC_BCF: bc( 3, SR_CU3, 0 ); break; case BC_BCT: bc( 3, SR_CU3, 1 ); break; } break; default: advance_pc(); break; } } break; case OP_LB: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = PSXCPU_BYTE_EXTEND( readbyte( address ) ); if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_LH: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_half_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = PSXCPU_WORD_EXTEND( readhalf( address ) ); if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_LWL: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int load_type = address & 3; int breakpoint; address &= ~3; breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = get_register_from_pipeline( INS_RT( m_op ) ); switch( load_type ) { case 0: data = ( data & 0x00ffffff ) | ( readword_masked( address, 0x000000ff ) << 24 ); break; case 1: data = ( data & 0x0000ffff ) | ( readword_masked( address, 0x0000ffff ) << 16 ); break; case 2: data = ( data & 0x000000ff ) | ( readword_masked( address, 0x00ffffff ) << 8 ); break; case 3: data = readword( address ); break; } if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_LW: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_word_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = readword( address ); if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_LBU: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = readbyte( address ); if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_LHU: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_half_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = readhalf( address ); if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_LWR: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = load_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { load_bad_address( address ); } else if( breakpoint ) { breakpoint_exception(); } else { uint32_t data = get_register_from_pipeline( INS_RT( m_op ) ); switch( address & 3 ) { case 0: data = readword( address ); break; case 1: data = ( data & 0xff000000 ) | ( readword_masked( address, 0xffffff00 ) >> 8 ); break; case 2: data = ( data & 0xffff0000 ) | ( readword_masked( address, 0xffff0000 ) >> 16 ); break; case 3: data = ( data & 0xffffff00 ) | ( readword_masked( address, 0xff000000 ) >> 24 ); break; } if( m_berr ) { load_bus_error_exception(); } else { delayed_load( INS_RT( m_op ), data ); } } } break; case OP_SB: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = store_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { store_bad_address( address ); } else { int shift = 8 * ( address & 3 ); writeword_masked( address, m_r[ INS_RT( m_op ) ] << shift, 0xff << shift ); if( breakpoint ) { breakpoint_exception(); } else if( m_berr ) { store_bus_error_exception(); } else { advance_pc(); } } } break; case OP_SH: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = store_data_address_breakpoint( address ); if( ( address & m_bad_half_address_mask ) != 0 ) { store_bad_address( address ); } else { int shift = 8 * ( address & 2 ); writeword_masked( address, m_r[ INS_RT( m_op ) ] << shift, 0xffff << shift ); if( breakpoint ) { breakpoint_exception(); } else if( m_berr ) { store_bus_error_exception(); } else { advance_pc(); } } } break; case OP_SWL: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int save_type = address & 3; int breakpoint; address &= ~3; breakpoint = store_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { store_bad_address( address ); } else { switch( save_type ) { case 0: writeword_masked( address, m_r[ INS_RT( m_op ) ] >> 24, 0x000000ff ); break; case 1: writeword_masked( address, m_r[ INS_RT( m_op ) ] >> 16, 0x0000ffff ); break; case 2: writeword_masked( address, m_r[ INS_RT( m_op ) ] >> 8, 0x00ffffff ); break; case 3: writeword( address, m_r[ INS_RT( m_op ) ] ); break; } if( breakpoint ) { breakpoint_exception(); } else if( m_berr ) { store_bus_error_exception(); } else { advance_pc(); } } } break; case OP_SW: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = store_data_address_breakpoint( address ); if( ( address & m_bad_word_address_mask ) != 0 ) { store_bad_address( address ); } else { writeword( address, m_r[ INS_RT( m_op ) ] ); if( breakpoint ) { breakpoint_exception(); } else if( m_berr ) { store_bus_error_exception(); } else { advance_pc(); } } } break; case OP_SWR: { uint32_t address = m_r[ INS_RS( m_op ) ] + PSXCPU_WORD_EXTEND( INS_IMMEDIATE( m_op ) ); int breakpoint = store_data_address_breakpoint( address ); if( ( address & m_bad_byte_address_mask ) != 0 ) { store_bad_address( address ); } else { switch( address & 3 ) { case 0: writeword( address, m_r[ INS_RT( m_op ) ] ); break; case 1: writeword_masked( address, m_r[ INS_RT( m_op ) ] << 8, 0xffffff00 ); break; case 2: writeword_masked( address, m_r[ INS_RT( m_op ) ] << 16, 0xffff0000 ); break; case 3: writeword_masked( address, m_r[ INS_RT( m_op ) ] << 24, 0xff000000 ); break; } if( breakpoint ) { breakpoint_exception(); } else if( m_berr ) { store_bus_error_exception(); } else { advance_pc(); } } } break; case OP_LWC0: lwc( 0, SR_CU0 ); break; case OP_LWC1: lwc( 1, SR_CU1 ); break; case OP_LWC2: lwc( 2, SR_CU2 ); break; case OP_LWC3: lwc( 3, SR_CU3 ); break; case OP_SWC0: swc( 0, SR_CU0 ); break; case OP_SWC1: swc( 1, SR_CU1 ); break; case OP_SWC2: swc( 2, SR_CU2 ); break; case OP_SWC3: swc( 3, SR_CU3 ); break; default: logerror( "%08x: unknown opcode %08x\n", m_pc, m_op ); stop(); exception( EXC_RI ); break; } } } m_icount--; } while( m_icount > 0 ); } uint32_t psxcpu_device::getcp1dr( int reg ) { /* if a mtc/ctc precedes then this will get the value moved (which cop1 register is irrelevant). */ /* if a mfc/cfc follows then it will get the same value as this one. */ return m_program->read_dword( m_pc + 4 ); } void psxcpu_device::setcp1dr( int reg, uint32_t value ) { } uint32_t psxcpu_device::getcp1cr( int reg ) { /* if a mtc/ctc precedes then this will get the value moved (which cop1 register is irrelevant). */ /* if a mfc/cfc follows then it will get the same value as this one. */ return m_program->read_dword( m_pc + 4 ); } void psxcpu_device::setcp1cr( int reg, uint32_t value ) { } uint32_t psxcpu_device::getcp3dr( int reg ) { /* if you have mtc/ctc with an mfc/cfc directly afterwards then you get the value that was moved. */ /* if you have an lwc with an mfc/cfc somewhere after it then you get the value that is loaded */ /* otherwise you get the next opcode. which register you transfer to or from is irrelevant. */ return m_program->read_dword( m_pc + 4 ); } void psxcpu_device::setcp3dr( int reg, uint32_t value ) { } uint32_t psxcpu_device::getcp3cr( int reg ) { /* if you have mtc/ctc with an mfc/cfc directly afterwards then you get the value that was moved. */ /* if you have an lwc with an mfc/cfc somewhere after it then you get the value that is loaded */ /* otherwise you get the next opcode. which register you transfer to or from is irrelevant. */ return m_program->read_dword( m_pc + 4 ); } void psxcpu_device::setcp3cr( int reg, uint32_t value ) { } uint32_t psxcpu_device::gpu_r(offs_t offset, uint32_t mem_mask) { return m_gpu_read_handler( offset, mem_mask ); } void psxcpu_device::gpu_w(offs_t offset, uint32_t data, uint32_t mem_mask) { m_gpu_write_handler( offset, data, mem_mask ); } uint16_t psxcpu_device::spu_r(offs_t offset, uint16_t mem_mask) { return m_spu_read_handler( offset, mem_mask ); } void psxcpu_device::spu_w(offs_t offset, uint16_t data, uint16_t mem_mask) { m_spu_write_handler( offset, data, mem_mask ); } uint8_t psxcpu_device::cd_r(offs_t offset, uint8_t mem_mask) { return m_cd_read_handler( offset, mem_mask ); } void psxcpu_device::cd_w(offs_t offset, uint8_t data, uint8_t mem_mask) { m_cd_write_handler( offset, data, mem_mask ); } void psxcpu_device::set_disable_rom_berr(bool mode) { m_disable_rom_berr = mode; } device_memory_interface::space_config_vector psxcpu_device::memory_space_config() const { return space_config_vector { std::make_pair(AS_PROGRAM, &m_program_config), }; } //------------------------------------------------- // device_add_mconfig - add device configuration //------------------------------------------------- void psxcpu_device::device_add_mconfig(machine_config &config) { auto &irq(PSX_IRQ(config, "irq", 0)); irq.irq().set_inputline(DEVICE_SELF, PSXCPU_IRQ0); auto &dma(PSX_DMA(config, "dma", 0)); dma.irq().set("irq", FUNC(psxirq_device::intin3)); auto &mdec(PSX_MDEC(config, "mdec", 0)); dma.install_write_handler(0, psxdma_device::write_delegate(&psxmdec_device::dma_write, &mdec)); dma.install_read_handler(1, psxdma_device::write_delegate(&psxmdec_device::dma_read, &mdec)); auto &rcnt(PSX_RCNT(config, "rcnt", 0)); rcnt.irq0().set("irq", FUNC(psxirq_device::intin4)); rcnt.irq1().set("irq", FUNC(psxirq_device::intin5)); rcnt.irq2().set("irq", FUNC(psxirq_device::intin6)); auto &sio0(PSX_SIO0(config, "sio0", DERIVED_CLOCK(1, 2))); sio0.irq_handler().set("irq", FUNC(psxirq_device::intin7)); auto &sio1(PSX_SIO1(config, "sio1", DERIVED_CLOCK(1, 2))); sio1.irq_handler().set("irq", FUNC(psxirq_device::intin8)); RAM(config, "ram").set_default_value(0x00); }
25.115683
192
0.596537
c608cce4c238e6b9b1c059a24f1b4f4763f80c95
2,751
asm
Assembly
Code/VidTestROM/ver2/main.asm
QuinnPainter/6502Computer
2dfd19499bb230caf7a6afb460a54b007692f764
[ "Unlicense" ]
null
null
null
Code/VidTestROM/ver2/main.asm
QuinnPainter/6502Computer
2dfd19499bb230caf7a6afb460a54b007692f764
[ "Unlicense" ]
null
null
null
Code/VidTestROM/ver2/main.asm
QuinnPainter/6502Computer
2dfd19499bb230caf7a6afb460a54b007692f764
[ "Unlicense" ]
null
null
null
VIA1_RB = $9000 ; VIA used for the graphics and keyboard systems. VIA1_RA = $9001 ; RB = GFX Data, RA = keyboard data. VIA1_DDRB = $9002 ; Data Direction Register - 1 = output, 0 = input VIA1_DDRA = $9003 VIA1_T1CL = $9004 VIA1_T1CH = $9005 VIA1_T1LL = $9006 VIA1_T1LH = $9007 VIA1_T2CL = $9008 VIA1_T2CH = $9009 VIA1_SR = $900A VIA1_ACR = $900B VIA1_PCR = $900C VIA1_IFR = $900D VIA1_IER = $900E VIA1_RA2 = $900F .org $C000 reset: ldx #$FF ; Initialize stack pointer txs sei ; disable IRQ cld ; disable decimal mode lda #%11111111 sta VIA1_DDRB ; DDRB (graphics bus) all outputs lda #%10001100 sta VIA1_PCR ; setup graphics handshake lda #%01111111 sta VIA1_IER ; disable all via interrupts ;lda #%10010000 ;sta VIA1_IER ; Enable graphics ready interrupt ldy #$FF ; wait for graphics card to start up jsr delay ;cli ; now that the VIA IRQs are set up, we can enable IRQ lda #0 sta VIA1_RB ; clear the screen (multiple times in case there's a gfx command in progress) sta VIA1_RB ; clear the screen (multiple times in case there's a gfx command in progress) sta VIA1_RB ; clear the screen (multiple times in case there's a gfx command in progress) sta VIA1_RB ; clear the screen (multiple times in case there's a gfx command in progress) lda #'F' sta $500 infloop: lda #1 sta VIA1_RB ldy #$FF jsr delay ;.lp2: ; ldx #$FF ;.lp1: ; lda $00 ; 3 cycles (doesn't do anything, just needed a 3 cycle instruction ; dex ; 2 cycles ; bne .lp1 ; 3 or 4 cycles if on page boundary ; dey ; So, if it's 8 cycles, at 2MHz this loop will take 1020 microseconds ; bne .lp2 lda $500 ina bne .n lda #32 .n: sta VIA1_RB sta $500 ldy #$FF jsr delay ;.blp2: ; ldx #$FF ;.blp1: ; lda $00 ; 3 cycles (doesn't do anything, just needed a 3 cycle instruction ; dex ; 2 cycles ; bne .blp1 ; 3 or 4 cycles if on page boundary ; dey ; So, if it's 8 cycles, at 2MHz this loop will take 1020 microseconds ; bne .blp2 bra infloop ; Delay for a while ; Inputs: Y - Number of times to wait approx 1 millisecond (1020 microseconds) ; Outputs: X - Garbage delay: pha .lp2: ldx #$FF .lp1: lda $00 ; 3 cycles (doesn't do anything, just needed a 3 cycle instruction dex ; 2 cycles bne .lp1 ; 3 or 4 cycles if on page boundary dey ; So, if it's 8 cycles, at 2MHz this loop will take 1020 microseconds bne .lp2 pla rts nmi: rti irq: rti .org $FFFA .word nmi ; NMI vector .word reset ; Reset vector .word irq ; IRQ vector
25.009091
93
0.622683
da7237086149a266fc41bb6c37f51c5b50fd9cc9
2,372
php
PHP
framework/tests/forms/OptionsetFieldTest.php
lastgrade/limecoke
88a37a5c4ee328cd1135ae571536cf50538c35c3
[ "Unlicense" ]
null
null
null
framework/tests/forms/OptionsetFieldTest.php
lastgrade/limecoke
88a37a5c4ee328cd1135ae571536cf50538c35c3
[ "Unlicense" ]
16
2017-09-23T06:29:35.000Z
2017-12-04T23:49:25.000Z
framework/tests/forms/OptionsetFieldTest.php
lastgrade/limecoke
88a37a5c4ee328cd1135ae571536cf50538c35c3
[ "Unlicense" ]
1
2017-02-13T16:51:32.000Z
2017-02-13T16:51:32.000Z
<?php /** * @package framework * @subpackage tests */ class OptionsetFieldTest extends SapphireTest { public function testSetDisabledItems() { $f = new OptionsetField( 'Test', false, array(0 => 'Zero', 1 => 'One') ); $f->setDisabledItems(array(0)); $p = new CSSContentParser($f->Field()); $item0 = $p->getBySelector('#Test_0'); $item1 = $p->getBySelector('#Test_1'); $this->assertEquals( (string)$item0[0]['disabled'], 'disabled' ); $this->assertEquals( (string)$item1[0]['disabled'], '' ); } public function testValidation() { $field = OptionsetField::create('Test', 'Testing', array( "One" => "One", "Two" => "Two", "Five" => "Five" )); $validator = new RequiredFields('Test'); $form = new Form($this, 'Form', new FieldList($field), new FieldList(), $validator); $field->setValue("One"); $this->assertTrue($field->validate($validator)); //non-existent value should make the field invalid $field->setValue("Three"); $this->assertFalse($field->validate($validator)); //empty string should pass field-level validation... $field->setValue(''); $this->assertTrue($field->validate($validator)); // ... but should not pass "RequiredFields" validation $this->assertFalse($form->validate()); //disabled items shouldn't validate $field->setDisabledItems(array('Five')); $field->setValue('Five'); $this->assertFalse($field->validate($validator)); } public function testReadonlyField() { $sourceArray = array(0 => 'No', 1 => 'Yes'); $field = new OptionsetField('FeelingOk', 'are you feeling ok?', $sourceArray, 1); $field->setEmptyString('(Select one)'); $field->setValue(1); $readonlyField = $field->performReadonlyTransformation(); preg_match('/Yes/', $field->Field(), $matches); $this->assertEquals($matches[0], 'Yes'); } public function testSafelyCast() { $field1 = new OptionsetField('Options', 'Options', array( 1 => 'One', 2 => 'Two & Three', 3 => DBField::create_field('HTMLText', 'Four &amp; Five &amp; Six') )); $fieldHTML = (string)$field1->Field(); $this->assertContains('One', $fieldHTML); $this->assertContains('Two &amp; Three', $fieldHTML); $this->assertNotContains('Two & Three', $fieldHTML); $this->assertContains('Four &amp; Five &amp; Six', $fieldHTML); $this->assertNotContains('Four & Five & Six', $fieldHTML); } }
29.283951
86
0.643761
46c3e7cfbe3c943fa8b742503c1b82358f794b5d
6,439
py
Python
susi/SOMPlots.py
felixriese/susi
fa405e683eda30850900c14d214e732862ef4180
[ "BSD-3-Clause" ]
72
2019-03-27T12:48:27.000Z
2022-03-13T09:40:14.000Z
susi/SOMPlots.py
felixriese/susi
fa405e683eda30850900c14d214e732862ef4180
[ "BSD-3-Clause" ]
18
2019-03-29T12:10:20.000Z
2022-03-06T16:59:26.000Z
susi/SOMPlots.py
felixriese/susi
fa405e683eda30850900c14d214e732862ef4180
[ "BSD-3-Clause" ]
23
2019-03-26T20:56:23.000Z
2022-03-08T05:44:13.000Z
"""SOMPlots functions. Copyright (c) 2019-2021 Felix M. Riese. All rights reserved. """ from typing import List, Tuple import matplotlib.pyplot as plt import matplotlib import numpy as np def plot_estimation_map( estimation_map: np.ndarray, cbar_label: str = "Variable in unit", cmap: str = "viridis", fontsize: int = 20, ) -> plt.Axes: """Plot estimation map. Parameters ---------- estimation_map : np.ndarray Estimation map of the size (n_rows, n_columns) cbar_label : str, optional Label of the colorbar, by default "Variable in unit" cmap : str, optional (default="viridis") Colormap fontsize : int, optional (default=20) Fontsize of the labels Returns ------- ax : pyplot.axis Plot axis """ _, ax = plt.subplots(1, 1, figsize=(7, 5)) img = ax.imshow(estimation_map, cmap=cmap) ax.set_xlabel("SOM columns", fontsize=fontsize) ax.set_ylabel("SOM rows", fontsize=fontsize) # ax.set_xticklabels(fontsize=fontsize) # ax.set_yticklabels(fontsize=fontsize) ax.tick_params(axis="both", which="major", labelsize=fontsize) # colorbar cbar = plt.colorbar(img, ax=ax) cbar.ax.tick_params(labelsize=fontsize) cbar.ax.set_ylabel(cbar_label, fontsize=fontsize, labelpad=10) for label in cbar.ax.xaxis.get_ticklabels()[::2]: label.set_visible(False) plt.grid(b=False) return ax def plot_som_histogram( bmu_list: List[Tuple[int, int]], n_rows: int, n_columns: int, n_datapoints_cbar: int = 5, fontsize: int = 22, ) -> plt.Axes: """Plot 2D Histogram of SOM. Plot 2D Histogram with one bin for each SOM node. The content of one bin is the number of datapoints matched to the specific node. Parameters ---------- bmu_list : list of (int, int) tuples Position of best matching units (row, column) for each datapoint n_rows : int Number of rows for the SOM grid n_columns : int Number of columns for the SOM grid n_datapoints_cbar : int, optional (default=5) Maximum number of datapoints shown on the colorbar fontsize : int, optional (default=22) Fontsize of the labels Returns ------- ax : pyplot.axis Plot axis """ fig, ax = plt.subplots(1, 1, figsize=(6, 6)) # colormap cmap = plt.cm.viridis cmaplist = [cmap(i) for i in range(cmap.N)] cmap = matplotlib.colors.LinearSegmentedColormap.from_list( "mcm", cmaplist, cmap.N ) bounds = np.arange(0.0, n_datapoints_cbar + 1, 1.0) norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N) ax2 = fig.add_axes([0.96, 0.12, 0.03, 0.76]) cbar = matplotlib.colorbar.ColorbarBase( ax2, cmap=cmap, norm=norm, spacing="proportional", ticks=bounds, boundaries=bounds, format="%1i", extend="max", ) cbar.ax.set_ylabel("Number of datapoints", fontsize=fontsize) cbar.ax.tick_params(labelsize=fontsize) ax.hist2d( [x[0] for x in bmu_list], [x[1] for x in bmu_list], bins=[n_rows, n_columns], cmin=1, cmap=cmap, norm=norm, ) for label in cbar.ax.xaxis.get_ticklabels()[::2]: label.set_visible(False) ax.set_xlabel("SOM columns", fontsize=fontsize) ax.set_ylabel("SOM rows", fontsize=fontsize) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(fontsize) # to be compatible with plt.imshow: ax.invert_yaxis() plt.grid(b=False) return ax def plot_umatrix( u_matrix: np.ndarray, n_rows: int, n_colums: int, cmap: str = "Greys", fontsize: int = 18, ) -> plt.Axes: """Plot u-matrix. Parameters ---------- u_matrix : np.ndarray U-matrix containing the distances between all nodes of the unsupervised SOM. Shape = (n_rows*2-1, n_columns*2-1) n_rows : int Number of rows for the SOM grid n_columns : int Number of columns for the SOM grid cmap : str, optional (default="Greys) Colormap fontsize : int, optional (default=18) Fontsize of the labels Returns ------- ax : pyplot.axis Plot axis """ _, ax = plt.subplots(figsize=(6, 6)) img = ax.imshow(u_matrix.squeeze(), cmap=cmap) ax.set_xticks(np.arange(0, n_colums * 2 + 1, 20)) ax.set_xticklabels(np.arange(0, n_colums + 1, 10)) ax.set_yticks(np.arange(0, n_rows * 2 + 1, 20)) ax.set_yticklabels(np.arange(0, n_rows + 1, 10)) # ticks and labels for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(fontsize) ax.set_ylabel("SOM rows", fontsize=fontsize) ax.set_xlabel("SOM columns", fontsize=fontsize) # colorbar cbar = plt.colorbar(img, ax=ax, fraction=0.04, pad=0.04) cbar.ax.set_ylabel( "Distance measure (a.u.)", rotation=90, fontsize=fontsize, labelpad=20 ) cbar.ax.tick_params(labelsize=fontsize) return ax def plot_nbh_dist_weight_matrix(som, it_frac: float = 0.1) -> plt.Axes: """Plot neighborhood distance weight matrix in 3D. Parameters ---------- som : susi.SOMClustering or related Trained (un)supervised SOM it_frac : float, optional (default=0.1) Fraction of `som.n_iter_unsupervised` for the plot state. Returns ------- ax : pyplot.axis Plot axis """ nbh_func = som._calc_neighborhood_func( curr_it=som.n_iter_unsupervised * it_frac, mode=som.neighborhood_mode_unsupervised, ) dist_weight_matrix = som._get_nbh_distance_weight_matrix( neighborhood_func=nbh_func, bmu_pos=[som.n_rows // 2, som.n_columns // 2], ) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection="3d") x = np.arange(som.n_rows) y = np.arange(som.n_columns) X, Y = np.meshgrid(x, y) Z = dist_weight_matrix.reshape(som.n_rows, som.n_columns) surf = ax.plot_surface( X, Y, Z, cmap=matplotlib.cm.coolwarm, antialiased=False, rstride=1, cstride=1, linewidth=0, ) fig.colorbar(surf, shrink=0.5, aspect=10) return ax
26.497942
78
0.628048
20fb524f584f166fc7272f8cbe7ea79799bcc240
12,279
cs
C#
WWCP_OCPPv1.6/DataTypes/Simple/Reservation_Id.cs
OpenChargingCloud/WWCP_
ff040e0b9b228e6eae98de81d0589e760c13e55e
[ "Apache-2.0" ]
null
null
null
WWCP_OCPPv1.6/DataTypes/Simple/Reservation_Id.cs
OpenChargingCloud/WWCP_
ff040e0b9b228e6eae98de81d0589e760c13e55e
[ "Apache-2.0" ]
null
null
null
WWCP_OCPPv1.6/DataTypes/Simple/Reservation_Id.cs
OpenChargingCloud/WWCP_
ff040e0b9b228e6eae98de81d0589e760c13e55e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2021 GraphDefined GmbH * This file is part of WWCP OCPP <https://github.com/OpenChargingCloud/WWCP_OCPP> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Usings using System; using org.GraphDefined.Vanaheimr.Illias; #endregion namespace cloud.charging.open.protocols.OCPPv1_6 { /// <summary> /// A reservation identification. /// </summary> public readonly struct Reservation_Id : IId, IEquatable<Reservation_Id>, IComparable<Reservation_Id> { #region Data /// <summary> /// The nummeric value of the reservation identification. /// </summary> public readonly UInt64 Value; private static readonly Random random = new Random(); #endregion #region Properties /// <summary> /// Indicates whether this identification is null or empty. /// </summary> public Boolean IsNullOrEmpty => false; /// <summary> /// The length of this identification. /// </summary> public UInt64 Length => (UInt64) Value.ToString().Length; #endregion #region Constructor(s) /// <summary> /// Create a new reservation identification. /// </summary> /// <param name="Token">An integer.</param> private Reservation_Id(UInt64 Token) { this.Value = Token; } #endregion #region (static) Random /// <summary> /// Create a new random reservation identification. /// </summary> public static Reservation_Id Random => new Reservation_Id((UInt64) random.Next()); #endregion #region (static) Parse (Text) /// <summary> /// Parse the given string as a reservation identification. /// </summary> /// <param name="Text">A text representation of a reservation identification.</param> public static Reservation_Id Parse(String Text) { #region Initial checks if (Text != null) Text = Text.Trim(); if (Text.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Text), "The given text representation of a reservation identification must not be null or empty!"); #endregion if (TryParse(Text, out Reservation_Id reservationId)) return reservationId; throw new ArgumentNullException(nameof(Text), "The given text representation of a reservation identification is invalid!"); } #endregion #region (static) Parse (Integer) /// <summary> /// Parse the given number as a reservation identification. /// </summary> public static Reservation_Id Parse(UInt64 Integer) => new Reservation_Id(Integer); #endregion #region (static) TryParse(Text) /// <summary> /// Try to parse the given string as a reservation identification. /// </summary> /// <param name="Text">A text representation of a reservation identification.</param> public static Reservation_Id? TryParse(String Text) { if (TryParse(Text, out Reservation_Id reservationId)) return reservationId; return null; } #endregion #region (static) TryParse(Number) /// <summary> /// Try to parse the given number as a reservation identification. /// </summary> /// <param name="Number">A numeric representation of a reservation identification.</param> public static Reservation_Id? TryParse(UInt64 Number) { if (TryParse(Number, out Reservation_Id reservationId)) return reservationId; return null; } #endregion #region (static) TryParse(Text, out ReservationId) /// <summary> /// Try to parse the given string as a reservation identification. /// </summary> /// <param name="Text">A text representation of a reservation identification.</param> /// <param name="ReservationId">The parsed reservation identification.</param> public static Boolean TryParse(String Text, out Reservation_Id ReservationId) { #region Initial checks Text = Text?.Trim(); if (Text.IsNullOrEmpty()) { ReservationId = default; return false; } #endregion if (UInt64.TryParse(Text, out UInt64 number)) { ReservationId = new Reservation_Id(number); return true; } ReservationId = default; return false; } #endregion #region (static) TryParse(Number, out ReservationId) /// <summary> /// Try to parse the given number as a reservation identification. /// </summary> /// <param name="Number">A numeric representation of a reservation identification.</param> /// <param name="ReservationId">The parsed reservation identification.</param> public static Boolean TryParse(UInt64 Number, out Reservation_Id ReservationId) { ReservationId = new Reservation_Id(Number); return true; } #endregion #region Clone /// <summary> /// Clone this reservation identification. /// </summary> public Reservation_Id Clone => new Reservation_Id(Value); #endregion #region Operator overloading #region Operator == (ReservationId1, ReservationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId1">A reservation identification.</param> /// <param name="ReservationId2">Another reservation identification.</param> /// <returns>true|false</returns> public static Boolean operator == (Reservation_Id ReservationId1, Reservation_Id ReservationId2) => ReservationId1.Equals(ReservationId2); #endregion #region Operator != (ReservationId1, ReservationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId1">A reservation identification.</param> /// <param name="ReservationId2">Another reservation identification.</param> /// <returns>true|false</returns> public static Boolean operator != (Reservation_Id ReservationId1, Reservation_Id ReservationId2) => !(ReservationId1 == ReservationId2); #endregion #region Operator < (ReservationId1, ReservationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId1">A reservation identification.</param> /// <param name="ReservationId2">Another reservation identification.</param> /// <returns>true|false</returns> public static Boolean operator < (Reservation_Id ReservationId1, Reservation_Id ReservationId2) => ReservationId1.CompareTo(ReservationId2) < 0; #endregion #region Operator <= (ReservationId1, ReservationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId1">A reservation identification.</param> /// <param name="ReservationId2">Another reservation identification.</param> /// <returns>true|false</returns> public static Boolean operator <= (Reservation_Id ReservationId1, Reservation_Id ReservationId2) => !(ReservationId1 > ReservationId2); #endregion #region Operator > (ReservationId1, ReservationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId1">A reservation identification.</param> /// <param name="ReservationId2">Another reservation identification.</param> /// <returns>true|false</returns> public static Boolean operator > (Reservation_Id ReservationId1, Reservation_Id ReservationId2) => ReservationId1.CompareTo(ReservationId2) > 0; #endregion #region Operator >= (ReservationId1, ReservationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId1">A reservation identification.</param> /// <param name="ReservationId2">Another reservation identification.</param> /// <returns>true|false</returns> public static Boolean operator >= (Reservation_Id ReservationId1, Reservation_Id ReservationId2) => !(ReservationId1 < ReservationId2); #endregion #endregion #region IComparable<ReservationId> Members #region CompareTo(Object) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="Object">An object to compare with.</param> public Int32 CompareTo(Object Object) => Object is Reservation_Id reservationId ? CompareTo(reservationId) : throw new ArgumentException("The given object is not a reservation identification!", nameof(Object)); #endregion #region CompareTo(ReservationId) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="ReservationId">An object to compare with.</param> public Int32 CompareTo(Reservation_Id ReservationId) => Value.CompareTo(ReservationId.Value); #endregion #endregion #region IEquatable<ReservationId> Members #region Equals(Object) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="Object">An object to compare with.</param> /// <returns>true|false</returns> public override Boolean Equals(Object Object) => Object is Reservation_Id reservationId && Equals(reservationId); #endregion #region Equals(ReservationId) /// <summary> /// Compares two reservation identifications for equality. /// </summary> /// <param name="ReservationId">A reservation identification to compare with.</param> /// <returns>True if both match; False otherwise.</returns> public Boolean Equals(Reservation_Id ReservationId) => Value.Equals(ReservationId.Value); #endregion #endregion #region (override) GetHashCode() /// <summary> /// Return the HashCode of this object. /// </summary> /// <returns>The HashCode of this object.</returns> public override Int32 GetHashCode() => Value.GetHashCode(); #endregion #region (override) ToString() /// <summary> /// Return a text representation of this object. /// </summary> public override String ToString() => Value.ToString(); #endregion } }
30.022005
154
0.584331
e72b71c5779b2dc6d88b9d14ba67c235a2f69c7d
205
php
PHP
modules/admin/controllers/AppAdminController.php
AlexandrPanchuk/moda-store
25701a50a0c05709227db66a95b6de4d5c5c0bc0
[ "BSD-3-Clause" ]
null
null
null
modules/admin/controllers/AppAdminController.php
AlexandrPanchuk/moda-store
25701a50a0c05709227db66a95b6de4d5c5c0bc0
[ "BSD-3-Clause" ]
null
null
null
modules/admin/controllers/AppAdminController.php
AlexandrPanchuk/moda-store
25701a50a0c05709227db66a95b6de4d5c5c0bc0
[ "BSD-3-Clause" ]
null
null
null
<?php /** * Created by PhpStorm. * User: alexandr * Date: 29.09.17 * Time: 15:40 */ namespace app\modules\admin\controllers; use yii\web\Controller; class AppAdminController extends Controller { }
12.8125
43
0.702439
47fc88054ce5e6292d6be0aa301d255f560c5b46
426
sql
SQL
src/T-SQL/Stored Procedures/proc38_removeObj.sql
microsoft/ProcBench
206f4b6d29124191ad31e1d4c2635f247163cc57
[ "MIT" ]
27
2021-05-01T20:53:30.000Z
2022-01-19T15:55:54.000Z
src/T-SQL/Stored Procedures/proc38_removeObj.sql
microsoft/ProcBench
206f4b6d29124191ad31e1d4c2635f247163cc57
[ "MIT" ]
null
null
null
src/T-SQL/Stored Procedures/proc38_removeObj.sql
microsoft/ProcBench
206f4b6d29124191ad31e1d4c2635f247163cc57
[ "MIT" ]
4
2021-05-06T20:58:19.000Z
2021-09-15T17:17:59.000Z
CREATE or ALTER PROCEDURE RemoveObject( @objName nvarchar(max), @newName NVARCHAR(MAX)=NULL OUTPUT, @IfExists int = 0) AS BEGIN DECLARE @ObjectId INT; SELECT @ObjectId = OBJECT_ID(@objName); IF(@ObjectId IS NULL) BEGIN IF(@IfExists = 1) RETURN; RAISERROR('%s does not exist!',16,10,@objName); END; EXEC dbo.RenameObjectUsingObjectId @ObjectId, @NewName = @NewName OUTPUT; END; GO
23.666667
76
0.671362
b6f8d7caf683b455e689c5724bdb64c4966c3428
2,894
rb
Ruby
vendor/bundle/ruby/2.5.0/gems/rouge-3.9.0/lib/rouge.rb
jai-singhal/djangopy
67f5a7479aabc9bf6f85e9c880d40855cc8324ff
[ "MIT" ]
null
null
null
vendor/bundle/ruby/2.5.0/gems/rouge-3.9.0/lib/rouge.rb
jai-singhal/djangopy
67f5a7479aabc9bf6f85e9c880d40855cc8324ff
[ "MIT" ]
4
2020-06-24T11:27:00.000Z
2021-09-27T23:17:00.000Z
vendor/bundle/ruby/2.5.0/gems/rouge-3.9.0/lib/rouge.rb
jai-singhal/djangopy
67f5a7479aabc9bf6f85e9c880d40855cc8324ff
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # frozen_string_literal: true # stdlib require 'pathname' # The containing module for Rouge module Rouge class << self def reload! Object.send :remove_const, :Rouge load __FILE__ end # Highlight some text with a given lexer and formatter. # # @example # Rouge.highlight('@foo = 1', 'ruby', 'html') # Rouge.highlight('var foo = 1;', 'js', 'terminal256') # # # streaming - chunks become available as they are lexed # Rouge.highlight(large_string, 'ruby', 'html') do |chunk| # $stdout.print chunk # end def highlight(text, lexer, formatter, &b) lexer = Lexer.find(lexer) unless lexer.respond_to? :lex raise "unknown lexer #{lexer}" unless lexer formatter = Formatter.find(formatter) unless formatter.respond_to? :format raise "unknown formatter #{formatter}" unless formatter formatter.format(lexer.lex(text), &b) end end end # mimic Kernel#require_relative API def load_relative(path) load File.join(__dir__, "#{path}.rb") end def lexer_dir(path = '') File.join(__dir__, 'rouge', 'lexers', path) end load_relative 'rouge/version' load_relative 'rouge/util' load_relative 'rouge/text_analyzer' load_relative 'rouge/token' load_relative 'rouge/lexer' load_relative 'rouge/regex_lexer' load_relative 'rouge/template_lexer' Dir.glob(lexer_dir('*rb')).each { |f| Rouge::Lexers.load_lexer(f.sub(lexer_dir, '')) } load_relative 'rouge/guesser' load_relative 'rouge/guessers/util' load_relative 'rouge/guessers/glob_mapping' load_relative 'rouge/guessers/modeline' load_relative 'rouge/guessers/filename' load_relative 'rouge/guessers/mimetype' load_relative 'rouge/guessers/source' load_relative 'rouge/guessers/disambiguation' load_relative 'rouge/formatter' load_relative 'rouge/formatters/html' load_relative 'rouge/formatters/html_table' load_relative 'rouge/formatters/html_pygments' load_relative 'rouge/formatters/html_legacy' load_relative 'rouge/formatters/html_linewise' load_relative 'rouge/formatters/html_line_table' load_relative 'rouge/formatters/html_inline' load_relative 'rouge/formatters/terminal256' load_relative 'rouge/formatters/tex' load_relative 'rouge/formatters/null' load_relative 'rouge/theme' load_relative 'rouge/tex_theme_renderer' load_relative 'rouge/themes/thankful_eyes' load_relative 'rouge/themes/colorful' load_relative 'rouge/themes/base16' load_relative 'rouge/themes/github' load_relative 'rouge/themes/igor_pro' load_relative 'rouge/themes/monokai' load_relative 'rouge/themes/molokai' load_relative 'rouge/themes/monokai_sublime' load_relative 'rouge/themes/gruvbox' load_relative 'rouge/themes/tulip' load_relative 'rouge/themes/pastie' load_relative 'rouge/themes/bw' load_relative 'rouge/themes/magritte'
31.11828
87
0.734969
a98b63403bbaa56cad067d43c9b632b764bbb6d1
842
html
HTML
AppEngine/ubuntu_prod/test.html
valgarn/fraud-detection-framework
52ce63a41af42de541354f32a3fb4bae773f2f86
[ "Apache-2.0" ]
null
null
null
AppEngine/ubuntu_prod/test.html
valgarn/fraud-detection-framework
52ce63a41af42de541354f32a3fb4bae773f2f86
[ "Apache-2.0" ]
null
null
null
AppEngine/ubuntu_prod/test.html
valgarn/fraud-detection-framework
52ce63a41af42de541354f32a3fb4bae773f2f86
[ "Apache-2.0" ]
null
null
null
<!doctype html> <html> <head> <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,maximum-scale=1,target-densitydpi=device-dpi,user-scalable=0" /> <title>fdf docker-server test</title> </head> <body> <br /><br /> <form action="https://fraud-detection-framework.appspot.com/api/v2int/set_photo/info_exif_quality_benford_pca_cnn" method="POST" enctype="multipart/form-data"> <input type="file" name="photo" /><br /> <input type="submit" /> </form> <br /><br /> <a href="https://fraud-detection-framework.appspot.com/api/v2int/get_result">Check result</a> <br /><br /> <a href="https://fraud-detection-framework.appspot.com/liveness_check">Liveness check</a> <br /><br /> <a href="https://fraud-detection-framework.appspot.com/readiness_check">Readiness check</a> </body> </html>
30.071429
159
0.704276
46ed8a6be5c3254c3263359c6985b5bd42670eb4
6,009
py
Python
classa/classa/report/s_invoices_report/s_invoices_report.py
erpcloudsystems/classa
2e719355c0fe0b72eea42979a403870ed244497e
[ "MIT" ]
null
null
null
classa/classa/report/s_invoices_report/s_invoices_report.py
erpcloudsystems/classa
2e719355c0fe0b72eea42979a403870ed244497e
[ "MIT" ]
null
null
null
classa/classa/report/s_invoices_report/s_invoices_report.py
erpcloudsystems/classa
2e719355c0fe0b72eea42979a403870ed244497e
[ "MIT" ]
1
2022-02-08T19:50:59.000Z
2022-02-08T19:50:59.000Z
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): columns, data = [], [] columns = get_columns() data = get_data(filters, columns) return columns, data def get_columns(): return [ { "label": _("الفاتورة"), "fieldname": "name", "fieldtype": "Link", "options": "Sales Invoice", "width": 110 }, { "label": _("التاريخ"), "fieldname": "posting_date", "fieldtype": "Date", "width": 100 }, { "label": _("اسم العميل"), "fieldname": "customer", "fieldtype": "Link", "options": "Customer", "width": 220 }, { "label": _("مجموعة العميل"), "fieldname": "customer_group", "fieldtype": "Data", "width": 150 }, { "label": _("الفرع"), "fieldname": "branch", "fieldtype": "Data", "width": 90 }, { "label": _("المنطقة"), "fieldname": "territory", "fieldtype": "Data", "width": 90 }, { "label": _("عنوان العميل"), "fieldname": "customer_address", "options": "Data", "width": 200 }, { "label": _("إجمالي المبلغ"), "fieldname": "grand_total", "fieldtype": "Currency", "width": 130 }, { "label": _("مندوب الأوردر"), "fieldname": "sales_person", "fieldtype": "Data", "width": 220 }, { "label": _("مدير القسم"), "fieldname": "sales_manager", "fieldtype": "Data", "width": 220 }, { "label": _("مدير إدارة العميل"), "fieldname": "territory_manager", "fieldtype": "Data", "width": 220 }, { "label": _("مدير التشغيل الخارجي"), "fieldname": "sales_supervisor", "fieldtype": "Data", "width": 220 }, { "label": _("منسق"), "fieldname": "merchandiser", "fieldtype": "Data", "width": 220 }, { "label": _("السائق"), "fieldname": "driver", "fieldtype": "Data", "width": 220 }, { "label": _("منشأ بواسطة"), "fieldname": "owner", "fieldtype": "Data", "width": 240 }, ] def get_data(filters, columns): item_price_qty_data = [] item_price_qty_data = get_item_price_qty_data(filters) return item_price_qty_data def get_item_price_qty_data(filters): conditions = "" if filters.get("from_date"): conditions += " and `tabSales Invoice`.posting_date>=%(from_date)s" if filters.get("to_date"): conditions += " and `tabSales Invoice`.posting_date<=%(to_date)s" if filters.get("user"): conditions += " and `tabSales Invoice`.owner=%(user)s" result = [] item_results = frappe.db.sql(""" SELECT `tabSales Invoice`.name as name, `tabSales Invoice`.posting_date as posting_date, `tabSales Invoice`.customer as customer, `tabSales Invoice`.customer_group as customer_group, `tabSales Invoice`.branch as branch, `tabSales Invoice`.territory as territory, `tabSales Invoice`.customer_address as customer_address, `tabSales Invoice`.grand_total as grand_total, (Select `tabAddress`.sales_person from `tabAddress` where `tabAddress`.name = `tabSales Invoice`.customer_address) as sales_person, (Select `tabAddress`.sales_manager from `tabAddress` where `tabAddress`.name = `tabSales Invoice`.customer_address) as sales_manager, (Select `tabAddress`.territory_manager from `tabAddress` where `tabAddress`.name = `tabSales Invoice`.customer_address) as territory_manager, (Select `tabAddress`.sales_supervisor from `tabAddress` where `tabAddress`.name = `tabSales Invoice`.customer_address) as sales_supervisor, (Select `tabAddress`.merchandiser from `tabAddress` where `tabAddress`.name = `tabSales Invoice`.customer_address) as merchandiser, (Select `tabDriver`.full_name from `tabDriver` where `tabSales Invoice`.driver = `tabDriver`.name) as driver, (Select `tabUser`.full_name from `tabUser` where `tabSales Invoice`.owner = `tabUser`.name) as owner FROM `tabSales Invoice` WHERE `tabSales Invoice`.docstatus = 1 {conditions} ORDER BY `tabSales Invoice`.posting_date desc """.format(conditions=conditions), filters, as_dict=1) if item_results: for item_dict in item_results: data = { 'name': item_dict.name, 'posting_date': item_dict.posting_date, 'customer': item_dict.customer, 'customer_group': item_dict.customer_group, 'branch': item_dict.branch, 'territory': item_dict.territory, 'customer_address': item_dict.customer_address, 'grand_total': item_dict.grand_total, 'sales_person': item_dict.sales_person, 'sales_manager': item_dict.sales_manager, 'territory_manager': item_dict.territory_manager, 'sales_supervisor': item_dict.sales_supervisor, 'merchandiser': item_dict.merchandiser, 'driver': item_dict.driver, 'owner': item_dict.owner, } result.append(data) return result
33.569832
157
0.534532
da26f186068dbbd0a33390b22f33f3a7c8c1fa9e
16,589
php
PHP
resources/views/pages/users/govern_managers.blade.php
ahmedmagdihammad/Golf-App-
5ea5b89506830a3f1ffb37e8e29f8500dc887f13
[ "MIT" ]
null
null
null
resources/views/pages/users/govern_managers.blade.php
ahmedmagdihammad/Golf-App-
5ea5b89506830a3f1ffb37e8e29f8500dc887f13
[ "MIT" ]
null
null
null
resources/views/pages/users/govern_managers.blade.php
ahmedmagdihammad/Golf-App-
5ea5b89506830a3f1ffb37e8e29f8500dc887f13
[ "MIT" ]
null
null
null
@extends('layouts.master') @section('title') مديرين المحافظات @endsection @section('content') <section class="container mt-3" id="autofill"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#modal-add"><i class="la la-plus" style="font-size:14px"></i> إضافة مدير محافظة</button> <a class="heading-elements-toggle"><i class="la la-ellipsis-v font-medium-3"></i></a> <div class="heading-elements"> </div> </div> <div class="card-content collapse show"> <div class="card-body card-dashboard"> @if(count($govern_managers)>0) <table class="table table-striped table-bordered auto-fill"> <thead> <tr> <th>صورة </th> <th>إسم</th> <th>الموبايل</th> <th>العنوان</th> {{-- <th>رقم البطاقة</th> --}} <th>تم بواسطة </th> <th>تارخ الانشاء </th> <th> خيارات </th> </tr> </thead> <tbody> @foreach($govern_managers as $gov_manag) <tr> <td><img src="{{$gov_manag->picture}}" style="width: 64px; height: 64px;border-radius:50%"></td> <td>{{$gov_manag->name}}</td> <td>{{$gov_manag->phone}}</td> <td>{{$gov_manag->address}}</td> {{-- <td>{{$gov_manag->national_id}}</td> --}} <td>{{$gov_manag->user['name']}}</td> <td>{{$gov_manag->created_at}}</td> <td> <button type="button" class="btn btn-sm btn-warning" data-toggle="modal" data-target="#modal-edit{{$gov_manag->id}}"><i class="la la-edit"></i></button> <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#modal-delete{{$gov_manag->id}}"><i class="la la-trash"></i></button> </td> </tr> <!-- Model Edit --> <div id="modal-edit{{$gov_manag->id}}" class="modal fade" > <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <i class="la la-edit"> تعديل</i> <a href="#" data-dismiss="modal" class="la la-close"></a> </div> <form method="POST" action="{{route('gov_manag.edit', $gov_manag->id)}}" enctype="multipart/form-data"> @csrf <div class="modal-body"> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>إسم مدير المحافظة</label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="upname" id="upname" value="{{$gov_manag->name}}" placeholder="Enter Name" required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>الموبايل</label> </div> <div class="col-md-10"> <input class="form-control" type="number" name="upphone" id="upphone" value="{{$gov_manag->phone}}" placeholder="Enter Mobile" required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>العنوان</label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="upaddress" id="upaddress" value="{{$gov_manag->address}}" placeholder="Enter Address" required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>رقم البطاقة</label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="upnational_id" id="upnational_id" value="{{$gov_manag->national_id}}" placeholder="Enter Address" required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>صورة </label> </div> <div class="col-md-7"> <input class="form-control" type="file" name="uppicture" id="uppicture" value="{{$gov_manag->picture}}" placeholder="Enter Address" > </div> <div class="col-md-2"> <img src="{{$gov_manag->picture}}" style="width: 100px; height: 80px"> </div> </div> </div> <div class="form-group hidden"> <div class="row"> <div class="col-md-2"> <label>تم بواسطت</label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="upcreated_by" id="upcreated_by" value="{{Auth::user()->id}}" placeholder="Enter Created by" required=""> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">إلغاء</button> <button type="submit" class="btn btn-success">تعديل</button> </div> </form> </div> </div> </div> <!-- Model Delete --> <div id="modal-delete{{$gov_manag->id}}" class="modal fade" > <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <i class="la la-trash"> حذف</i> <a href="#" data-dismiss="modal" class="la la-close"></a> </div> <form method="POST" action="{{route('gov_manag.delete', $gov_manag->id)}}"> @csrf <div class="modal-body"> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>إسم مدير المحافظة</label> </div> <div class="col-md-4"> <p>{{$gov_manag->name}}</p> </div> <div class="col-md-2"> <label>موبايل</label> </div> <div class="col-md-4"> <p>{{$gov_manag->phone}}</p> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-info" data-dismiss="modal">إلغاء</button> <button type="submit" class="btn btn-danger">حذف</button> </div> </form> </div> </div> </div> @endforeach @else <h4 class="text-center mt-3"><i class="la la-frown-o"></i> لايوجد مديرين محافظات <i class="la la-frown-o"></i></h4> <br> <br> <br> <br> @endif </tbody> </table> </div> </div> </div> </div> </div> </section> <!-- Model Add --> <div id="modal-add" class="modal fade "> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h3> <i class="la la-plus"> </i> إضافة </h3> </div> <form method="POST" action="{{route('gov_manag.store')}}" enctype="multipart/form-data"> @csrf <div class="modal-body"> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>إسم مدير المحافظة</label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="name" id="name" placeholder="إسم مدير المحافظة" required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>موبايل </label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="phone" id="phone" placeholder=" موبايل " required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>العنوان </label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="address" id="address" placeholder=" العنوان " required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>رقم البطاقة </label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="national_id" id="national_id" placeholder=" رقم البطاقة " required=""> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-2"> <label>صورة </label> </div> <div class="col-md-10"> <input class="form-control" type="file" name="picture" id="picture" placeholder=" صورة " required=""> </div> </div> </div> <div class="form-group hidden"> <div class="row"> <div class="col-md-2"> <label>تم بواسطت</label> </div> <div class="col-md-10"> <input class="form-control" type="text" name="created_by" id="created_by" value="{{Auth::user()->id}}" placeholder="Enter Name" required=""> </div> </div> </div> <div class="accordion" id="accordionExample"> @foreach ($governorates as $governorate) <div class="card "> <div class="card-header bg-dark" id="headingOne{{$governorate->id}}"> <h2 class="mb-0"> <button class="btn btn-link text-light" type="button" data-toggle="collapse" data-target="#collapseOne{{$governorate->id}}" aria-expanded="true" aria-controls="collapseOne{{$governorate->id}}"> <div class="custom-control custom-checkbox d-inline-block ml-2"> <input type="checkbox" onchange="checkStates(this)" name="{{$governorate->id}}" class="custom-control-input" id="customCheck{{$governorate->id}}"> <label class="custom-control-label" for="customCheck{{$governorate->id}}"></label> </div> {{ $governorate->name }} </button> </h2> </div> <div id="collapseOne{{$governorate->id}}" class="collapse" aria-labelledby="headingOne{{$governorate->id}}" data-parent="#accordionExample"> <div class="card-body"> @if (count($governorate->states) <= 0) <h4 class="text-center">لا يوجد مراكز لهذة المحافظة</h4> <small class="d-block text-center"> <a href="{{ route('states.index') }}"> <i class="la la-plus-circle" style="font-size:14px"></i> اضافة مركز جديد </a> </small> @endif @if (count($governorate->states) > 0) @foreach ($governorate->states as $state) <div class="custom-control custom-checkbox d-inline-block ml-2"> <input type="checkbox" name="{{ $state->id }}" class="custom-control-input governorateId{{ $governorate->id }}" id="customCheck{{ $state->id }}"> <label class="custom-control-label" for="customCheck{{ $state->id }}">{{ $state->name }}</label> </div> @endforeach @endif </div> </div> </div> @endforeach </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">إلغاء</button> <button type="submit" class="btn btn-primary btn-sm">حفظ</button> </div> </form> </div> </div> </div> @endsection @section('scripts') <script> function checkStates(checkbox){ if(checkbox.checked) { var governorate_id = checkbox.id; $(".governorateId"+governorate_id.charAt(checkbox.id.length -1)+"").attr("checked","checked"); }else{ var governorate_id = checkbox.id; $(".governorateId"+governorate_id.charAt(checkbox.id.length -1)+"").removeAttr("checked"); } } </script> @endsection
50.730887
219
0.370848
c942012019fa390f089b6dfc4bfe749753915bc4
6,693
ts
TypeScript
src/request/index.ts
maldua-mirror/zm-api-js-client-OBSOLETE-develop-branch-deleted-on-20200329
33d060b45aaac1ffab522e85514ebc856ee73265
[ "BSD-3-Clause" ]
null
null
null
src/request/index.ts
maldua-mirror/zm-api-js-client-OBSOLETE-develop-branch-deleted-on-20200329
33d060b45aaac1ffab522e85514ebc856ee73265
[ "BSD-3-Clause" ]
null
null
null
src/request/index.ts
maldua-mirror/zm-api-js-client-OBSOLETE-develop-branch-deleted-on-20200329
33d060b45aaac1ffab522e85514ebc856ee73265
[ "BSD-3-Clause" ]
null
null
null
import get from 'lodash/get'; import reduce from 'lodash/reduce'; import { BatchRequestOptions, BatchRequestResponse, JsonRequestOptions, Namespace, NetworkError, ParsedResponse, RequestOptions, RequestResponse, SingleBatchRequestError, SingleBatchRequestResponse, SOAPHeader } from './types'; export const DEFAULT_HOSTNAME = '/@zimbra'; export const DEFAULT_SOAP_PATHNAME = '/service/soap'; function soapCommandBody(options: RequestOptions) { return { _jsns: options.namespace || Namespace.Mail, ...options.body }; } function parseJSON(response: Response): Promise<ParsedResponse> { if (!response.ok) { // whenever the response is not ok, for errors 502, 503, and 504 (gateway timeout/bad gateway), throw the network error if ([502, 503, 504].indexOf(response.status) !== -1) { throw networkError(response); } // for the rest of the cases (as of now only 500 error), parse and return the error response so that it can // be handled properly by the caller return parseErrorJSON(response).then(parsedResponse => { const fault = get(parsedResponse.parsed, 'Body.Fault'); throw faultError(parsedResponse, [fault]); }); } return _responseParseHandler(response); } function _responseParseHandler(response: Response): Promise<ParsedResponse> { try { return response.json().then(json => { (response as ParsedResponse).parsed = json; return response; }); } catch (e) { (response as ParsedResponse).parseError = e; return Promise.resolve(response); } } function parseErrorJSON(response: Response): Promise<ParsedResponse> { return _responseParseHandler(response); } function networkError(response: ParsedResponse) { const message = `Network request failed with status ${response.status}${ response.statusText ? `- "${response.statusText}"` : '' }`; const error = new Error(message); (error as NetworkError).message = message; (error as NetworkError).response = response; (error as NetworkError).parseError = response.parseError; return error as NetworkError; } function faultReasonText(faults: any = []): string { if (!Array.isArray(faults)) faults = [faults]; return faults .map((f: any) => get(f, 'Reason.Text')) .filter(Boolean) .join(', '); } function faultError(response: ParsedResponse, faults: any) { const error = new Error( `Fault error: ${faults ? faultReasonText(faults) : 'Unknown Error'}` ); (error as SingleBatchRequestError).response = response; (error as SingleBatchRequestError).parseError = response.parseError; (error as SingleBatchRequestError).faults = faults; return error as SingleBatchRequestError; } /** * Create one key per SOAP command name, with a value * containing an array of the requests for that command. */ function batchBody(requests: Array<RequestOptions>) { return reduce( requests, (body: { [key: string]: any }, request) => { const key = `${request.name}Request`; const value = soapCommandBody(request); if (body[key]) { body[key].push(value); } else { body[key] = [value]; } return body; }, {} ); } /** * For each SOAP command key, flatten it back out * into the ordered array that was requested. */ function batchResponse(requests: any, response: RequestResponse) { const { body: { _jsns: _, ...batchBody }, ...res } = response; // For each request type, track which responses have been // pulled out of the batch request body by incrementing // indexes. let indexes: { [key: string]: number } = {}; return { ...res, requests: reduce( requests, ( responses: Array<SingleBatchRequestResponse | SingleBatchRequestError>, request ) => { const batchResponses = batchBody[`${request.name}Response`]; const index = indexes[request.name]; const response: any = batchResponses && batchResponses[index || 0]; if (response) { responses.push({ body: response }); } else { responses.push(faultError(res.originalResponse, batchBody.Fault)); } if (index) { indexes[request.name] += 1; } else { indexes[request.name] = 1; } return responses; }, [] ) }; } export function batchJsonRequest( options: BatchRequestOptions ): Promise<BatchRequestResponse> { const { requests, ...requestOptions } = options; const body = batchBody(requests); return jsonRequest({ ...requestOptions, name: 'Batch', namespace: Namespace.All, body }).then(res => batchResponse(requests, res)); } export function jsonRequest( requestOptions: JsonRequestOptions ): Promise<RequestResponse> { const options = { ...requestOptions, credentials: requestOptions.credentials || 'include', headers: requestOptions.headers || {}, origin: requestOptions.origin !== undefined ? requestOptions.origin : DEFAULT_HOSTNAME, soapPathname: requestOptions.soapPathname || DEFAULT_SOAP_PATHNAME, namespace: requestOptions.namespace || Namespace.Mail }; const soapRequestName = `${options.name}Request`; const soapResponseName = `${options.name}Response`; const url = `${options.origin}${options.soapPathname}/${soapRequestName}`; let header: SOAPHeader; header = { context: { _jsns: Namespace.All, authTokenControl: { voidOnExpired: true } } }; if (requestOptions.userAgent) { header.context.userAgent = requestOptions.userAgent; } if (requestOptions.sessionId) { header.context.session = { id: requestOptions.sessionId, _content: requestOptions.sessionId }; } if (requestOptions.sessionSeq) { header.context.notify = { seq: requestOptions.sessionSeq }; } if (requestOptions.accountName) { header.context.account = { by: 'name', _content: requestOptions.accountName }; } if (requestOptions.accountId) { header.context.account = { by: 'id', _content: requestOptions.accountId }; } if (requestOptions.jwtToken) { header.context.jwtToken = { _content: requestOptions.jwtToken }; } if (requestOptions.csrfToken) { options.headers['X-Zimbra-Csrf-Token'] = requestOptions.csrfToken; header.context.csrfToken = requestOptions.csrfToken; } const body = { [soapRequestName]: soapCommandBody(options) }; return fetch(url, { method: 'POST', credentials: options.credentials, body: JSON.stringify({ Body: body, Header: header }), headers: options.headers }) .then(parseJSON) .then(response => { const globalFault = get(response.parsed, 'Body.Fault'); if (globalFault) { throw faultError(response, globalFault); } return { body: response.parsed.Body[soapResponseName], header: response.parsed.Header, namespace: response.parsed._jsns, originalResponse: response }; }); }
24.338182
121
0.698043
6828498713ee333086ba5991d3704d0e49b95c69
3,885
php
PHP
system/design/components/properties/TSB.php
KashaketCompany/Dev-S
27b2b0ad6ee318ce1b1503fc8d0cfc0a6c20cd14
[ "CC0-1.0" ]
6
2019-02-03T05:58:50.000Z
2019-05-17T02:27:23.000Z
system/design/components/properties/TSB.php
KashaketCompany/Dev-S
27b2b0ad6ee318ce1b1503fc8d0cfc0a6c20cd14
[ "CC0-1.0" ]
145
2019-02-02T19:32:03.000Z
2019-07-25T20:13:49.000Z
system/design/components/properties/TSB.php
KashaketCompany/Dev-S
27b2b0ad6ee318ce1b1503fc8d0cfc0a6c20cd14
[ "CC0-1.0" ]
3
2019-04-05T15:32:42.000Z
2019-07-22T17:32:56.000Z
<? $result = []; $result[] = array( 'CAPTION'=>t('Align'), 'TYPE'=>'combo', 'PROP'=>'align', 'VALUES'=>$_c->s('TAlign'), 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Text'), 'TYPE'=>'text', 'PROP'=>'caption', ); $result[] = array( 'CAPTION'=>t('font'), 'TYPE'=>'stfont', 'PROP'=>'font', 'CLASS'=>'TFont', ); $result[] = array('CAPTION'=>t('Font Color'), 'TYPE'=>'color', 'PROP'=>'OneFColor'); $result[] = array( 'CAPTION'=>t('TwoFColor'), 'TYPE'=>'color', 'PROP'=>'TwoFColor' ); $result[] = array( 'CAPTION'=>t('ThreeFColor'), 'TYPE'=>'color', 'PROP'=>'ThreeFColor' ); $result[] = array('CAPTION'=>t('Font Size'), 'PROP'=>'font->size'); $result[] = array('CAPTION'=>t('Font Height'), 'PROP'=>'font->height'); $result[] = array('CAPTION'=>t('Font Pitch'), 'PROP'=>'font->pitch'); $result[] = array('CAPTION'=>t('Font Orientation'), 'PROP'=>'font->orientation'); $result[] = array('CAPTION'=>t('Font Style'), 'PROP'=>'font->style'); $result[] = array( 'CAPTION'=>t('Color'), 'TYPE'=>'color', 'PROP'=>'ColorOne' ); $result[] = array('CAPTION'=>t('TwoC_'), 'TYPE'=>'color', 'PROP'=>'ColorTwo'); $result[] = array('CAPTION'=>t('ThreeC_'), 'TYPE'=>'color', 'PROP'=>'ColorThree'); $result[] = array( 'CAPTION'=>t('Auto Size'), 'TYPE'=>'check', 'PROP'=>'autoSize', 'ADD_GROUP'=>true, ); $result[] = array( 'CAPTION'=>t('Layout'), 'TYPE'=>'combo', 'PROP'=>'layout', 'VALUES'=>array('tlTop', 'tlCenter', 'tlBottom'), 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Alignment'), 'TYPE'=>'combo', 'PROP'=>'alignment', 'VALUES'=>array('taLeftJustify', 'taRightJustify','taCenter'), 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Transparent'), 'TYPE'=>'check', 'PROP'=>'transparent', 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Word Wrap'), 'TYPE'=>'check', 'PROP'=>'wordWrap', 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Hint'), 'TYPE'=>'text', 'PROP'=>'hint' ); $result[] = array( 'CAPTION'=>t('Cursor'), 'TYPE'=>'combo', 'PROP'=>'cursor', 'VALUES'=>$GLOBALS['cursors_meta'], 'NO_CONST'=>true, 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Sizes and position'), 'TYPE'=>'sizes', 'PROP'=>'', 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('Enabled'), 'TYPE'=>'check', 'PROP'=>'enabled', 'ADD_GROUP'=>true ); $result[] = array( 'CAPTION'=>t('visible'), 'TYPE'=>'check', 'PROP'=>'avisible', 'REAL_PROP'=>'visible', 'ADD_GROUP'=>true, ); return $result;
31.844262
84
0.362162