language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
TypeScript
UTF-8
781
2.546875
3
[]
no_license
import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import { Task } from 'src/app/models/Task'; @Component({ selector: 'app-add-task', templateUrl: './add-task.component.html', styleUrls: ['./add-task.component.css'] }) export class AddTaskComponent implements OnInit { text!: string; date!: string; reminder: boolean = false; @Output() onTaskAdd : EventEmitter<Task> = new EventEmitter() constructor() { } ngOnInit(): void { } onSubmit(){ if(!this.text){ alert("Please enter valid text"); return; } const newTask = { text : this.text, day : this.date, reminder : this.reminder } this.onTaskAdd.emit(newTask); this.text=''; this.date=''; this.reminder = false; } }
C++
UTF-8
1,312
2.859375
3
[]
no_license
class Solution { struct node { int in; vector<node *> next; node() : in(0), next(0) { } }; public: int longestIncreasingPath(vector<vector<int>>& matrix) { vector<vector<node>> m; for (auto &v: matrix) m.push_back(vector<node>(v.size())); int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; for (int i = 0; i < matrix.size(); i++) for (int j = 0; j < matrix[i].size(); j++) for (int k = 0; k < 4; k++) { int x = i + dx[k], y = j + dy[k]; if (0 <= x && x < matrix.size() && 0 <= y && y < matrix[x].size() && matrix[i][j] < matrix[x][y]) { m[i][j].next.push_back(&m[x][y]); m[x][y].in++; } } queue<node *> q; for (auto &v: m) for (auto &n: v) if (!n.in) q.push(&n); int depth = 0; for (int num = 1; !q.empty(); q.pop()) { if (!--num) { depth++; num = q.size(); } for (auto p: q.front()->next) if (!--p->in) q.push(p); } return depth; } };
Rust
UTF-8
6,329
2.921875
3
[ "MIT", "Zlib" ]
permissive
use super::system_prelude::*; #[derive(Default)] pub struct LoaderSystem; /// Loads loadable entities when they are within the camera. impl<'a> System<'a> for LoaderSystem { type SystemData = ( ReadExpect<'a, Settings>, Entities<'a>, Read<'a, LoadingLevel>, Write<'a, World>, ReadStorage<'a, Camera>, ReadStorage<'a, Loader>, ReadStorage<'a, Transform>, ReadStorage<'a, Size>, ReadStorage<'a, Enemy>, ReadStorage<'a, Loadable>, WriteStorage<'a, Loaded>, ); fn run( &mut self, ( settings, entities, loading_level, mut world, cameras, loaders, transforms, sizes, enemies, loadables, mut loadeds, ): Self::SystemData, ) { // Don't do anything if level is loading. if loading_level.0 { return; } let mut entities_loader = EntitiesLoader::default(); for (camera_opt, loader, loader_transform, loader_size_opt) in (cameras.maybe(), &loaders, &transforms, sizes.maybe()).join() { let loader_pos = { let pos = loader_transform.translation(); match camera_opt.as_ref() { None => (pos.x, pos.y), // If the loader is the camera, then its position's origin is bottom-left, // so we need to change the position we are working with accordingly. Some(_) => { let size = loader_size_opt.expect( "The camera needs to have a size as a loader", ); (pos.x + size.w * 0.5, pos.y + size.h * 0.5) } } }; for (entity, transform, size_opt, _, loaded_opt, enemy_opt) in ( &entities, &transforms, sizes.maybe(), &loadables, loadeds.maybe(), enemies.maybe(), ) .join() { let size = size_opt.map(|s| s.into()).unwrap_or(Vector::new(0.0, 0.0)); let loader_padding_default = Vector::new(0.0, 0.0); let loader_padding = loader.padding.as_ref().unwrap_or(&loader_padding_default); let load_distance = { let loader_distance = match loader.distance.as_ref() { None => { let loader_size = loader_size_opt.expect( "Loader needs to either have its `distance` \ field be Some or it needs to have a size \ component", ); ( loader_size.w * 0.5 + size.0 * 0.5 + loader_padding.0, loader_size.h * 0.5 + size.1 * 0.5 + loader_padding.1, ) } Some(distance) => ( distance.0 + loader_padding.0, distance.1 + loader_padding.1, ), }; match enemy_opt { None => { let difference = settings .entity_loader .enemy_load_distance_difference; ( loader_distance.0 + difference.0, loader_distance.1 + difference.1, ) } Some(_) => loader_distance, } }; let pos = transform.translation(); let distance = ( (loader_pos.0 - pos.x).abs(), (loader_pos.1 - pos.y).abs(), ); let in_distance = distance.0 <= load_distance.0 && distance.1 <= load_distance.1; match loaded_opt { None if in_distance => { entities_loader.load(entity); } Some(_) => { if in_distance { entities_loader.maintain_loaded(entity); } else { entities_loader.unload(entity); } } _ => (), // Do nothing } } } entities_loader.work(&mut loadeds, &mut world); } } #[derive(Default)] struct EntitiesLoader { to_load: Vec<Entity>, to_unload: Vec<Entity>, to_maintain_loaded: Vec<Entity>, } impl EntitiesLoader { pub fn load(&mut self, entity: Entity) { if !self.to_load.contains(&entity) { self.to_load.push(entity); self.maintain_loaded(entity); } } pub fn unload(&mut self, entity: Entity) { // Only unload if it isn't already staged for loading. if !self.to_load.contains(&entity) && !self.to_unload.contains(&entity) { self.to_unload.push(entity); } } pub fn maintain_loaded(&mut self, entity: Entity) { if !self.to_maintain_loaded.contains(&entity) { self.to_maintain_loaded.push(entity); } } pub fn work(self, loadeds: &mut WriteStorage<Loaded>, world: &mut World) { for entity in self.to_unload { if loadeds.contains(entity) { if !self.to_maintain_loaded.contains(&entity) { loadeds.remove(entity); } } } for entity in self.to_load { if !loadeds.contains(entity) { loadeds.insert(entity, Loaded).unwrap(); } } world.maintain(); } }
Markdown
UTF-8
3,679
3.265625
3
[]
no_license
# xml2json2txt ## This mini tool with zero dependences and <200 lines of code, can convert data between XML, JSON and TXT and viseversa. Is good for comunicate between multiple platforms heterogeneous, for example Cobol (TXT) <-> Node.js/Browser (JSON) <-> SOAP/REST API (XML). Tested in production, working on. ## Some examples... ```javascript const convert = require('xml2json2txt'); console.log(convert.json2xml({ hello: 'world', somedata: [ { name: 'Alice', foo: 'bar' }, { name: 'Bob', bar: 'foo' } ] })); /* <hello>world</hello> <somedata> <name>Alice</name> <foo>bar</foo> </somedata> <somedata> <name>Bob</name> <bar>foo</bar> </somedata> */ console.log(convert.json2txt({ hello: 'world', somedata: [ { name: 'Alice', foo: 'bar' }, { name: 'Bob', bar: 'foo' } ] })); /* hello world somedata[0]:name Alice somedata[0]:foo bar somedata[1]:name Bob somedata[1]:bar foo */ console.log(convert.xml2json('<country>' + '<people>' + '<name>Bob</name>' + '<gender>male</gender>' + '</people>' + '<people>' + '<name>Alice</name>' + '<gender>female</gender>' + '</people>' + '</country>')); /* { country: { people: [ { name: 'Bob', gender: 'male' }, { name: 'Alice', gender: 'female' } ] } } */ console.log(convert.xml2txt('<country>' + '<people>' + '<name>Bob</name>' + '<gender>male</gender>' + '</people>' + '<people>' + '<name>Alice</name>' + '<gender>female</gender>' + '</people>' + '</country>')); /* country:people[0]:name Bob country:people[0]:gender male country:people[1]:name Alice country:people[1]:gender female */ console.log(convert.txt2json('service Soap\n' + 'auth:token abc\n' + 'auth:secret cde\n' + 'data:name Bob\n' + 'data:age 27\n' + 'data:roles[0]:name Admin\n' + 'data:roles[1]:name Tester\n' )); /* { service: 'Soap', auth: { token: 'abc', secret: 'cde' }, data: { name: 'Bob', age: '27', roles: [ { name: 'Admin' }, { name: 'Tester' } ] } } */ console.log(convert.txt2xml('service Soap\n' + 'auth:token abc\n' + 'auth:secret cde\n' + 'data:name Bob\n' + 'data:age 27\n' + 'data:roles[0]:name Admin\n' + 'data:roles[1]:name Tester\n' )); /* <service>Soap</service> <auth> <token>abc</token> <secret>cde</secret> </auth> <data> <name>Bob</name> <age>27</age> <roles> <name>Admin</name> </roles> <roles> <name>Tester</name> </roles> </data> */ ```
JavaScript
UTF-8
254
3.046875
3
[]
no_license
function inicio(){ var styles = ["Jazz", "Blues"]; styles.push("Rock'n'Roll"); styles[1] = "Classic"; console.log(styles); lastStyle = styles[styles.length-1]; console.log(lastStyle); } window.addEventListener("load", inicio);
Markdown
UTF-8
1,584
3.0625
3
[]
no_license
# ACSE-7 (Inversion and Optimisation) Coursework This is the assessed coursework for module ACSE-7: Inversion and Optimisation for year 2020/21. It consists of four parts: Part-A (15 pts): covers lecture 1 Part-B (45 pts): covers lectures 2-7 Part-C (15 pts): covers lecture 8 Part-D (25 pts): covers lecture 9-11 Instructions: * This is independent work, you cannot work in groups. * Please provide your answers in each of the four notebooks seperately. * For questions that involve coding please include the output, printed output or graphs, that show the correct behaviour of your implementation without the need to rerun your code. However you do need to make sure that your code _can_ be rerun by executing the relevant cells in (top-to-bottom) order. * You are allowed to use NumPy and Scipy and any code from the lecture notes in your answers. * For answers that involve mathematical equations, use the usual combination of markdown and latex, or, if your prefer, include a photo/scan of your handwritten answer in the notebook. * Even if you're not completely sure how to complete a part of the question, our advice is to submit something, even if it's just your ideas on how to go about answering the question, as you could well score some marks. * **NOTE**: do not wait to complete Part-D until the very last minute! As explained in the notebook it is recommended to implement a version that you have tested on a small data set first, well in advance of the deadline, as the final run may take several hours to complete. **DEADLINE**: Friday 23 Apr 17:00 BST
C
UTF-8
866
4.21875
4
[ "CC0-1.0" ]
permissive
#include <stdio.h> #include <string.h> int main() { int c = 1; printf("while loop\n"); while (c <= 5) { printf("%d\n", c); c++; } printf("for loop\n"); for (int c = 1; c<=5; c++) printf("%d\n", c); printf("nested loops\n"); for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) printf("%d + %d = %d\n", i, j, i+j); printf("loop with break\n"); char s[] = "Coffee cup."; int i = 0; while (i < strlen(s)) { if (s[i] == ' ') break; i++; } if (i == strlen(s)) printf("%s does not contain a space\n", s); else printf("First space in %s is at position %d\n", s, i); printf("loop with continue\n"); for (int j = 1; j <= 10; j++) { if (j == 5) continue; printf("%d ", j); } printf("\n"); }
Python
UTF-8
276
3.609375
4
[]
no_license
sequence_of_values = list(map(float, input().split())) values_count = {} for value in sequence_of_values: if value not in values_count: values_count[value] = sequence_of_values.count(value) [print(f"{key} - {value} times") for key, value in values_count.items()]
Java
UTF-8
2,503
2.390625
2
[]
no_license
package flight.wizzair.entities; import static flight.entities.refdata.Station.BARCELONA; import static flight.entities.refdata.Station.BUDAPEST; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Test; import flight.entities.AbstractTest; import flight.entities.Flight; import flight.entities.refdata.Airline; import flight.entities.refdata.Currency; public class WizzairSearchResponseTest extends AbstractTest{ @Test public void testSearchResponseJsonConversion() throws Exception { WizzairSearchResponse searchResponse = objectMapper.readValue(readFromFile("searchResponse.json"), WizzairSearchResponse.class); Assert.assertFalse(searchResponse.getOutboundFlights().isEmpty()); Assert.assertFalse(searchResponse.getReturnFlights().isEmpty()); } @Test public void testSearchResponseJsonConversion_multi() throws Exception { WizzairSearchResponse searchResponse = objectMapper.readValue(readFromFile("searchResponse_multi.json"), WizzairSearchResponse.class); Assert.assertEquals(searchResponse.getOutboundFlights().size(), 2); List<Flight> outboundFlights = searchResponse.getOutboundFlights() .stream() .flatMap(r -> r.toFlights().stream()) .collect(Collectors.toList()); Assert.assertEquals(outboundFlights.size(), 3); assertFlight(outboundFlights.get(0), LocalDateTime.of(2020, 5, 23, 6, 0), 9690.0, Currency.HUF, BUDAPEST, BARCELONA, Airline.WIZZAIR, true); assertFlight(outboundFlights.get(1), LocalDateTime.of(2020, 5, 23, 17, 10), 9690.0, Currency.HUF, BUDAPEST, BARCELONA, Airline.WIZZAIR, true); assertFlight(outboundFlights.get(2), LocalDateTime.of(2020, 5, 24, 6, 0), 21090.0, Currency.HUF, BUDAPEST, BARCELONA, Airline.WIZZAIR, false); Assert.assertEquals(searchResponse.getReturnFlights().size(), 2); List<Flight> returnFlights = searchResponse.getReturnFlights() .stream() .flatMap(r -> r.toFlights().stream()) .collect(Collectors.toList()); Assert.assertEquals(returnFlights.size(), 3); assertFlight(returnFlights.get(0), LocalDateTime.of(2020, 5, 22, 9, 15), 21090.0, Currency.HUF, BARCELONA, BUDAPEST, Airline.WIZZAIR, false); assertFlight(returnFlights.get(1), LocalDateTime.of(2020, 5, 23, 9, 15), 19490.0, Currency.HUF, BARCELONA, BUDAPEST, Airline.WIZZAIR, true); assertFlight(returnFlights.get(2), LocalDateTime.of(2020, 5, 23, 20, 25), 19490.0, Currency.HUF, BARCELONA, BUDAPEST, Airline.WIZZAIR, true); } }
Java
UTF-8
636
3.765625
4
[ "MIT" ]
permissive
import java.util.Scanner; public class Exercise1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int userInput, computer; System.out.print("Enter 0 (Heads) or 1 (Tails): "); userInput = input.nextInt(); double d = Math.random(); computer = (int) (d * 2); if(computer == 0) { System.out.println("Coin flip: Heads"); } else { System.out.println("Coin flip: Tails"); } if(userInput == computer) { System.out.println("Correct!"); } else { System.out.println("Nope!"); } } }
Java
UTF-8
2,322
2.59375
3
[]
no_license
package com.tsi.aspects; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; import com.tsi.beans.Account; import com.tsi.exceptions.InsufficientFundException; @Component("aspect") @Aspect public class TransactionAspects { @Before("execution(* com.tsi.services.TransactionService.*(..))") public void before(JoinPoint jp) { Object[] params = jp.getArgs(); Account acc = (Account) params[0]; System.out.println("Before Advice Method : Initial Balance of your Account is :" + acc.getBalance()); } @After("execution(* com.tsi.services.TransactionService.*(..))") public void after(JoinPoint jp) { Object[] params = jp.getArgs(); Account acc = (Account) params[0]; System.out.println("After Advice Method : Final Balance of your Account is :" + acc.getBalance()); } @AfterReturning(pointcut = "execution(* com.tsi.services.TransactionService.*(..))",returning = "results") public void afterReturning(JoinPoint jp, String results) { System.out.println("Transaction Status " + results); } @Around("execution(* com.tsi.services.TransactionService.*(..))") public void around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Around Advice Before Method: " + pjp.getSignature().getName() + "Method Exception!!"); String status = ""; try { status = (String) pjp.proceed(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Around Advice After Method :" + pjp.getSignature().getName() + "Method Exception!!"); System.out.println("Around Advice After Method : Transaction Status :" + status); } @AfterThrowing(pointcut ="execution(* com.tsi.services.TransactionService.*(..))",throwing = "exception" ) public void afterThrowing(JoinPoint jp, InsufficientFundException exception) { System.out.println( "After Throwing :" + exception.getClass().getName() + "In Transaction " + exception.getMessage()); } }
TypeScript
UTF-8
1,674
2.65625
3
[]
no_license
import { AbstractControl } from '@angular/forms'; import { stringify } from '@angular/core/src/render3/util'; export function IDNumberValidator(control: AbstractControl) { const currentValue = control.value; if (isNaN(currentValue)) { return { validIDNumber: true }; } try { const StringCurrentValue = currentValue.toString(); if (StringCurrentValue.replace(' ', '').length < 13) { return { validIDNumber: true }; } const dateMonth: string = StringCurrentValue.substring(2, 4); const dateDay: string = StringCurrentValue.substring(4, 6); const saCitizenNumber: string = StringCurrentValue.substring(10, 11); if (parseInt(saCitizenNumber, 10) > 1 || parseInt(dateDay, 10) > 31 || parseInt(dateMonth, 10) > 12) { return { validIDNumber: true }; } // get the gender const genderCode = StringCurrentValue.substring(6, 10); const gender = parseInt(genderCode, 10) < 5000 ? 'Female' : 'Male'; // get country ID for citzenship const citzenship = parseInt(StringCurrentValue.substring(10, 11), 10) === 0 ? 'Yes' : 'No'; // apply Luhn formula for check-digits let tempTotal = 0; let checkSum = 0; let multiplier = 1; for (let i = 0; i < 13; ++i) { tempTotal = parseInt(StringCurrentValue.charAt(i), 10) * multiplier; if (tempTotal > 9) { tempTotal = parseInt(tempTotal.toString().charAt(0), 10) + parseInt(tempTotal.toString().charAt(1), 10); } checkSum = checkSum + tempTotal; multiplier = (multiplier % 2 === 0) ? 1 : 2; } if ((checkSum % 10) !== 0) { return { validIDNumber: true }; } } catch { } return null; }
C
UTF-8
656
3.0625
3
[]
no_license
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #define osAssert(cond, msg) osErrorFatal(cond, msg, __FILE__, __LINE__) void osErrorFatal(bool cond, char* msg, char* file, int line) { if(!cond) { perror(msg); fprintf(stderr, "%s: %d", file, line); exit(EXIT_FAILURE); } } int main(int argc, char** argv) { pid_t childPid = fork(); osAssert(-1 != childPid, "fork failed"); if (childPid > 0) printf("This is parent process\n"); else printf("This is child process\n"); printf("Both processes to this!\n"); }
C++
UTF-8
2,355
3.203125
3
[]
no_license
#include <chrono> #include <vector> #include "data_sorting.h" std::vector<long long> radix_sort(std::vector<int> data){ //index 0 = swaps; index 1 = comparisons; index 2 = time; std::vector<long long> results; results.resize(3); int cycles = 0; int size_data = data.size(); while(size_data != 0){ cycles++; size_data /= 10; } std::vector<std::vector<long long>> digit_counter; digit_counter.resize(10); auto begin = std::chrono::system_clock::now(); int divisor = 1; for(int i = 0; i < cycles; i++){ for(int j = 0; j < data.size(); j++){ int current_digit = data[j] / divisor % 10; switch (current_digit) { case 0: digit_counter[0].push_back(data[j]); break; case 1: digit_counter[1].push_back(data[j]); break; case 2: digit_counter[2].push_back(data[j]); break; case 3: digit_counter[3].push_back(data[j]); break; case 4: digit_counter[4].push_back(data[j]); break; case 5: digit_counter[5].push_back(data[j]); break; case 6: digit_counter[6].push_back(data[j]); break; case 7: digit_counter[7].push_back(data[j]); break; case 8: digit_counter[8].push_back(data[j]); break; case 9: digit_counter[9].push_back(data[j]); break; default: break; } results[0]++; } int index = 0; for(int i = 0; i < digit_counter.size(); i++){ while(digit_counter[i].size() != 0){ int num = digit_counter[i].front(); data[index] = digit_counter[i].front(); digit_counter[i].erase(digit_counter[i].begin()); index++; } } divisor *= 10; } auto finish = std::chrono::system_clock::now(); std::chrono::duration<double> delta_time = finish - begin; //Time in milliseconds results[2] = delta_time.count() * 1000; return results; }
Python
UTF-8
499
3.484375
3
[]
no_license
# coding=utf-8 # --- Day 2: Password Philosophy --- f = open('input.txt', 'r') valid_first, valid_second = 0, 0 for line in f: tokens = line.strip().split(' ') fr, to = map(lambda x: int(x), tokens[0].split('-')) let = tokens[1][0] passwd = tokens[2] if passwd.count(let) in range(fr, to + 1): valid_first += 1 valid_second += (passwd[fr - 1] == let) ^ (passwd[to - 1] == let) f.close() print("First part: ", valid_first) print("Second part: ", valid_second)
Java
UTF-8
2,386
2.671875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package byui.cit260.treeOfLife.model; import java.io.Serializable; import java.util.Objects; /** * * @author gradygb */ public class SceneTwo implements Serializable { private char type; private String description; private char symbol; private char blocked; private Location[] location; public SceneTwo() { } public char getType() { return type; } public void setType(char type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public char getSymbol() { return symbol; } public void setSymbol(char symbol) { this.symbol = symbol; } public char getBlocked() { return blocked; } public void setBlocked(char blocked) { this.blocked = blocked; } public Location[] getLocation() { return location; } public void setLocation(Location[] location) { this.location = location; } @Override public String toString() { return "SceneTwo{" + "type=" + type + ", description=" + description + ", symbol=" + symbol + ", blocked=" + blocked + '}'; } @Override public int hashCode() { int hash = 5; hash = 37 * hash + this.type; hash = 37 * hash + Objects.hashCode(this.description); hash = 37 * hash + this.symbol; hash = 37 * hash + this.blocked; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SceneTwo other = (SceneTwo) obj; if (this.type != other.type) { return false; } if (!Objects.equals(this.description, other.description)) { return false; } if (this.symbol != other.symbol) { return false; } return this.blocked == other.blocked; } }
SQL
UTF-8
41,648
3.390625
3
[]
no_license
ALTER TABLE `invdb`.`dc_request_audit` ADD COLUMN `product` VARCHAR(50) NULL AFTER `id`, ADD COLUMN `mode` VARCHAR(20) NULL AFTER `product`; USE `invdb`; DROP procedure IF EXISTS `dc_request_auditrial`; DELIMITER $$ USE `invdb`$$ CREATE PROCEDURE `dc_request_auditrial`( in p_id numeric(10), in p_product varchar(50), in p_mode varchar(20), in p_requestIds varchar(100), in p_acctNum varchar(12), in p_eventNum varchar(12), in p_envelopId varchar(100), in p_status varchar(1), in p_dcRequest varchar(5000), in p_dcResponce varchar(1000), in p_reqTime datetime, in p_resTime datetime, in p_remarks varchar(1000), in p_opt varchar(20), out op_msgCode int(3),out op_msg varchar(20)) BEGIN if(p_opt='INSERT') then Insert into dc_request_audit(product, mode, requestIds,acctnum,eventNum, dcRequest, dcResponce, status, remarks, reqTime, resTime) value(p_product, p_mode, p_requestIds,p_acctNum, p_eventNum, p_dcRequest, p_dcResponce, p_status, p_remarks, p_reqTime, p_resTime); if(p_status='S') then update dc_requests set status='S' , envelopeId =p_envelopId where acctnum=p_acctNum and eventNum=p_eventNum and status='I'; elseif(p_status='E') then update dc_requests set status='E' where acctnum=p_acctNum and eventNum=p_eventNum and status='I'; else update dc_requests set status='X' where acctnum=p_acctNum and eventNum=p_eventNum and status='I'; end if; SELECT p_opt, 1 INTO op_msg , op_msgCode; end if; END$$ DELIMITER ; DROP VIEW `vwdc_requests`; CREATE VIEW `vwdc_requests` AS SELECT `dc_requests_final`.`reqId` AS `reqId`, `dc_requests_final`.`acctnum` AS `acctnum`, `dc_requests_final`.`eventNum` AS `eventNum`, `dc_requests_final`.`envelopeHeading` AS `envelopeHeading`, `dc_requests_final`.`reqType` AS `reqType`, `dc_requests_final`.`envelopeId` AS `envelopeId`, `dc_requests_final`.`status` AS `status`, `dc_requests_final`.`refReqId` AS `refReqId`, `dc_requests_final`.`seqno` AS `seqNo`, `dc_requests_final`.`formType` AS `formType` FROM `dc_requests_final` ORDER BY acctnum, eventNum,seqNo; USE `invdb`; DROP procedure IF EXISTS `dc_request_auditrial`; DELIMITER $$ USE `invdb`$$ CREATE PROCEDURE `dc_request_auditrial`( in p_id numeric(10), in p_product varchar(50), in p_mode varchar(20), in p_requestIds varchar(100), in p_acctNum varchar(12), in p_eventNum varchar(12), in p_envelopId varchar(100), in p_status varchar(1), in p_dcRequest varchar(5000), in p_dcResponce varchar(1000), in p_reqTime datetime, in p_resTime datetime, in p_remarks varchar(1000), in p_opt varchar(20), out op_msgCode int(3),out op_msg varchar(20)) BEGIN if(p_opt='INSERT') then Insert into dc_request_audit(product, mode, requestIds,acctnum,eventNum, dcRequest, dcResponce, status, remarks, reqTime, resTime) value(p_product, p_mode, p_requestIds,p_acctNum, p_eventNum, p_dcRequest, p_dcResponce, p_status, p_remarks, p_reqTime, p_resTime); if(p_status='S') then update dc_requests_final set status='S' , envelopeId =p_envelopId where acctnum=p_acctNum and eventNum=p_eventNum and status='I'; update dc_requests set status='S' , envelopeId =p_envelopId where reqId in(select distinct(refReqId) from dc_requests_final where acctnum=p_acctNum and eventNum=p_eventNum); elseif(p_status='E') then update dc_requests_final set status='E' where acctnum=p_acctNum and eventNum=p_eventNum and status='I'; update dc_requests set status='E' where reqId in(select distinct(refReqId) from dc_requests_final where acctnum=p_acctNum and eventNum=p_eventNum); else update dc_requests_final set status='X' where acctnum=p_acctNum and eventNum=p_eventNum and status='I'; update dc_requests set status='X' where reqId in(select distinct(refReqId) from dc_requests_final where acctnum=p_acctNum and eventNum=p_eventNum); end if; /*UPDATE invdb.dc_requests SET status = 'I' WHERE acctnum = 2334 AND status = 'S';*/ SELECT p_opt, 1 INTO op_msg , op_msgCode; end if; END$$ DELIMITER ; INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ACAT_OTHER_NEW', 'DOCUSIGN', 'A', '0', 'BB_ACAT_OTHER'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ACCT_ADV_FORM', 'DOCUSIGN', 'A', '0', 'BB_ACCT_ADV'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ACCT_APPLI_NEW', 'DOCUSIGN', 'A', '0', 'BB_ACCT_APPLI'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ACCT_CHNG_ADDR', 'DOCUSIGN', 'A', '0', 'BB_CHNG_ADDRS'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ACCT_TRAN_NEW', 'DOCUSIGN', 'A', '0', 'BB_ACCT_TRANS'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_ADV_AGREE', 'DOCUSIGN', 'A', '0', 'BB_TCM_ADV_AGREE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ELEC_FUND_TRAN_CHANGE', 'DOCUSIGN', 'A', '0', 'BB_ELECT_FUND_TRANS'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ELEC_FUND_TRAN_NEW', 'DOCUSIGN', 'A', '0', 'BB_ELECT_FUND_TRANS'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'ELEC_FUND_TRAN_REPLACE', 'DOCUSIGN', 'A', '0', 'BB_ELECT_FUND_TRANS'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'IRA_APPLI_NEW', 'DOCUSIGN', 'A', '0', 'BB_IRA_APPLI'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'IRA_MOVE_MONEY_CHANGE', 'DOCUSIGN', 'A', '0', 'BB_MOVE_MONEY_IRA'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'IRA_MOVE_MONEY_NEW', 'DOCUSIGN', 'A', '0', 'BB_MOVE_MONEY_IRA'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'IRA_MOVE_MONEY_REMOVE', 'DOCUSIGN', 'A', '0', 'BB_MOVE_MONEY_IRA'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'IRA_QRP_BENE_NEW', 'DOCUSIGN', 'A', '0', 'BB_IRAQRP_BENE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'MOVE_MONEY_CHANGE', 'DOCUSIGN', 'A', '0', 'BB_MOVE_MONEY'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'MOVE_MONEY_NEW', 'DOCUSIGN', 'A', '0', 'BB_MOVE_MONEY'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'MOVE_MONEY_REMOVE', 'DOCUSIGN', 'A', '0', 'BB_MOVE_MONEY'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TCM_ADV_2AB', 'DOCUSIGN', 'A', '0', 'BB_TCM_ADV_2AB'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TCM_PRIVACY_NOTICE', 'DOCUSIGN', 'A', '0', 'BB_TCM_PRIVACY_NOTICE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TD_TRAN_NEW', 'DOCUSIGN', 'A', '0', 'BB_LPOA'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'ACCOUNT_ID', '18036', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'BASE_URL', 'https://demo.docusign.net/restapi', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'CCMAIL', 'docusign@invessence.com', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'CCMAILNAME', 'Building Benjamins', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'DOC_PATH', 'D:\\Project\\Abhang\\Project Work\\TCM\\documents', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'EXPIRE_AFTER', '60', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'EXPIRE_ENABLED', 'false', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'EXPIRE_WARN', '5', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'ID_CHECK_CONF_NAME', 'ID Check $', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'INTEGRATOR_KEY', 'TDAM-d7feb45c-e88d-4c20-b5bd-1dcd9a9d6f56', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'PASSWORD', 'Inv3ss3nc3!', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'REMINDER_DELAY', '1', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'REMINDER_ENABLED', 'false', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'REMINDER_FREQUENCY', '2', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'USERNAME', 'prashant@invessence.com', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'USE_ACCT_DEFAULT_NOTIFICATION', 'true', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'ACCOUNT_ID', '18036', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'BASE_URL', 'https://demo.docusign.net/restapi', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'CCMAIL', 'docusign@invessence.com', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'CCMAILNAME', 'Building Benjamins', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'DOC_PATH', 'D:\\Project\\Abhang\\Project Work\\TCM\\documents', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'EXPIRE_AFTER', '60', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'EXPIRE_ENABLED', 'false', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'EXPIRE_WARN', '5', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'ID_CHECK_CONF_NAME', 'ID Check $', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'INTEGRATOR_KEY', 'TDAM-d7feb45c-e88d-4c20-b5bd-1dcd9a9d6f56', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'PASSWORD', 'Inv3ss3nc3!', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'REMINDER_DELAY', '1', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'REMINDER_ENABLED', 'false', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'REMINDER_FREQUENCY', '2', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'USERNAME', 'prashant@invessence.com', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'DOCUSIGN', 'USE_ACCT_DEFAULT_NOTIFICATION', 'true', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('PROD', 'TCM', 'BROKER-WEBSERVICES', 'TD', 'SERVICE', 'Active', 'N'); INSERT INTO `service`.`service_config_details` (`mode`, `company`, `service`, `vendor`, `name`, `value`, `encrFlag`) VALUES ('UAT', 'TCM', 'BROKER-WEBSERVICES', 'TD', 'SERVICE', 'Active', 'N'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'service', 'status', 'vendor'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'AGGREGATION-SERVICES', 'A', 'MX'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'AGGREGATION-SERVICES', 'I', 'YODLEE'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'BROKER-WEBSERVICES', 'I', 'GEMINI'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'BROKER-WEBSERVICES', 'A', 'TD'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'A', 'DOCUSIGN'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'DOWNLOAD-SERVICES', 'I', 'GEMINI'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'DOWNLOAD-SERVICES', 'A', 'TD'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'EMAIL-SERVICE', 'A', 'INVESSENCE-GMAIL'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'PRICING', 'I', 'YAHOO'); INSERT INTO `service`.`service_master` (`company`, `service`, `status`, `vendor`) VALUES ('TCM', 'TRADE-PROCESS', 'A', 'VENDOR'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACAT_OTHER', 'ca47568b-70d6-42c4-b10f-0e10545e1a31', 'Account Transfer Form Other', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACCT_ADV', 'c3818a4d-320f-4a6c-8181-5c0f45206d69', 'Account ADV Forms', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACCT_APPLI', 'e21c6a62-8527-40d8-a006-26845ca2a1d5', 'Account Application', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACCT_TRANS', 'de101955-89c5-4cad-99b8-ec04fda60790', 'Account Transfer Form', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_CHNG_ADDRS', 'bba60794-5788-4656-8bb7-5857a228a52a', 'Change Address', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ELECT_FUND_TRANS', '7c19f254-3616-402e-ac0b-3279a241153b', 'Electronic Funds Transfer Form', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_IRAQRP_BENE', '0752806c-994e-4a48-b709-58ae78973882', 'IRA/QRP Beneficiary Account App', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_IRA_APPLI', 'ff8ec806-45e4-499d-846d-4ad84e628295', 'IRA Application', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_LPOA', '314a6465-44c1-4460-a31a-c10cc92ae886', 'LPOA', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_MOVE_MONEY', 'c607c4a9-09ee-4aea-8aff-e9e74d7a43e6', 'Move Money', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_MOVE_MONEY_IRA', 'a8e87128-8c05-4080-8fb9-c842709eada8', 'Move Money IRA', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_ADV_2AB', 'f5fd0a0d-1fca-486e-9de8-92386f322201', 'TCM ADV 2AB', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_ADV_AGREE', 'c0d642a7-7e19-486a-9b64-4e3d724f9965', 'Building Benjamins Tradition Advisory Agreeme', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_PRIVACY_NOTICE', 'ce93131f-68f2-4cf7-80e0-51a0636de5f2', 'TCM Privacy Notice', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACAT_OTHER', 'ca47568b-70d6-42c4-b10f-0e10545e1a31', 'Account Transfer Form Other', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACCT_ADV', 'c3818a4d-320f-4a6c-8181-5c0f45206d69', 'Account ADV Forms', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACCT_APPLI', 'e21c6a62-8527-40d8-a006-26845ca2a1d5', 'Account Application', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ACCT_TRANS', 'de101955-89c5-4cad-99b8-ec04fda60790', 'Account Transfer Form', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_CHNG_ADDRS', 'bba60794-5788-4656-8bb7-5857a228a52a', 'Change Address', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_ELECT_FUND_TRANS', '7c19f254-3616-402e-ac0b-3279a241153b', 'Electronic Funds Transfer Form', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_IRAQRP_BENE', '0752806c-994e-4a48-b709-58ae78973882', 'IRA/QRP Beneficiary Account App', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_IRA_APPLI', 'ff8ec806-45e4-499d-846d-4ad84e628295', 'IRA Application', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_LPOA', '314a6465-44c1-4460-a31a-c10cc92ae886', 'LPOA', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_MOVE_MONEY', 'c607c4a9-09ee-4aea-8aff-e9e74d7a43e6', 'Move Money', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_MOVE_MONEY_IRA', 'a8e87128-8c05-4080-8fb9-c842709eada8', 'Move Money IRA', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_ADV_2AB', 'f5fd0a0d-1fca-486e-9de8-92386f322201', 'TCM ADV 2AB', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_ADV_AGREE', 'c0d642a7-7e19-486a-9b64-4e3d724f9965', 'Building Benjamins Tradition Advisory Agreeme', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'BB_TCM_PRIVACY_NOTICE', 'ce93131f-68f2-4cf7-80e0-51a0636de5f2', 'TCM Privacy Notice', 'Y', 'A'); USE `invdb`; DROP procedure IF EXISTS `save_tddc_acct_details`; DELIMITER $$ USE `invdb`$$ CREATE PROCEDURE `save_tddc_acct_details`( `p_acctnum` bigint(20), `p_clientAccountID` varchar(45), `p_caseNumber` varchar(45), `p_advisorId` bigint(20), `p_acctTypeId` varchar(45), `p_cashSweepVehicleChoiceId` varchar(45), `p_divIntPrefId` varchar(45), `p_monthStmtId` varchar(45), `p_tradConfId` varchar(45), `p_dupStatement` char(1), `p_dupTradeConfirm` char(1), `p_proxyAuthorizationId` varchar(45), `p_optoutRegulatory` char(1), `p_optoutBeneficiary` char(1), `p_optoutFunding` char(1), `p_optoutRecurring` char(1), `p_createdBy` varchar(45) ) BEGIN DECLARE tAcctType VARCHAR(30); declare v_advisorId int; declare v_advId,v_repId varchar(45); select advisor, rep into v_advId,v_repId from user_trade_profile where acctnum=p_acctnum; select id into v_advisorId from invdb.dc_advisor_details where advisorName= v_advId and repId= (CASE WHEN v_repId is null or v_repId ='' THEN 'CATCHALL' ELSE v_repId END); INSERT INTO `dc_acct_details` (`acctnum`, `clientAccountID`, `caseNumber`, `advisorId`, `acctTypeId`, `cashSweepVehicleChoiceId`, `divIntPrefId`, `monthStmtId`, `tradConfId`, `dupStatement`, `dupTradeConfirm`, `proxyAuthorizationId`, `optoutRegulatory`, `optoutBeneficiary`, `optoutFunding`, `optoutRecurring`, `created`, `createdBy`) VALUES (`p_acctnum`, `p_clientAccountID`, `p_caseNumber`, IFNULL(v_advisorId,1), `p_acctTypeId`, `p_cashSweepVehicleChoiceId`, `p_divIntPrefId`, `p_monthStmtId`, `p_tradConfId`, `p_dupStatement`, `p_dupTradeConfirm`, `p_proxyAuthorizationId`, `p_optoutRegulatory`, `p_optoutBeneficiary`, `p_optoutFunding`, `p_optoutRecurring`, now(), `p_createdBy` ) ON DUPLICATE KEY UPDATE `clientAccountID` = `p_clientAccountID` ,`caseNumber` = `p_caseNumber` ,`advisorId` = IFNULL(`v_advisorId`,1) ,`acctTypeId` = `p_acctTypeId` ,`cashSweepVehicleChoiceId` = `p_cashSweepVehicleChoiceId` ,`divIntPrefId` = `p_divIntPrefId` ,`monthStmtId` = `p_monthStmtId` ,`tradConfId` = `p_tradConfId` ,`dupStatement` = `p_dupStatement` ,`dupTradeConfirm` = `p_dupTradeConfirm` ,`proxyAuthorizationId` = `p_proxyAuthorizationId` ,`optoutRegulatory`=`p_optoutRegulatory` ,`optoutBeneficiary`=`p_optoutBeneficiary` ,`optoutFunding`=`p_optoutFunding` ,`optoutRecurring`=`p_optoutRecurring` ,`updated` = now() ,`updatedBy` = `p_createdBy` ; -- Save the Account Type in User Trade Profile Table for easy display. SELECT `displayName` INTO `tAcctType` FROM `dc_m_lookup` WHERE `lookupSet` = 'ACCTTYPE' AND `lookupCode` = `p_acctTypeId` LIMIT 1; UPDATE `user_trade_profile` set `user_trade_profile`.`acctType` = IFNULL(`tAcctType`, `user_trade_profile`.`acctType`) WHERE `user_trade_profile`.`acctnum` = `p_acctnum`; END$$ DELIMITER ; USE `service`; CREATE OR REPLACE VIEW `vw_service_config_details_new` AS SELECT `scd`.`company` AS `company`, `scd`.`service` AS `service`, `scd`.`vendor` AS `vendor`, `scd`.`mode` AS `mode`, `scd`.`name` AS `name`, `scd`.`value` AS `value`, `scd`.`encrFlag` AS `encrFlag` FROM (`service_master` `sm` JOIN `service_config_details` `scd`) WHERE ((`sm`.`company` = `scd`.`company`) AND (`sm`.`service` = `scd`.`service`) AND (`sm`.`status` = 'A')) ORDER BY `scd`.`company` , `scd`.`service` , `scd`.`vendor` , `scd`.`mode` , `scd`.`name`; USE `service`; CREATE TABLE `service_error_external` ( `service` varchar(45) NOT NULL, `vendor` varchar(20) NOT NULL, `displayErrMsg` varchar(250) NOT NULL, `vendorErrCode` varchar(45) NOT NULL, `vendorErrMsg` varchar(250) NOT NULL, `status` varchar(1) DEFAULT NULL, `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, PRIMARY KEY (`service`,`vendor`,`vendorErrCode`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `service_error_internal` ( `errCode` varchar(45) NOT NULL, `errMsg` varchar(250) NOT NULL, `status` varchar(1) DEFAULT NULL, `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, PRIMARY KEY (`errCode`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; USE `service`; CREATE OR REPLACE VIEW `vw_service_error_external` AS SELECT `service_error_external`.`service` AS `service`, `service_error_external`.`vendor` AS `vendor`, `service_error_external`.`displayErrMsg` AS `displayErrMsg`, `service_error_external`.`vendorErrCode` AS `vendorErrCode`, `service_error_external`.`vendorErrMsg` AS `vendorErrMsg`, `service_error_external`.`status` AS `status` FROM `service_error_external`; USE `service`; CREATE OR REPLACE VIEW `vw_service_error_internal` AS SELECT `service_error_internal`.`errCode` AS `errCode`, `service_error_internal`.`errMsg` AS `errMsg`, `service_error_internal`.`status` AS `status` FROM `service_error_internal`; USE `service`; DROP procedure IF EXISTS `sel_service_common_details`; DELIMITER $$ USE `service`$$ CREATE PROCEDURE `sel_service_common_details`( IN p_product varchar(50), IN p_service varchar(50), IN p_type varchar(50) ) BEGIN if(p_service ='TRADE-PROCESS' and p_type='TRADE_FILE_DETAILS')then select vendor, fileName, fileType, fileExtension, delimeter, containsHeader, active, uploadDir, dbStoredProc, preInstruction, postInstruction from service.trade_process_file_details where vendor= p_product; elseif(p_service ='DOCUSIGN-SERVICES' and p_type='DOCUSIGN_MAPPING')then select * from service.dc_template_mapping where (dbColumn IS NOT NULL or dbColumn != '')order by tempCode, role, tab; end if; END$$ DELIMITER ; USE `service`; DROP procedure IF EXISTS `sel_service_details`; DELIMITER $$ USE `service`$$ CREATE PROCEDURE `sel_service_details`( IN p_product varchar(50), IN p_service varchar(50), IN p_type varchar(50), IN p_info varchar(50) ) BEGIN if(p_service ='TRADE-PROCESS' and p_type='COMMON_DETAILS' and p_info='TRADE_FILE_DETAILS')then select vendor, fileName, fileType, fileExtension, delimeter, containsHeader, active, uploadDir, dbStoredProc, preInstruction, postInstruction from service.trade_process_file_details where vendor= p_product; elseif(p_service ='DOCUSIGN-SERVICES' and p_type='COMMON_DETAILS' and p_info='DOCUSIGN_MAPPING')then select * from service.dc_template_mapping where (dbColumn IS NOT NULL or dbColumn != '') order by tempCode, role, tab; elseif(p_service ='DOCUSIGN-SERVICES' and p_type='ADDITIONAL_DETAILS' and p_info='TEMPLATE_DETAILS')then select * from service.dc_template_details where company= p_product order by company,mode, tempCode; elseif(p_type='OPERATION_DETAILS' and p_info='OPERATION_DETAILS')then select * from service.service_operation_details where status='A' and company=p_product and service=p_service order by operation; end if; END$$ DELIMITER ; INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_ADV_2AB', '01ee8896-5340-460c-87d8-b95fe9cf1b0d', 'TCM ADV 2AB', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_ADV_AGREE', 'c31f1730-84be-4ee5-bf6d-318b200d7e14', 'Tradition Advisory Agreement', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_PRIVACY_NOTICE', 'aa56763c-5fba-43c0-85cd-eabc75b0eeeb', 'TCM Privacy Notice', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_ADV_2AB', '09123936-8876-4263-aa1b-d741654e9505', 'TCM ADV 2AB', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_ADV_AGREE', 'd5a1c41b-21ce-4c99-9c8b-4c9ad403320a', 'Tradition Advisory Agreement', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_PRIVACY_NOTICE', '7efde06a-1180-4001-a0d6-c995440d7a17', 'TCM Privacy Notice', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_ADV_2AB', '01ee8896-5340-460c-87d8-b95fe9cf1b0d', 'TCM ADV 2AB', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_ADV_AGREE', 'c31f1730-84be-4ee5-bf6d-318b200d7e14', 'Tradition Advisory Agreement', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_PRIVACY_NOTICE', 'aa56763c-5fba-43c0-85cd-eabc75b0eeeb', 'TCM Privacy Notice', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_ADV_2AB', '09123936-8876-4263-aa1b-d741654e9505', 'TCM ADV 2AB', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_ADV_AGREE', 'd5a1c41b-21ce-4c99-9c8b-4c9ad403320a', 'Tradition Advisory Agreement', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_PRIVACY_NOTICE', '7efde06a-1180-4001-a0d6-c995440d7a17', 'TCM Privacy Notice', 'Y', 'A'); INSERT INTO `service`.`dc_template_mapping` (`tempCode`, `tab`, `lable`, `dbColumn`, `role`, `isDisabled`) VALUES ('TAI_ADV_AGREE', 'Textbox', 'AdvisorName', 'firmName', 'Client', 'N'); INSERT INTO `service`.`dc_template_mapping` (`tempCode`, `tab`, `lable`, `dbColumn`, `role`, `isDisabled`) VALUES ('TAI_ADV_AGREE', 'Textbox', 'FullName', 'fullName', 'Client', 'N'); INSERT INTO `service`.`dc_template_mapping` (`tempCode`, `tab`, `lable`, `dbColumn`, `role`, `isDisabled`) VALUES ('TAI_ADV_AGREE', 'Textbox', 'JointAHFullName', 'fullName', 'Joint', 'N'); INSERT INTO `service`.`dc_template_mapping` (`tempCode`, `tab`, `lable`, `dbColumn`, `role`, `isDisabled`) VALUES ('TAE_ADV_AGREE', 'Textbox', 'AdvisorName', 'firmName', 'Client', 'N'); INSERT INTO `service`.`dc_template_mapping` (`tempCode`, `tab`, `lable`, `dbColumn`, `role`, `isDisabled`) VALUES ('TAE_ADV_AGREE', 'Textbox', 'FullName', 'fullName', 'Client', 'N'); INSERT INTO `service`.`dc_template_mapping` (`tempCode`, `tab`, `lable`, `dbColumn`, `role`, `isDisabled`) VALUES ('TAE_ADV_AGREE', 'Textbox', 'JointAHFullName', 'fullName', 'Joint', 'N'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TAI_ADV_2AB', 'DOCUSIGN', 'A', '0', 'TAI_ADV_2AB'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TAI_ADV_AGREE', 'DOCUSIGN', 'A', '0', 'TAI_ADV_AGREE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TAI_PRIVACY_NOTICE', 'DOCUSIGN', 'A', '0', 'TAI_PRIVACY_NOTICE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TAE_ADV_2AB', 'DOCUSIGN', 'A', '0', 'TAE_ADV_2AB'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TAE_ADV_AGREE', 'DOCUSIGN', 'A', '0', 'TAE_ADV_AGREE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'TAE_PRIVACY_NOTICE', 'DOCUSIGN', 'A', '0', 'TAE_PRIVACY_NOTICE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'INT_ACAT_OTHER_NEW', 'DOCUSIGN', 'A', '0', 'TAI_ACAT_OTHER'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'EXT_ACAT_OTHER_NEW', 'DOCUSIGN', 'A', '0', 'TAE_ACAT_OTHER'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_ACAT_OTHER', 'c62d9775-24f8-46c4-91fe-834ce0dda1f6', 'TCM External Manual Account Transfer', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_ACAT_OTHER', '542ad322-7aa0-4c45-9f97-6187b198b874', 'TCM Internal Manual Account Transfer', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAE_ACAT_OTHER', 'c62d9775-24f8-46c4-91fe-834ce0dda1f6', 'TCM External Manual Account Transfer', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'TAI_ACAT_OTHER', '542ad322-7aa0-4c45-9f97-6187b198b874', 'TCM Internal Manual Account Transfer', 'Y', 'A'); insert into service.dc_template_mapping select 'TAE_ACAT_OTHER', tab, lable, dbColumn, role, isDisabled from service.dc_template_mapping where tempCode='BB_ACAT_OTHER'; insert into service.dc_template_mapping select 'TAI_ACAT_OTHER', tab, lable, dbColumn, role, isDisabled from service.dc_template_mapping where tempCode='BB_ACAT_OTHER'; INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'BUILDINGBENJAMINS', 'DOCUSIGN-SERVICES', 'GENE_EMAIL_MESSAGE', '6fe4789b-f36d-4c05-a974-67037c5a692e', 'Generic Email Message', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('PROD', 'TCM', 'DOCUSIGN-SERVICES', 'GENE_EMAIL_MESSAGE', '6fe4789b-f36d-4c05-a974-67037c5a692e', 'Generic Email Message', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'BUILDINGBENJAMINS', 'DOCUSIGN-SERVICES', 'GENE_EMAIL_MESSAGE', '6fe4789b-f36d-4c05-a974-67037c5a692e', 'Generic Email Message', 'Y', 'A'); INSERT INTO `service`.`dc_template_details` (`mode`, `company`, `service`, `tempCode`, `tempId`, `tempName`, `authRequired`, `status`) VALUES ('UAT', 'TCM', 'DOCUSIGN-SERVICES', 'GENE_EMAIL_MESSAGE', '6fe4789b-f36d-4c05-a974-67037c5a692e', 'Generic Email Message', 'Y', 'A'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('BUILDINGBENJAMINS', 'DOCUSIGN-SERVICES', 'GENE_EMAIL_MESSAGE', 'DOCUSIGN', 'A', '0', 'GENE_EMAIL_MESSAGE'); INSERT INTO `service`.`service_operation_details` (`company`, `service`, `operation`, `vendor`, `status`, `priority`, `refValue`) VALUES ('TCM', 'DOCUSIGN-SERVICES', 'GENE_EMAIL_MESSAGE', 'DOCUSIGN', 'A', '0', 'GENE_EMAIL_MESSAGE'); insert into adv_request_document_mappings select advisorid, action, 'DEFAULT', 'GENE_EMAIL_MESSAGE', envelopeHeading, 100, 'ADV' from adv_request_document_mappings where reqType='ACCT_APPLI_NEW' order by advisorId, action, seqno;
C#
UTF-8
1,518
3
3
[]
no_license
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SaturnsTurn5 { class Projectile { //projectile image public Texture2D Texture; public Vector2 Position; public bool Active; public int Damage { get; set; } Viewport viewport; //get the width of the projectile public int Width { get { return Texture.Width; } } //height of projectile public int Height { get { return Texture.Height; } } //how fast projectile moves float projectileMoveSpeed; public void Initialize(Viewport viewport, Texture2D texture, Vector2 position,int damage) { Texture = texture; Position = position; this.viewport = viewport; Active = true; this.Damage = damage; projectileMoveSpeed = 20f; } public void Update() { //projectiles move to the right always Position.X += projectileMoveSpeed; //deacivate the bullet if it goes out of screen if (Position.X + Texture.Width / 2 > viewport.Width) Active = false; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(Texture, Position, null, Color.White, 0f, new Vector2(Width / 2, Height / 2), 1f, SpriteEffects.None, 0f); } } }
C++
UTF-8
9,412
3.015625
3
[]
no_license
#pragma once #include "Point.hpp" #include "Plane.hpp" #include "Polygon.hpp" #include <Exceptions.hpp> // #include "PolyGroup.hpp" #include <CollisionGJK.hpp> namespace angem { template <typename Scalar> bool collision(const Plane<Scalar> & pl1, const Plane<Scalar> & pl2, Line<3,Scalar> & intersection) { /* The method selects a third plane P3 with * an implicit equation n3 · P = 0 where n3 = n1 x n2 and d3 = 0 (meaning it passes through the origin). This always works since: (1) L is perpendicular to P3 and thus intersects it, and (2) the vectors n1, n2, and n3 are linearly independent. Thus the planes P1, P2 and P3 intersect in a unique point P0 which must be on L. Using the formula for the intersection of 3 planes, where d3 = 0 for P3, we get: (d2 n1 - d1 n2) x n3 p3 = -------------------- (n1 x n2) · n3 Ref: http://geomalgorithms.com/a05-_intersect-1.html */ // direction of intersection line n 3 = n1 x n2 Point<3,Scalar> n3 = pl1.normal().cross(pl2.normal()); if (n3.norm() < 1e-16) return false; n3.normalize(); intersection.direction = n3; const auto & n1 = pl1.normal(); const auto & d1 = pl1.d; const auto & n2 = pl2.normal(); const auto & d2 = pl2.d; Point<3,Scalar> numerator = (d2*n1 - d1*n2).cross(n3); Scalar denumenator = (n1.cross(n2)).dot(n3); intersection.point = numerator / denumenator; return true; } // collision of a polygon with a plane // can be 1 points, two points, or zero points template <typename Scalar> bool collision(const Polygon<Scalar> & poly, const Plane<Scalar> & plane, std::vector<Point<3,Scalar>> & intersection, const double tol = 1e-10) { // call collision of all edges bool result = false; const auto & pts = poly.get_points(); for (std::size_t i=0; i<pts.size(); ++i) { bool loc_collision = false; if (i < pts.size() - 1) loc_collision = collision(pts[i], pts[i+1], plane, intersection, tol); else loc_collision = collision(pts[i], pts[0], plane, intersection, tol); if (loc_collision) result = true; } return result; } // collision of a polygon with a plane // can be 1 points, two points, or zero points template <typename Scalar> bool collision(const Polygon<Scalar> & poly1, const Polygon<Scalar> & poly2, std::vector<Point<3,Scalar>> & intersection, const double tol = 1e-10) { // CollisionGJK<double> collision_gjk; // if (!collision_gjk.check(poly1, poly2)) // { // std::cout << "no GJK" << std::endl; // return false; // } // std::cout << "yes GJK" << std::endl; if (poly1.plane.normal().parallel(poly2.plane.normal(), tol)) { // 1. find vertices of each poly inside another // 2. find intersection of edges if any points inside PointSet<3,Scalar> pset(tol * 1.5); // 1. const auto & pts1 = poly1.get_points(); const auto & pts2 = poly2.get_points(); bool all_inside1 = true, all_inside2 = true; for (const auto & p : pts1) if (poly2.point_inside(p, tol)) pset.insert(p); else all_inside2 = false; for (const auto & p : pts2) if (poly1.point_inside(p, tol)) pset.insert(p); else all_inside1 = false; // std::cout << pset.points << std::endl; if (all_inside1) { pset.points.clear(); pset.points = pts2; } if (all_inside2) { pset.points.clear(); pset.points = pts1; } // if (all_inside1 or all_inside2) // throw std::runtime_error("wtf"); // 2. if ( !pset.empty() and !all_inside1 and !all_inside2 ) for (const auto & edge1 : poly1.get_edges()) { std::vector<Point<3,Scalar>> v_points; Plane<Scalar> side = poly1.get_side(edge1); for (const auto & edge2 : poly2.get_edges()) { collision(pts2[edge2.first], pts2[edge2.second], side, v_points, tol); for (const auto & p : v_points) if (poly1.point_inside(p)) pset.insert(p); } } for (const auto & p: pset.points) intersection.push_back(p); if (pset.size() > 0) return true; else return false; } else // two polygons in non-parallel planes { std::vector<Point<3,Scalar>> v_section; angem::collision(poly1, poly2.plane, v_section, tol); bool result = false; for (const auto & p : v_section) if (poly2.point_inside(p, tol) and poly1.point_inside(p, tol)) { intersection.push_back(p); result = true; } return result; } return true; } // intersection of a segment with plane // intersection is appended to! template <typename Scalar> bool collision(const Point<3,Scalar> & l0, const Point<3,Scalar> & l1, const Plane<Scalar> & plane, std::vector<Point<3,Scalar>> & intersection, const double tol = 1e-10) { // Plane : (p - p0) · n = 0 // line p = d l + l0 // segment : l0, l1 // intersection: d = (p0 - l0) · n / (l · n) // call collision of all edges const Scalar d1 = plane.distance(l0); const Scalar d2 = plane.distance(l1); // both points are on the plane if (fabs(d1) + fabs(d2) < tol) { intersection.push_back(l0); intersection.push_back(l1); return true; } if (d1*d2 > 0) // both points on one side of plane return false; // compute intersection point const Point<3,Scalar> l = l1 - l0; const Scalar d = (plane.point - l0).dot(plane.normal()) / l.dot(plane.normal()); intersection.push_back(l0 + d * l); return true; } // marks polygons above fracture as 1 // polygons below fracture as 0 template <typename Scalar> void split(const Polygon<Scalar> & poly, const Plane<Scalar> & plane, PolyGroup<Scalar> & result, const int marker_below = 0, const int marker_above = 1) { std::vector<Point<3,Scalar>> section; collision(poly, plane, section); if (section.size() == 0) { std::vector<std::size_t> indices; bool above = false; for (const auto & p : poly.get_points()) { const std::size_t ind = result.vertices.insert(p); indices.push_back(ind); if (plane.above(p)) // technically need to check only one above = true; } result.polygons.push_back(indices); // assign markers if (above) result.markers.push_back(marker_above); else result.markers.push_back(marker_below); return; } std::vector<std::size_t> above, below; for (const auto p : poly.get_points()) { const std::size_t ind = result.vertices.insert(p); if (plane.above(p)) above.push_back(ind); else below.push_back(ind); } for (Point<3,Scalar> & p : section) { const std::size_t ind = result.vertices.insert(p); above.push_back(ind); below.push_back(ind); } if (above.size() > 2) { result.polygons.push_back(std::move(above)); result.markers.push_back(marker_above); } if (below.size() > 2) { result.polygons.push_back(std::move(below)); result.markers.push_back(marker_below); } } // throws std::runtime_error template <typename Scalar> bool collision(const Line<3,Scalar> & line, const Plane<Scalar> & plane, Point<3,Scalar> & intersection) { // Plane : (p - p0) · n = 0 // line p = d l + l0 // intersection: d = (p0 - l0) · n / (l · n) // Note: if (l · n) == 0 then line is parallel to the plane if (line.direction.dot(plane.normal()) < 1e-16) { if (plane.distance(line.point) < 1e-16) throw std::runtime_error("line and plane coinside."); return false; } const Scalar d = (plane.point - line.point).dot(plane.normal()) / line.direction.dot(plane.normal()); intersection = line.point + d*line.direction; return true; } // section is a vector cause line can reside on polygon // appends to vector intersection // note: polygon should have sorted points template <typename Scalar> bool collision(const Line<3,Scalar> & line, const Polygon<Scalar> & poly, std::vector<Point<3,Scalar>> & intersection) { // find intersection between polygon plane and line Point<3,Scalar> p; const bool colinear = collision(line, poly.plane, p); if (colinear) return false; // // check that intersection point is within the polygon // // algorithm: if section point is on the same side of the faces as the // // mass center, then the point is inside of the polygon // // const auto & poly_verts = poly.get_points(); // Point<3,Scalar> cm = poly.center(); // const auto & normal = poly.plane.normal(); // for (const auto & edge : poly.get_edges()) // { // Point<3,Scalar> p_perp = edge.first + normal * (edge.second - edge.first).norm(); // Plane<Scalar> side(edge.first, edge.second, p_perp); // if (side.above(p) != side.above(cm)) // return false; // } if (poly.point_inside(p), 1e-4) { intersection.push_back(p); return true; } else return false; } } // end namespace
SQL
UTF-8
3,651
3.296875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Sep 05, 2018 at 02:31 PM -- Server version: 5.7.23-0ubuntu0.18.04.1 -- PHP Version: 5.6.37-1+ubuntu18.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `try` -- -- -------------------------------------------------------- -- -- Table structure for table `accounts` -- CREATE TABLE `accounts` ( `Id` int(10) NOT NULL, `name` varchar(20) NOT NULL, `website` varchar(20) NOT NULL, `lat` int(10) NOT NULL, `longg` int(10) NOT NULL, `primary_poc` varchar(20) NOT NULL, `sales_rep_id` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `Orders` -- CREATE TABLE `Orders` ( `Id` int(10) NOT NULL, `account_id` int(10) NOT NULL, `standard_qty` int(10) NOT NULL, `poster_qty` int(10) NOT NULL, `total` int(10) NOT NULL, `standard_amt_usd` int(10) NOT NULL, `gloss_amt_usd` int(10) NOT NULL, `poster_amt_usd` int(10) NOT NULL, `total_amt_usd` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `region` -- CREATE TABLE `region` ( `Id` int(10) NOT NULL, `name` int(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `sales_reps` -- CREATE TABLE `sales_reps` ( `Id` int(11) NOT NULL, `name` int(11) NOT NULL, `region_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `web_events` -- CREATE TABLE `web_events` ( `occured_at` date NOT NULL, `account_id` int(11) NOT NULL, `channel` int(11) NOT NULL, `Id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `accounts` -- ALTER TABLE `accounts` ADD PRIMARY KEY (`Id`), ADD KEY `sales_rep_id` (`sales_rep_id`); -- -- Indexes for table `Orders` -- ALTER TABLE `Orders` ADD PRIMARY KEY (`Id`), ADD KEY `account_id` (`account_id`); -- -- Indexes for table `region` -- ALTER TABLE `region` ADD PRIMARY KEY (`Id`); -- -- Indexes for table `sales_reps` -- ALTER TABLE `sales_reps` ADD PRIMARY KEY (`Id`), ADD KEY `region_id` (`region_id`); -- -- Indexes for table `web_events` -- ALTER TABLE `web_events` ADD PRIMARY KEY (`Id`), ADD KEY `account_id` (`account_id`); -- -- Constraints for dumped tables -- -- -- Constraints for table `accounts` -- ALTER TABLE `accounts` ADD CONSTRAINT `accounts_ibfk_1` FOREIGN KEY (`Id`) REFERENCES `web_events` (`account_id`); -- -- Constraints for table `Orders` -- ALTER TABLE `Orders` ADD CONSTRAINT `Orders_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`Id`); -- -- Constraints for table `sales_reps` -- ALTER TABLE `sales_reps` ADD CONSTRAINT `sales_reps_ibfk_1` FOREIGN KEY (`region_id`) REFERENCES `region` (`Id`), ADD CONSTRAINT `sales_reps_ibfk_2` FOREIGN KEY (`Id`) REFERENCES `accounts` (`sales_rep_id`); /*!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 */;
PHP
UTF-8
3,242
2.671875
3
[]
no_license
<?php // wcf imports require_once(WCF_DIR.'lib/form/AbstractForm.class.php'); require_once(WCF_DIR.'lib/data/user/UserEditor.class.php'); /** * Shows the user activation form. * * @author Marcel Werk * @copyright 2001-2009 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package com.woltlab.wcf.form.user * @subpackage form * @category Community Framework */ class RegisterActivationForm extends AbstractForm { /** * user id * * @var integer */ public $userID = null; /** * activation code * * @var integer */ public $activationCode = ''; /** * user object * * @var UserEditor */ public $user; /** * @see AbstractPage::$templateName */ public $templateName = 'registerActivation'; /** * @see Page::readParameters() */ public function readParameters() { parent::readParameters(); if (isset($_GET['u']) && !empty($_GET['u'])) $this->userID = intval($_GET['u']); if (isset($_GET['a']) && !empty($_GET['a'])) $this->activationCode = intval($_GET['a']); } /** * @see Form::readFormParameters() */ public function readFormParameters() { parent::readFormParameters(); if (isset($_POST['u']) && !empty($_POST['u'])) $this->userID = intval($_POST['u']); if (isset($_POST['a']) && !empty($_POST['a'])) $this->activationCode = intval($_POST['a']); } /** * @see Form::validate() */ public function validate() { parent::validate(); // check given user id require_once(WCF_DIR.'lib/system/session/UserSession.class.php'); $this->user = new UserEditor($this->userID); if (!$this->user->userID) { throw new UserInputException('u', 'notValid'); } // user is already enabled if ($this->user->activationCode == 0) { throw new NamedUserException(WCF::getLanguage()->get('wcf.user.register.error.userAlreadyEnabled')); } // check given activation code if ($this->user->activationCode != $this->activationCode) { throw new UserInputException('a', 'notValid'); } } /** * @see Form::save() */ public function save() { parent::save(); // enable user // update activation code $this->additionalFields['activationCode'] = 0; $this->user->update('', '', '', null, null, $this->additionalFields); // remove user from guest group $this->user->removeFromGroup(Group::getGroupIdByType(Group::GUESTS)); // add user to default users group $this->user->addToGroup(Group::getGroupIdByType(Group::USERS)); // reset session Session::resetSessions($this->user->userID, true, false); $this->saved(); // forward to login page WCF::getTPL()->assign(array( 'url' => 'index.php'.SID_ARG_1ST, 'message' => WCF::getLanguage()->get('wcf.user.register.activation.redirect') )); WCF::getTPL()->display('redirect'); exit; } /** * @see Page::assignVariables() */ public function assignVariables() { parent::assignVariables(); WCF::getTPL()->assign(array( 'u' => $this->userID, 'a' => $this->activationCode )); } /** * @see Page::show() */ public function show() { if (!count($_POST) && $this->userID !== null && $this->activationCode != 0) { $this->submit(); } parent::show(); } } ?>
Python
UTF-8
5,630
3.3125
3
[]
no_license
'''Create Gender Data Picture''' def genderData(file): import numpy as np genotypes=np.load(file) # Create a new PCA object. pca = PCA(n_components=3) # Find three principal components, and project the dataset onto them. # This outputs an array of three-dimensional vectors, one per sample. genotypes_fit = pca.fit_transform(genotypes) ## Plot the dataset projected onto oe of the principal directions # Prepare axis for scatter, and for histogram to show distribution along axis. scatter_axes = plt.subplot2grid((3, 2), (1, 0), rowspan=2, colspan=2) x_hist_axes = plt.subplot2grid((3, 2), (0, 0), colspan=2, sharex=scatter_axes) # Plot scatter of genotypes on PC 2 scatter_axes.scatter(genotypes_fit[:,2], np.zeros_like(genotypes_fit[:,2]), color='blue', marker='.', s=3) # Plot histogram of distribution on PC2 x_hist_axes.hist(genotypes_fit[:,2],histtype='step',bins=40) plt.savefig("scatter.png") '''Analyze Populations''' def analyzePopulations(flabel, file2): # Import required Python libraries and genotypes dataset from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np labels=np.load(flabel) genotypes=np.load(file2) # Create a new PCA object. pca = PCA(n_components=3) # Find three principal components, and project the dataset onto them genotypes_fit = pca.fit_transform(genotypes) # Plot the dataset projected onto the two principal directions with labels for i in range(len(labels)): if labels[i] == 'LWK': color='green' lwk=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'YRI': color='purple' yri=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'MSL': color='orange' msl=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'ESN': color='blue' esn=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'GWD': color='black' gwd=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) # Create a legend plt.legend((lwk,yri,msl,esn,gwd),['Luhya in Webuye, Kenya', 'Yoruba in Ibadan, Nigeria','Mende in Sierra Leone', 'Esan in Nigeria','Gambian in Western Divisions'], scatterpoints=1, loc='upper right',ncol=1,fontsize=8) plt.xlabel("PC 1") plt.ylabel("PC 2") plt.savefig('pca.png') '''Genotype Average''' def genotypeAvg(): import numpy as np # Y-chromosome genotypes and their frequencies in the three populations (Icelandic, Nordic, and Irish) y = np.array([[1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1]]) freq_y = np.array([[0.41, 0.26, 0.82], [0.34, 0.51, 0.15], [0.23,0.18,0], [0.01,0.03,0.42]]) # Mitochondrial genotypes and theif frequencies in the three populations (Icelandic, Nordic, and Irish) m = np.array([[1,1,1,0,1,0,0,0], [0,0,1,1,0,1,0,0], [0,0,1,1,1,1,1,0], [0,0,0,0,1,0,0,1], [1,0,0,0,0,1,0,0]]) freq_m = np.array([[0.6, 0.29, 0.7], [0.14, 0.52, 0.21], [0.40,0.04,0.35], [0.04,0.65,0.03], [0.08,0.16,0.07]]) # Calculate average y-chromosome and mitochondrial genotypes for each population avg_y =[] avg_m =[] for i in range(3): avg_y.append(freq_y[0,i]*y[0,:]+freq_y[1,i]*y[1,:]+freq_y[2,i]*y[2,:]+freq_y[3,i]*y[3,:]) avg_m.append(freq_m[0,i]*m[0,:]+freq_m[1,i]*m[1,:]+freq_m[2,i]*m[2,:]+freq_m[3,i]*m[3,:]+freq_m[4,i]*m[4,:]) avg_y = np.array(avg_y) avg_m = np.array(avg_m) # Generate the two distance matrices map_y = np.zeros((3,3)) map_m = np.zeros((3,3)) for i in range(3): for j in range(3): map_y[i,j]= np.sqrt(np.sum((avg_y[i,:]-avg_y[j,:])**2)) map_m[i,j]= np.sqrt(np.sum((avg_m[i,:]-avg_m[j,:])**2)) print(avg_y) print(avg_m) import matplotlib.pyplot as plt plt.imshow(map_y) plt.colorbar() plt.savefig("map_y.png") plt.imshow(map_m) plt.savefig("map_m.png") ''' Know Ancestry ''' def knowAncestry(flabel1, file3): # Import required Python libraries and genotypes dataset from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np labels=np.load(flabel1) genotypes=np.load(file3) # Create a new PCA object. pca = PCA(n_components=3) # Find three principal components, and project the dataset onto them genotypes_fit = pca.fit_transform(genotypes) # Plot the dataset projected onto the two principal directions with labels for i in range(len(labels)): if labels[i] == 'LWK': color='green' lwk=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'YRI': color='purple' yri=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'MSL': color='orange' msl=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'ESN': color='blue' esn=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) elif labels[i] == 'GWD': color='black' gwd=plt.scatter(genotypes_fit[i,1],genotypes_fit[i,0], c=color) # Create a legend plt.legend((lwk,yri,msl,esn,gwd),['Luhya in Webuye, Kenya', 'Yoruba in Ibadan, Nigeria','Mende in Sierra Leone', 'Esan in Nigeria','Gambian in Western Divisions'], scatterpoints=1, loc='upper right',ncol=1,fontsize=8) plt.xlabel("PC 1") plt.ylabel("PC 2") plt.savefig('pca.png') sample = np.load("data/sample.npy") [[1, 1, 0, ..., 0, 0, 0]] sample_proj = pca.transform(sample) plt.scatter(sample_proj[0][1], sample_proj[0][0], c='red', marker='X', s = 500) plt.savefig('indi.png')
C++
UTF-8
3,746
2.59375
3
[ "MIT" ]
permissive
#define _USE_MATH_DEFINES #include <DataStructures.h> #include <vector> #include <array> #include <math.h> #include <cmath> #include <string> #include <iostream> void CameraData::AccelerateCamera(float acc[3]) { for (int i = 0; i < 3; i++) acceleration[i] += acc[i] * acc_mul; } void CameraData::RotateCamera(float dx, float dy) { rotation[1] += dx * sensitivity * (500.0f/m_width); if (rotation[0] + dy * sensitivity * (500.0f / m_width) < -90) rotation[0] = -90; else if (rotation[0] + dy * sensitivity * (500.0f / m_width) > 90) rotation[0] = 90; else rotation[0] += dy * sensitivity * (500.0f / m_width); rotation[1] = (float)fmod(rotation[1], 360); if((abs(dx) > 0.0001f) || (abs(dy) > 0.0001f)) m_changed = true; } void CameraData::CopyData(ShaderData& shader_data) { shader_data._camera_position = { position[0], position[1], position[2], 0 }; shader_data._camera_rotation = { rotation[0], rotation[1], rotation[2], 0 }; } bool CameraData::HasChanged() { return m_changed; } void CameraData::SetChanged(bool ch) { m_changed = ch; } float DegToRad(float deg) { return (float)(deg * (M_PI / 180.0f)); } void CameraData::UpdateCameraData(float time) { std::vector<std::vector<float>> move_vectors; std::vector<float> forward = { -sin(DegToRad(rotation[1])), sin(DegToRad(rotation[0])), cos(DegToRad(rotation[1])) }; std::vector<float> up = { 0, 1.0f, 0 }; std::vector<float> right = { cos(DegToRad(rotation[1])), 0, sin(DegToRad(rotation[1])) }; move_vectors.push_back(right); move_vectors.push_back(up); move_vectors.push_back(forward); //update position for (int i = 0; i < 3; i++) { temp[0] = position[i]; temp[1] = rotation[i]; // calculate accelleration float accel = 0; for (int x = 0; x < 3; x++) accel += acceleration[x] * move_vectors[x][i]; velocity[i] += accel * time; position[i] += velocity[i] * time; // apply friction float sum = abs(velocity[0]) + abs(velocity[1]) + abs(velocity[2]); float part_friction = abs((velocity[i] / sum)) * friction; if (sum != 0) { if (velocity[i] > 0) { if (part_friction * time > velocity[i]) velocity[i] = 0; else velocity[i] -= part_friction * time; } else if (velocity[i] < 0) { if (part_friction * time < velocity[i]) velocity[i] = 0; else velocity[i] += part_friction * time; } position[i] += velocity[i] * time; } if ((temp[0] != position[i]) || (temp[1] != rotation[i])) m_changed = true; } // reset acceleration for (int i = 0; i < 3; i++) acceleration[i] = 0; // scale velocity to max velocity float length = sqrt(pow(velocity[0], 2) + pow(velocity[1], 2) + pow(velocity[2], 2)); float scaling = 1.0f; if (length > max_v) { scaling = ((length - max_v) / max_v) + 1.0f; for(int i = 0; i < 3; i++) velocity[i] /= scaling; } } void ShaderData::UpdateSeed() { _seed = GetRand(); } void ShaderData::UpdateWindowSize(int width, int height) { _screen_size[0] = width; _screen_size[1] = height; } void ShaderData::GetWindowSize(int& width, int& height) { width = _screen_size[0]; height = _screen_size[1]; } int ShaderData::GetWidth() { return _screen_size[0]; } int ShaderData::GetHeight() { return _screen_size[1]; } void CameraData::UpdateWindowSize(int width, int height) { m_width = width; m_height = height; }
Java
UTF-8
4,683
2.1875
2
[]
no_license
package is.hi.g.hikersicelands.hikersicelands.Controllers; import is.hi.g.hikersicelands.hikersicelands.Entities.Achievement; import is.hi.g.hikersicelands.hikersicelands.Entities.Hike; import is.hi.g.hikersicelands.hikersicelands.Entities.Item; import is.hi.g.hikersicelands.hikersicelands.Entities.Profile; import is.hi.g.hikersicelands.hikersicelands.Services.HikeService; import is.hi.g.hikersicelands.hikersicelands.Services.ItemService; import is.hi.g.hikersicelands.hikersicelands.Services.ProfileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpSession; import javax.validation.Valid; @Controller public class ItemController { private HikeService hikeService; private ItemService itemService; private ProfileService profileService; @Autowired public ItemController(HikeService hikeService, ItemService itemService, ProfileService profileService) { this.hikeService = hikeService; this.itemService = itemService; this.profileService = profileService; } @RequestMapping(value = "/hike/{id}/item", method = RequestMethod.POST) public String additem(@PathVariable("id") long id, @Valid Item item, BindingResult result, Model model, HttpSession httpSession) { if (result.hasErrors()) { return "welcome"; } // find the hike Hike hike = hikeService.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid Hike Id")); // create a new item Item saveItem = new Item(item.getName(), item.getDescription(), item.getItemType(), item.getImage(), hike); itemService.save(saveItem); Hike updatedHike = hikeService.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid Hike Id")); model.addAttribute("hike", updatedHike); model.addAttribute("achievement", new Achievement()); model.addAttribute("item", new Item()); String sessionUsername = (String) httpSession.getAttribute("username"); if (sessionUsername != null) { Profile sessionProfile = profileService.searchProfileByUsername(sessionUsername); model.addAttribute("profile", sessionProfile); } return "hike"; } @RequestMapping(value = "/hike/{hikeid}/item/{itemid}", method = RequestMethod.POST) public String deleteitem(@PathVariable("hikeid") long hikeid, @PathVariable("itemid") long id, @Valid Item item, BindingResult result, Model model, HttpSession httpSession) { if (result.hasErrors()) { return "welcome"; } itemService.deleteItemById(id); Hike hike = hikeService.findById(hikeid).orElseThrow(() -> new IllegalArgumentException("Invalid Hike Id")); model.addAttribute("hike", hike); model.addAttribute("achievement", new Achievement()); model.addAttribute("item", new Item()); String sessionUsername = (String) httpSession.getAttribute("username"); if (sessionUsername != null) { Profile sessionProfile = profileService.searchProfileByUsername(sessionUsername); model.addAttribute("profile", sessionProfile); } return "Hike"; } @RequestMapping(value = "/hike/{hikeid}/item/{itemid}/complete", method = RequestMethod.POST) public String completeitem(@PathVariable("hikeid") long hikeid, @PathVariable("itemid") long id, @Valid Item item, BindingResult result, Model model, HttpSession httpSession) { if (result.hasErrors()) { return "welcome"; } // TODO complete hike for a user Hike hike = hikeService.findById(hikeid).orElseThrow(() -> new IllegalArgumentException("Invalid Hike Id")); model.addAttribute("hike", hike); model.addAttribute("achievement", new Achievement()); model.addAttribute("item", new Item()); String sessionUsername = (String) httpSession.getAttribute("username"); if (sessionUsername != null) { Profile sessionProfile = profileService.searchProfileByUsername(sessionUsername); model.addAttribute("profile", sessionProfile); } return "Hike"; } @RequestMapping(value = "/hike/{id]/item", method = RequestMethod.GET) public String additemForm(Hike hike) { return "welcome"; } }
Java
UTF-8
3,341
2.21875
2
[]
no_license
package com.social.tmdb.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "backdrops", "posters", "profiles", "stills" }) public class Images { @JsonProperty("id") private Integer id; @JsonProperty("backdrops") private List<Backdrop> backdrops; @JsonProperty("posters") private List<Poster> posters; @JsonProperty("profiles") private List<Profile> profiles; @JsonProperty("stills") private List<Still> stills; /** * * @return * The id */ @JsonProperty("id") public Integer getId() { return id; } /** * * @param id * The id */ @JsonProperty("id") public void setId(Integer id) { this.id = id; } /** * * @return * The backdrops */ @JsonProperty("backdrops") public List<Backdrop> getBackdrops() { return backdrops; } /** * * @param backdrops * The backdrops */ @JsonProperty("backdrops") public void setBackdrops(List<Backdrop> backdrops) { this.backdrops = backdrops; } /** * * @return * The posters */ @JsonProperty("posters") public List<Poster> getPosters() { return posters; } /** * * @param posters * The posters */ @JsonProperty("posters") public void setPosters(List<Poster> posters) { this.posters = posters; } /** * * @return * The profiles */ @JsonProperty("profiles") public List<Profile> getProfiles() { return profiles; } /** * * @param profiles * The profiles */ @JsonProperty("profiles") public void setProfiles(List<Profile> profiles) { this.profiles = profiles; } /** * * @return * The stills */ @JsonProperty("stills") public List<Still> getStills() { return stills; } /** * * @param stills * The stills */ @JsonProperty("stills") public void setStills(List<Still> stills) { this.stills = stills; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int hashCode() { return new HashCodeBuilder().append(id).append(backdrops).append(posters).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Images) == false) { return false; } Images rhs = ((Images) other); return new EqualsBuilder().append(id, rhs.id).append(backdrops, rhs.backdrops).append(posters, rhs.posters).isEquals(); } }
JavaScript
UTF-8
4,605
4.40625
4
[]
no_license
//Await a Minute! Async/Await and a new syntax for Promises //The await and async keywords have been added to javascript to indicate asynchronous functions and they have the following effects: //By adding the async keyword, you make the result of that function a Promise, even if it would normally be completed synchronously. let returnRandNumAsync = async () => { return Math.random()*35; } let return35 = () => { return Math.random()*35; } let asyncAwaitPlayground = () => { console.log(returnRandNumAsync()); console.log(return35()); } // asyncAwaitPlayground(); //If you try to perform normal operations on the result of an async function, you must remember to treat it as a Promise! asyncAwaitPlayground = () => { let sum = return35() + return35(); console.log(sum); let asyncSum = returnRandNumAsync() + returnRandNumAsync(); console.log(asyncSum); } // asyncAwaitPlayground(); //Because the results of async functions are Promises, you can use a .then block //PS. remember the order from 03-eventLoop! asyncAwaitPlayground = () => { let res = returnRandNumAsync().then(res => console.log(`This will happen next: ${res}`)); console.log(`This will happen first ${res}`); } // asyncAwaitPlayground(); //However this is eerily reminiscent of the callback hell we wish to avoid. //If our asynchronous code should be handled synchronously, you should use await! //Await pauses the event loop that an asynchronous function or Promise is called in until it is resolved or rejected!! //(Await can only be used in an async function, not in normally declared functions or top-level code) //This has two huge effects! //1.) It is a lot clearer to write Promise-based code, without the use of long .then blocks asyncAwaitPlayground = async () => { let res = await returnRandNumAsync(); console.log(`This will happen first ${res}`); } //2.) Because the event loop is halted, an error is handled at its expected place in the call stack! //It can therefore be caught by a normal try/catch block! let errorThrowingAsyncFunction = async () => { throw new Error('I am an error'); } asyncAwaitPlayground = async () => { try { console.log("I'm about to throw an error!"); await errorThrowingAsyncFunction(); } catch (e) { console.log(`Caught and handled error: ${e.message}`); } } // asyncAwaitPlayground(); //You can also use a .catch block with or without the await keyword, however non-await code will still execute in that strange callback hell-ish way we don't like asyncAwaitPlayground = async () => { try { console.log("1"); errorThrowingAsyncFunction().catch(e => { console.log("3"); }) console.log("2"); await errorThrowingAsyncFunction(); } catch (e) { console.log(`4`); } console.log('5'); } // asyncAwaitPlayground(); //For most circumstances, if you are using async/await and try/catch blocks, it's my opinion that it's needlessly confusing to use .catch blocks also. //However!!! You should be careful to await any async functions you use: an error from an async function will be treated as a Promise rejection! //Therefore it will log a Promise rejection warning! asyncAwaitPlayground = async () => { try { console.log('we will get here'); errorThrowingAsyncFunction() console.log("we will even get here"); } catch (e) { console.log('We will never get here'); } } // asyncAwaitPlayground(); //The await keyword can be applied to any Promise, notably even after it's instantiated! asyncAwaitPlayground = async () => { let p = returnRandNumAsync(); console.log('P is just a Promise right now: ' + p); await p; console.log('P but after awaiting it has a value: ' + p); } // asyncAwaitPlayground(); //Another counterintuitive behaviour!! The await keyword does not wait for the Promise stored in p to resolve? //Why is this?? asyncAwaitPlayground = async () => { let p = returnRandNumAsync(); console.log('P is just a Promise right now: ' + p); let val = await p; console.log('P after awaiting and adding 1 to its value: ' + (p + 1) + '\nBut after assigning its value: ' + val); } asyncAwaitPlayground(); // p was actually resolved in the previous example but it is still treated as a Promise as in the console log. // However, assigning the awaited Promise to a value will pass the value of the resolved Promise the way we'd expect. // This final quirk is worth noting if your Promise is awaiting a value as opposed to just the resolution of the Promise.
Java
UTF-8
735
1.890625
2
[]
no_license
package org.shop.model.vo; import lombok.Data; import lombok.ToString; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Data @ToString public class ProductSpecAddVO { @NotEmpty(message = "product spec name cannot be empty") private String name; @NotEmpty(message = "product spec selectType cannot be empty") private String selectType; // single, multiple @NotEmpty(message = "product spec entryMethod cannot be empty") private String entryMethod; // custom, selection @NotNull(message = "product spec categoryId cannot be empty") private Integer categoryId; private Integer sort = 0; private Boolean searchable; private String value; }
PHP
UTF-8
953
2.828125
3
[]
no_license
<?php namespace Acar\Post\Command; use Acar\Post\Command\AbstractCommand; /** * Customize class * * @author Cem AÇAR <myceykiii@gmail.com> */ class Customize extends AbstractCommand { /** * The namespace. * * @var string */ protected $namespace = "customize"; /** * Create Sorht Url * * @param $hash string * @param $customHash string * @param $longUrl string * @param $smartLink array * * @return array */ public function customSortUrl(string $hash, string $customHash = '', array $smartLink = []) { $result = [ "hash" => $hash ]; if($customHash <> ''){ $result["customHash"] = $customHash; } if(count($smartLink) > 0){ $result["smartLinks"] = "[".json_encode($smartLink,JSON_UNESCAPED_SLASHES)."]"; } return $this->get($this->namespace,$result); } }
Java
UTF-8
841
3.265625
3
[]
no_license
package OOP_Encapsulation; public class Company { private String name;//IBM private int empCount;//1000 private String hq; public String ceoName; public String getCompyInfo() {//getter of getting all comp information String info = name + empCount + hq; return info; } // setter and getter methods --> public public String getName() { return name;//IBM } public void setName(String name) { this.name = name; } public int getEmpCount() { return empCount;//1000 } public void setEmpCount(int empCount) { this.empCount = empCount; } public String getHq() { return hq; } public void setHq(String hq) { this.hq = hq; } // public static void main(String[] args) { // // Company obj = new Company(); // obj.name = "IBM"; // obj.empCount = 1000; // // System.out.println(obj.name); // // } }
Java
UTF-8
1,999
2.1875
2
[]
no_license
package br.una.laboratorio.sgate.controller; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import br.ufla.lemaf.commons.model.service.to.MessageReturnTO; import br.ufla.lemaf.commons.model.service.to.ObjectAndMessageReturnTO; import br.ufla.lemaf.commons.model.service.to.ReturnTO; import br.una.laboratorio.sgate.model.domain.entity.Servico; import br.una.laboratorio.sgate.model.service.bo.ServicoBO; import br.una.laboratorio.util.ContentBody; @Named @RequestMapping( value = "/servico/**" ) public class ServicoController extends ApplicationController { @Inject private ServicoBO bo; @RequestMapping( value = "/servico", method = RequestMethod.PUT ) public ReturnTO save( HttpServletRequest request ) { Servico servico = ContentBody.entity(request, Servico.class); return new ObjectAndMessageReturnTO<Servico>( bo.save( servico ) ); } @RequestMapping( value = "/servico", method = RequestMethod.POST ) public ReturnTO update( HttpServletRequest request ) { Servico servico = ContentBody.entity(request, Servico.class); return new ObjectAndMessageReturnTO<Servico>( bo.update( servico ) ); } @RequestMapping( value = "/servico/{id}", method = RequestMethod.GET ) public ReturnTO retrieve( @PathVariable Long id ) { return new ObjectAndMessageReturnTO<Servico>( bo.retrieve(id) ); } @RequestMapping(value = "/servico", method = RequestMethod.GET) public ReturnTO findAll() { return new ObjectAndMessageReturnTO<List<Servico>>( bo.retrieve() ); } @RequestMapping(value = "/servico", method = RequestMethod.DELETE) public ReturnTO delete( HttpServletRequest request ) { Servico servico = ContentBody.entity(request, Servico.class); bo.delete(servico); return new MessageReturnTO(); } }
Java
UTF-8
3,588
2.75
3
[ "LicenseRef-scancode-commercial-license", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-free-unknown", "LGPL-3.0-only", "GPL-3.0-only" ]
permissive
/* * Copyright (c) 2010-2021 Haifeng Li. All rights reserved. * * Smile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Smile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Smile. If not, see <https://www.gnu.org/licenses/>. */ package smile.data; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream; import smile.math.MathEx; import smile.math.matrix.SparseMatrix; /** * Binary sparse dataset. Each item is stored as an integer array, which * are the indices of nonzero elements in ascending order. * * @author Haifeng Li */ class BinarySparseDatasetImpl implements BinarySparseDataset { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BinarySparseDatasetImpl.class); /** * The data objects. */ private final int[][] data; /** * The number of nonzero entries. */ private int n; /** * The number of columns. */ private final int ncol; /** * The number of nonzero entries in each column. */ private final int[] colSize; /** * Constructor. * @param data Each row is a data item which are the indices * of nonzero elements. Every row will be sorted * into ascending order. */ public BinarySparseDatasetImpl(Collection<int[]> data) { this.data = data.toArray(new int[data.size()][]); ncol = MathEx.max(this.data) + 1; colSize = new int[ncol]; for (int[] x : this.data) { Arrays.sort(x); int prev = -1; // index of previous element for (int xi : x) { if (xi < 0) { throw new IllegalArgumentException(String.format("Negative index of nonzero element: %d", xi)); } if (xi == prev) { logger.warn(String.format("Ignore duplicated indices: %d in [%s]", xi, Arrays.toString(x))); } else { colSize[xi]++; n++; prev = xi; } } } } @Override public int size() { return data.length; } @Override public int length() { return n; } @Override public int ncol() { return ncol; } @Override public int[] get(int i) { return data[i]; } @Override public Stream<int[]> stream() { return Arrays.stream(data); } @Override public SparseMatrix toMatrix() { int[] pos = new int[ncol]; int[] colIndex = new int[ncol + 1]; for (int i = 0; i < ncol; i++) { colIndex[i + 1] = colIndex[i] + colSize[i]; } int nrow = data.length; int[] rowIndex = new int[n]; double[] x = new double[n]; for (int i = 0; i < nrow; i++) { for (int j : data[i]) { int k = colIndex[j] + pos[j]; rowIndex[k] = i; x[k] = 1; pos[j]++; } } return new SparseMatrix(nrow, ncol, x, rowIndex, colIndex); } }
PHP
UTF-8
508
3.203125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: KAB1VX2 * Date: 24/11/2017 * Time: 16:19 */ class Calculator { public static function addition($a,$b){ return $a+$b; } public static function soustraction($a,$b){ return $a-$b; } public static function multiplication($a,$b){ return $a*$b; } public static function puissance($a,$b){ return pow($a,$b); } public static function reste_division($a,$b){ return fmod ( $a , $b); } }
Python
UTF-8
2,628
3.875
4
[]
no_license
#!/usr/bin/python #coding:utf-8 # // 面试题34:二叉树中和为某一值的路径 # // 题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所 # // 有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 层次遍历 def levelOrder(self, root): """ :type root: TreeNode :rtype: int """ # 从根开始遍历,每层写入一个新数组 # 在将left ,right写入下次需要巡皇的数组 # 循环完成即可得到每层的数组 queue = [root] res = [] if not root: return [] while queue: templist = []#此层的数组 templen =len(queue) for i in range(templen): temp = queue.pop(0) templist.append(temp.val) if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) # print(templist) res.append(templist) return res def pathSum(self, root, target) : if not root: return None res = [] def dfs(root,tmp): if not root.left and not root.right: if sum(tmp)== target: res.append(tmp) if root.left: dfs(root.left,tmp+[root.left.val]) if root.right: dfs(root.right,tmp+[root.right.val]) dfs(root,[root.val]) return res def pathSum(self, root, target) : if not root:return None re = [] def bt(r, sum, path): if not r: return None sum+=r.val path.append(r.val) if not r.left and not r.right: if sum==target: re.append(path[:]) #这里必须把path[:]拷贝一份,不然pop()时re中的结果会变化 bt(r.left, sum, path) bt(r.right, sum, path) path.pop() bt(root,0,[]) return re # 测试树 # 10 # 5 9 # 4 7 t1 = TreeNode(10) t2 = TreeNode(5) t3 = TreeNode(9) t4 = TreeNode(4) t5 = TreeNode(7) root = t1 root.left = t2 root.right = t3 t2.left = t4 t2.right = t5 obj = Solution() re = obj.levelOrder(root) # for i in range(len(re)): # print(re[i]) # print("\n") print(obj.pathSum(t1, 19))
C++
UTF-8
819
2.921875
3
[]
no_license
// // main.cpp // Lab8 // // Created by Георгий Круглов on 11.02.2021. // #include <iostream> #include <vector> #include <numeric> using namespace std; int main(int argc, const char * argv[]) { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n; cin >> n; vector<vector<int>> array; array.resize(n); for (int i = 0; i < n; i++) { array[i].resize(n); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> array[i][j]; } } for (int i = 0; i < n - 1; i++) { for (int j = i; j < n; j++) { if (array[i][j] != array[j][i] || (i == j && array[i][j] != 0)) { cout << "NO"; exit(0); } } } cout << "YES"; return 0; }
Shell
UTF-8
1,098
2.625
3
[]
no_license
#!/bin/bash s1=cow;s2=dog; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=cow;s2=human; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=cow;s2=mouse; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=cow;s2=rat; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=dog;s2=human; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=dog;s2=mouse; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=dog;s2=rat; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=human;s2=mouse; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=human;s2=rat; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}' s1=mouse;s2=rat; echo ${s1}_${s2} cat result_${s1}_${s2}.txt | awk '{sum+=$4} END {print "avg = ", sum/NR}'
C#
UTF-8
1,019
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using LeaderboardAPI.Models; using LeaderboardAPI.Database; namespace LeaderboardAPI.Repositories { public class ScoreRepository : IScoreRepository { private readonly LeaderAPIDbContext _LeaderAPIDbContext; public ScoreRepository(LeaderAPIDbContext leaderAPIDbContext) { _LeaderAPIDbContext = leaderAPIDbContext; } public Score GetScore(int id) => _LeaderAPIDbContext.Scores.FirstOrDefault(c => c.ScoreId == id); public IEnumerable<Score> GetScores() => _LeaderAPIDbContext.Scores.ToList(); public void AddScore(Score score) { _LeaderAPIDbContext.Scores.Add(score); _LeaderAPIDbContext.SaveChanges(); } public void DeleteScore(int id) { _LeaderAPIDbContext.Remove(GetScore(id)); _LeaderAPIDbContext.SaveChanges(); } } }
Java
UTF-8
3,122
2.0625
2
[]
no_license
package com.example.myapplication.Models; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.example.myapplication.R; public class Config { public static final String Home = "home"; public static final String EditProfil = "editprofil"; public static final String TAG1 = "volley_response"; public static final String TAG2 = "volley_response_json"; public static final String TAG3 = "firestore_response"; public static final String cameroonFlag = "+237"; private static AlertDialog show; private static ProgressDialog progressDialog; public static final String signIn = "http://api-dev.montaxii.com/api/v1/drivers/login"; public static final String changePassword = "http://api-dev.montaxii.com/api/v1/drivers/change-password"; public static final String recoveraccount = "http://api-dev.montaxii.com/api/v1/drivers/recover-account"; public static final String chatcomment = "http://api-dev.montaxii.com/api/v1/comments"; public static final String resetPassword = "http://api-dev.montaxii.com/api/v1/drivers/reset-password"; public static final String resetProfil = "http://api-dev.montaxii.com/api/v1/drivers/drivers/"; public static void Alert(Context context, String message, boolean success){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final AlertDialog.Builder builder = new AlertDialog.Builder(context); View layoutView = inflater.inflate(R.layout.alertnotification, null); builder.setView(layoutView); TextView textView = (TextView)layoutView.findViewById(R.id.message); textView.setText(message); if (success) textView.setTextColor(context.getResources().getColor(R.color.commentsent)); else textView.setTextColor(context.getResources().getColor(R.color.red)); show = builder.show(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { show.dismiss(); } }, 3000); } public static void dismiss(){ show.dismiss(); } public static void ProgressDialog(Context context){ progressDialog = new ProgressDialog(context, R.style.AppTheme_Dark_Dialog); progressDialog.setIndeterminate(true); progressDialog.setCancelable(true); } public static void showDialog(String message){ progressDialog.setMessage(message); progressDialog.show(); } public static void hideDialog(){ if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } public static void showProgressDialog(View view){ view.setVisibility(View.VISIBLE); } public static void hideProgressDialog(View view){ view.setVisibility(View.GONE); } }
PHP
UTF-8
10,017
2.59375
3
[]
no_license
<?php /** * The kevindeviceModel * * @copyright Kevin * @author kevin<3301647@qq.com> * @package kevindevice */ ?> <?php class kevindeviceModel extends model { /** * Create a user. * * @access public * @return void */ public function devcreate() { $device = fixer::input('post') ->setDefault('join', '0000-00-00') ->get(); if (!$device->group) $device->group = 0; $this->dao->insert(TABLE_KEVINDEVICE_DEVLIST)->data($device) ->autoCheck() ->batchCheck($this->config->kevindevice->devcreate->requiredFields, 'notempty') ->check('nametype', 'unique') ->exec(); if (dao::isError()) return; } /** * Delete a user. * * @param int $deviceid * @access public * @return void */ public function devdelete($deviceid) { $this->dao->update(TABLE_KEVINDEVICE_DEVLIST)->set('deleted = 1') ->where('id')->eq((int) $deviceid) ->exec(); //$this->dao->delete()->from(TABLE_KEVINDEVICE_DEVLIST)->where('id')->eq($deviceid)->exec(); //$this->dao->delete()->from(TABLE_KEVINDEVICE_GROUPLIST)->where('`user`')->eq($deviceid)->exec(); } /** * Get user info by ID. * * @param int $deviceid * @access public * @return object|bool */ public function devGetById($deviceid) { $device = $this->dao->select('*')->from(TABLE_KEVINDEVICE_DEVLIST)->where('id')->eq($deviceid)->fetch(); return $device; } public function devStatusCheck(){ $dismatches=$this->dao->select('a.id,a.status,a.group,b.type')->from(TABLE_KEVINDEVICE_DEVLIST)->alias('a') ->leftJoin(TABLE_KEVINDEVICE_GROUP)->alias('b')->on('a.group = b.id') ->where('a.status')->eq('discard') ->orWhere('b.type')->eq('discard') ->fetchAll(); $group=$this->dao->select('id')->from(TABLE_KEVINDEVICE_GROUP)->where('type')->eq('discard')->fetch(); foreach($dismatches as $dismatch){ if($dismatch->status!=$dismatch->type){ if($dismatch->status=='discard') $this->dao->update(TABLE_KEVINDEVICE_DEVLIST)->set('group')->eq((int)$group->id) ->where('id')->eq($dismatch->id)->andWhere('deleted')->eq(0) ->exec(); elseif($dismatch->type=='discard') $this->dao->update(TABLE_KEVINDEVICE_DEVLIST)->set('status')->eq('normal') ->where('id')->eq($dismatch->id)->andWhere('deleted')->eq(0) ->exec(); } } } /** * Get devices by sql. * * @param int $query * @param int $pager * @access public * @return void */ public function devGetByQuery($groupID = 0, $pager = null, $orderBy = 'id') { $this->devStatusCheck(); if ($groupID) { return $this->dao->select('a.*,b.name as groupName,c.name as deptName') ->from(TABLE_KEVINDEVICE_DEVLIST)->alias('a') ->leftJoin(TABLE_KEVINDEVICE_GROUP)->alias('b')->on('a.group = b.id') ->leftJoin(TABLE_DEPT)->alias('c')->on('a.dept = c.id') ->where('a.group')->eq((int) $groupID) ->andWhere('a.deleted')->eq(0) ->orderBy($orderBy) ->page($pager) ->fetchAll(); } //no group select all return $this->dao->select('a.*,b.name as groupName,c.name as deptName')->from(TABLE_KEVINDEVICE_DEVLIST)->alias('a') ->leftJoin(TABLE_KEVINDEVICE_GROUP)->alias('b')->on('a.group = b.id') ->leftJoin(TABLE_DEPT)->alias('c')->on('a.dept = c.id') ->Where('a.deleted')->eq(0) ->orderBy($orderBy) ->page($pager) ->fetchAll(); } /** * Get devices by sql. * * @param int $query * @param int $pager * @access public * @return void */ public function devGetByGroup($groupID = 0, $orderBy = 'name') { if ($groupID) { return $this->dao->select('*') ->from(TABLE_KEVINDEVICE_DEVLIST) ->where('`group`')->eq((int) $groupID) ->andWhere('deleted')->eq(0) ->orderBy($orderBy) ->fetchAll(); } return null; } /** * Get user pairs of a group. * * @param int $groupID * @access public * @return array */ public function devGetPairs($groupID = 0) { if (0 == $groupID) { return $this->dao->select('id,name') ->from(TABLE_KEVINDEVICE_DEVLIST) ->Where('deleted')->eq(0) ->orderBy('name') ->fetchPairs(); } return $this->dao->select('id,name') ->from(TABLE_KEVINDEVICE_DEVLIST) ->where('`group`')->eq((int) $groupID) ->andWhere('deleted')->eq(0) ->orderBy('name') ->fetchPairs(); } /** * Update a user. * * @param int $deviceid * @access public * @return void */ public function devupdate($deviceid) { $oldUser = $this->devGetById($deviceid); if (!$oldUser) return; $deviceid = (int) $deviceid; $device = fixer::input('post') ->setDefault('join', '0000-00-00') ->get(); if (!$device->group) $device->group = 0; $this->dao->update(TABLE_KEVINDEVICE_DEVLIST)->data($device) ->autoCheck() ->batchCheck($this->config->kevindevice->devedit->requiredFields, 'notempty') ->where('id')->eq((int) $deviceid) ->exec(); if (dao::isError()) return; } /** * Create a group. * * @access public * @return bool */ public function groupcreate() { $group = fixer::input('post')->get(); return $this->dao->insert(TABLE_KEVINDEVICE_GROUP)->data($group)->batchCheck($this->config->kevindevice->groupcreate->requiredFields, 'notempty')->exec(); } /** * Copy a group. * * @param int $groupID * @access public * @return void */ public function groupcopy($groupID) { $group = fixer::input('post')->remove('options')->get(); $this->dao->insert(TABLE_KEVINDEVICE_GROUP)->data($group)->check('name', 'unique')->check('name', 'notempty')->exec(); if ($this->post->options == false) return; if (!dao::isError()) { $newGroupID = $this->dao->lastInsertID(); $options = join(',', $this->post->options); if (strpos($options, 'copyPriv') !== false) $this->copyPriv($groupID, $newGroupID); if (strpos($options, 'copyUser') !== false) $this->copyUser($groupID, $newGroupID); } } /** * Delete a group. * * @param int $groupID * @param null $null compatible with that of model::delete() * @access public * @return void */ public function groupdelete($groupID, $null = null) { $this->dao->update(TABLE_KEVINDEVICE_GROUP)->set('deleted = 1') ->where('id')->eq((int) $groupID) ->exec(); //$this->dao->delete()->from(TABLE_KEVINDEVICE_GROUP)->where('id')->eq($groupID)->exec(); } /** * Get group by id. * * @param int $groupID * @access public * @return object */ public function groupGetById($groupID) { return $this->dao->findById($groupID)->from(TABLE_KEVINDEVICE_GROUP)->fetch(); } /** * Get group by userID. * * @param int $deviceid * @access public * @return array */ public function groupGetByDevice($deviceid) { return $this->dao->select('a.*')->from(TABLE_KEVINDEVICE_GROUP)->alias('a') ->leftJoin(TABLE_KEVINDEVICE_DEVLIST)->alias('b') ->on('a.id = b.group') ->where('b.id')->eq($deviceid) ->fetchAll('id'); } /** * Get group lists. * * @access public * @return array */ public function groupGetList() { return $this->dao->select('*')->from(TABLE_KEVINDEVICE_GROUP)->orderBy('id')->fetchAll(); } /** * Update a group. * * @param int $groupID * @access public * @return void */ public function groupUpdate($groupID) { $group = fixer::input('post')->get(); return $this->dao->update(TABLE_KEVINDEVICE_GROUP)->data($group) ->batchCheck($this->config->kevindevice->nameRequire->requiredFields, 'notempty') ->where('id')->eq($groupID)->exec(); } /** * Get kevindevice pairs. * * @access public * @return array */ public function groupGetPairs() { return $this->dao->select('id, name')->from(TABLE_KEVINDEVICE_GROUP)->fetchPairs(); } /** * Update devices. * * @param int $groupID * @access public * @return void */ public function groupUpdateUser($groupID) { /* Delete old. */ $this->dao->delete()->from(TABLE_KEVINDEVICE_GROUPLIST)->where('`group`')->eq($groupID)->exec(); /* Insert new. */ if ($this->post->members == false) return; foreach ($this->post->members as $userid) { $data = new stdclass(); $data->user = $userid; $data->group = $groupID; $this->dao->insert(TABLE_KEVINDEVICE_GROUPLIST)->data($data)->exec(); } } /** * statistic By Group. * * @access public * @return array */ public function statisticByGroup() { return $this->dao->select('count(*) as deviceCount, `group`,b.name as groupName') ->from(TABLE_KEVINDEVICE_DEVLIST)->alias('a') ->leftJoin(TABLE_KEVINDEVICE_GROUP)->alias('b')->on('a.group = b.id') ->where('a.deleted')->eq('0') ->groupBy('`group`') ->orderBy('group') ->fetchAll(); } /** * statistic By dept. * * @access public * @return array */ public function statisticByDept() { return $this->dao->select('count(*) as deviceCount, `group`,b.name as groupName,b.id as groupID') ->from(TABLE_KEVINDEVICE_DEVLIST)->alias('a') ->leftJoin(TABLE_DEPT)->alias('b')->on('a.dept = b.id') ->where('a.deleted')->eq('0') ->groupBy('`dept`') ->orderBy('dept') ->fetchAll(); } /** * statistic By dept. * * @access public * @return array */ public function statisticByType() { return $this->dao->select('count(*) as deviceCount, b.type as groupName') ->from(TABLE_KEVINDEVICE_DEVLIST)->alias('a') ->leftJoin(TABLE_KEVINDEVICE_GROUP)->alias('b')->on('a.group=b.id') ->where('a.deleted')->eq('0') ->groupBy('b.type') ->orderBy('b.type') ->fetchAll(); } }
PHP
UTF-8
4,134
2.609375
3
[]
no_license
<?php if(isset($_GET['p_id'])){ $edit_post_id = $_GET['p_id']; // Show posts from database $edit_post_query = "SELECT * FROM posts WHERE post_id = $edit_post_id "; $edit_query_result = mysqli_query($connection,$edit_post_query); while($row = mysqli_fetch_assoc($edit_query_result)){ $edit_title = $row['post_title']; $edit_author = $row['post_author']; $edit_status = $row['post_status']; $edit_post_cat_id = $row['post_cat_id']; $edit_img = $row['post_img']; $edit_tags = $row['post_tags']; $edit_content = $row['post_content']; $edit_comment_count = $row['post_comment_count']; $edit_date = $row['post_date']; } } if(isset($_POST['update_post'])){ $post_id = $_GET['p_id']; $post_title = $_POST['title']; $post_author = $_POST['author']; $post_category_id = $_POST['post_category']; $post_status = $_POST['post_status']; $post_img = $_FILES['post_img']['name']; $post_img_tmp = $_FILES['post_img']['tmp_name']; $post_tags = $_POST['post_tags']; $post_content = $_POST['post_content']; move_uploaded_file($post_img_tmp,"../images/$post_img"); if(empty($post_img)){ $img_query = "SELECT * FROM posts WHERE post_id = $post_id "; $result_img_query = mysqli_query($connection,$img_query); while($row = mysqli_fetch_assoc($result_img_query)){ $post_img = $row['post_img']; } } $update_post_query = "UPDATE posts SET post_title = '$post_title', post_author = '$post_author', post_cat_id = '$post_category_id', post_date = now(), post_img = '$post_img', post_status = '$post_status', post_tags = '$post_tags', post_content = '$post_content' WHERE post_id = $post_id "; $update_query_result = mysqli_query($connection,$update_post_query); confirm_query($update_query_result); echo "<b>Post Updated.</b>"." "."<a href='../post.php?p_id=$post_id'>View Post</a> <b>or</b> <a href='posts.php'>Edit More Posts</a>"; echo '</br></br>'; } ?> <form action="" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Post Title</label> <input type="text" value="<?php echo $edit_title; ?>" name="title" class="form-control" placeholder="Enter Post Title"> </div> <div class="form-group"> <label for="categories">Categories</label> <select name="post_category" class="form-control"> <?php $query = "SELECT * FROM categories "; $select_cat = mysqli_query($connection,$query); confirm_query($select_cat); while($row = mysqli_fetch_assoc($select_cat)){ $cat_id = $row['cat_id']; $cat_title = $row['cat_title']; if($cat_id == $edit_post_cat_id){ echo "<option selected value='$cat_id'>$cat_title</option>"; } else { echo "<option value='$cat_id'>$cat_title</option>"; } } ?> </select> </div> <div class="form-group"> <label for="author">Post Author</label> <input type="text" value="<?php echo $edit_author; ?>" name="author" class="form-control" placeholder="Enter Post Author"> </div> <option value=""></option> <div class="form-group"> <label for="post_status">Post Status</label> <select name="post_status" class='form-control'> <option selected value='<?php echo $edit_status; ?>'><?php echo $edit_status; ?></option> <?php if($edit_status == 'published'){ echo "<option value='draft'>Draft</option>"; } else { echo "<option value='published'>Published</option>"; } ?> </select> </div> <div class="form-group"> <label for="post_img">Post Image</label><br> <img src="../images/<?php echo $edit_img; ?>" alt="image" class="img-small"><br><br> <input type="file" name="post_img"> </div> <div class="form-group"> <label for="post_tags">Post Tags</label> <input type="text" value="<?php echo $edit_tags; ?>" name="post_tags" class="form-control" placeholder="Enter Post Tags"> </div> <div class="form-group"> <label for="post_content">Post Content</label> <textarea name="post_content" class="form-control" placeholder="Write..." cols="30" rows="10" id="editor"><?php echo $edit_content; ?></textarea> </div> <div class="form-group"> <input type="submit" value="Update" name="update_post" class="btn btn-primary"> </div> </form>
Shell
UTF-8
53,657
3.234375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash # -*- shell-script -*- # Copyright (C) 2008-2013 Bob Hepple # 2014 StudioEtrange # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # http://sourceforge.net/projects/argpsh # http://bhepple.freeshell.org/oddmuse/wiki.cgi/arpg # Certainly would not work on plain old sh, csh, ksh ... . # Modified by StudioEtrange # * modification of the way to declare option and parameter # * support mandatory option # * check validity of parameter (foo.sh parameter -option) # * remove generation of man page # * lot of tweaks # * getopt command is now a parameter, # and could be a pure bash implementation if we choose "PURE_BASH" # from Aron Griffis https://github.com/agriffis/pure-getopt # TODO : refactoring of read_xml ARGP_argp_sh_usage() { cat <<"EOF" Usage: argp.sh A wrapper for getopt(1) which simulates argp(3) for bash. Normally other scripts pipe their option descriptions in here for automatic help and man mpage production and for generating the code for getopt(1). Requires bash-3+. See also argp(1) which is a binary (and much faster) version of this. See http://sourceforge.net/projects/argpsh See http://bhepple.freeshell.org/oddmuse/wiki.cgi/argp It buys you: o all the goodness of getopt o define options and parameters in one central place together with descriptions. o fewer 'magic' and duplicated values in your code o better consistency between the getopt calling parameters, the case statement processing the user's options and the help/man pages o less spaghetti in your own code o easier to maintain o checking of option and parameter consistency at runtime o range checking of option and parameter values at runtime o pretty easy to use o portable to OS's without long option support - the help page adapts too ############# USAGE ########################### The full usage is something like this assuming the option description is in the variable STRING (in flat as above or in XML) : STRING=" --HEADER-- ARGP_PROG=my-script-name # this defines the program's version string to be displayed by the -V option: ARGP_VERSION=1.6 # delete '--quiet' and '--verbose' built-in options (quiet, verbose, help are default built-in options) ARGP_DELETE=quiet verbose # if this is set then multiple invocations of a string or array option will # be concatenated using this separator eg '-s s -s b' will give 'a:b' ARGP_OPTION_SEP=: ARGP_SHORT=This is a short description for the first line of the man page. ARGP_LONG_DESC= This is a longer description. Spring the flangen dump. Spring the flingen dump. Spring the flangen dump. Spring the flingen dump. --OPTIONS-- #NAME=DEFAULT 'SHORT_NAME' 'LABEL' TYPE MANDATORY 'RANGE' DESCRIPTION # An hidden option (looks like : --hidden) which does not appear in the help # pages. It is a simple flag (boolean) with a default # value of '' and 'set' if --hidden is on the command line. HIDDEN='' '' '' b 0 '' # a boolean option with a short name and a numeric default which is # incremented every time the --bool, -b option is given: BOOL='0' 'b' '' b 0 '' description of this option # this is a (boolean) flag which gets set to the string 'foobar' when # --flag, -f is on the command line otherwise it is set to 'barfoo': FLAG='barfoo' 'f' '' b 0 'foobar' a flag # here is an integer value option which must sit in a given range: INT=1 'i' 'units' i 0 '1:3' an integer # here is an array value ie just a string which must take one of # the values in the 'range': ARRAY=a 'a' 'widgets' a 0 'a b' an array # this option is a simple string which will be checked against a regex(7): STRING='' 's' 'string' s 0 '^foo.*bar$|^$' a string # a double value which is checked against a range: DOUBLE=1 'd' 'miles' d 0 '0.1:1.3' a double # this is a URL which will be checked against the URL regex and has a # default value URL='http://www.foobar.com' 'u' 'url' u 0 '' a url # this uses the same short letter 'q' as the --quiet option which was # deleted above QUAINT='' 'q' '' s 0 '' a quaint description --PARAMETERS-- #NAME= 'LABEL' TYPE 'RANGE' DESCRIPTION ACTION= '' a 'build run' Action to compute. " exec 4>&1 eval $( echo "$STRING" | ./argp.sh "$@" 3>&1 1>&4 || echo exit $? ) exec 4>&- # $@ now contains args not processed. Parameters and options have been processed and removed. ############################ DEFINITION OF OPTIONS ############################ name=default : name must be present and unique. default may be '' for boolean type, default value is 0 sname : the single-letter short name of the option (use '' if not needed) label : the name of this option to be used in --help. If empty, it will be autogenerated depending on the type (do not use label for booleans, leave it empty with '') type : i (integer) d (double) s[:] (string) a[:] (array) a value to pick in a list of valid string u (url) b (boolean) When used a boolean option is set to the range value (if range value is not setted the boolean is set to +1 each time it is used -b -b -b will be set to 3), When a boolean option is not used on command line, it is set to the default value (if default value is not setted, then the value option is empty) If 's:' or 'a:' then ':' overrides ARGP_OPTION_SEP for this option. Any syntactically clean string can be used instead of ':' (ie not ' or ".) mandatory : 1 for mandatory option 0 for non mandatory option range : for numeric options (type i, d): min-max eg 1.2-4.5 for string options (type s) : an extended regexp for array options : a space separated list of alternates. array type must have a range specified. for boolean options : the value to assign the option when set (default is 1) for url options : do not use. argp use an internal fixed regexp desc : long description of this option leave empty for hidden options long description could use '\' at the end of each line ############################ DEFINITION OF PARAMETERS ############################ name : name must be present and unique. label : the name of the parameter to be used in --help. If empty, it will be autogenerated depending on the type type : i (integer) d (double) s (string) a (array) a value to pick in a list of valid string u (url) range : for numeric parameters (type i, d): min-max eg 1.2-4.5 for string parameters (type s) : an extended regexp for array parameters : a space separated list of alternates. array type must have a range specified. for url parameters : do not use. argp use an internal fixed regexp desc : long description of this parameter. long description could use '\' at the end of each line ############################################################################### XML can also be instead of the above (provided xmlstarlet is available): <?xml version="1.0" encoding="UTF-8"?> <argp> <prog>fs</prog> <short>Search for filenames in sub-directories (short description)</short> <delete>quiet</delete> <version>1.2</version> <usage>long description</usage> <parameter name="ACTION" type="s" mandatory="1" label="" range="build run">command</parameter> <option name="EXCLUDE" sname="x" type="s" mandatory="0" arg="directory">exclude directory</option> <option name="DIR" sname="d" type="b" mandatory="0" default="f" range="d">search for a directory rather than a file</option> <option name="SECRET" type="b"/> </argp> Note that the attribute 'name' is required - the others are all optional. Also the option value should be on a single line (the program usage can be on multiple lines). ############################################################################### Note that --verbose, --help, --quiet and --version options will be added automatically. Use ARGP_DELETE to disable them. Also, a hidden option '--print-xml' prints out the XML equivalent of the argp input. If POSIXLY_CORRECT is set, then option parsing will end on the first non-option argument (eg like ssh(1)). GETOPT_CMD is an env variable we can choose a getopt command instead of default getopt if GETOPT_CMD equal PURE_BASH, then a pure bash getopt implementation from Aron Griffis is used (https://github.com/agriffis/pure-getopt) ############################################################################### ############################################################################### Here is a sample of the output when the command is called with --help: Usage: my-script [OPTION...] [--] [parameters] This is a longer description. Spring the flangen dump. Spring the flingen dump. Spring the flangen dump. Spring the flingen dump." Parameters : Options: -a, --array=<widgets> an array Must be of type 'a'. Must be in the range 'a b'. -b, --bool description of this option -d, --double=<miles> a double. Must be of type 'd'. Must be in the range '0.1:1.3'. -f, --flag a flag -i, --int=<units> an integer. Must be of type 'i'. Must be in the range '1:3'. -q, --quaint a quaint description Must fit the regex ''. -s, --string=<string> a string. Must fit the regex '^foo.*bar$|^$'. -u, --url=<url> a url. Must fit the regex '^(nfs|http|https|ftp|file)://[[:alnum:]_.-]*[^[:space:]]*$'. -v, --verbose be verbose -h, --help print this help message -V, --version print version and exit EOF } argp_sh_version() { echo "$GARGP_VERSION" } print_array() { let n=0 for i in "$@"; do printf %s " [$n]='$i'"; let n+=1; done } debug_args() { { local i printf %s "${FUNCNAME[1]} " print_array "$@" echo } >&2 } abend() { STAT=$1; shift default_usage echo "* ERROR *" local FMT="fmt -w $GARGP_RMARGIN" type fmt &> /dev/null || FMT=cat echo "$ARGP_PROG: $@" | $FMT >&2 echo "exit $STAT;" >&3 exit $STAT } add_param() { local NAME DESC TYPE RANGE MANDATORY LABEL ORIGINAL_NAME NAME=$(convert_to_env_name "$1") ORIGINAL_NAME="$1" # original name of the param LABEL="${2:-}" # argument label - optional TYPE="${3:-}" # type of the argument - optional MANDATORY=1 RANGE="${4:-}" # range for the argument - optional DESC="${5:-}" local ALLOWED_CHARS='[a-zA-Z0-9_][a-zA-Z0-9_]*' local PARAM local OPT [[ "$ARGP_DEBUG" ]] && debug_args "$@" [[ "$NAME" ]] || abend 1 "$ARGP_PROG: argp.sh: add_param requires a name" # [[ "$NAME" =~ $ALLOWED_CHARS ]] || { ... this needs bash-3 [[ `echo $NAME |tr -d '[:alnum:]' |tr -d '[_]'` ]] && { abend 1 "argp.sh: add_param: NAME (\"$NAME\") must obey the regexp $ALLOWED_CHARS" } # check it's not already in use for PARAM in ${ARGP_PARAM_LIST:-}; do if [[ "$NAME" = "$PARAM" ]]; then abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: param name \"$NAME\" is already in use" fi done for OPT in ${ARGP_OPT_LIST:-}; do if [[ "$NAME" = "$PARAM" ]]; then abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: param name \"$NAME\" is already in use" fi done export ARGP_ORIGINAL_NAME_$NAME="$ORIGINAL_NAME" if [[ "$DESC" ]]; then export ARGP_DESC_PARAM_$NAME="$DESC" fi export ARGP_MANDATORY_$NAME="$MANDATORY" [[ "$LABEL" ]] && export ARGP_LABEL_$NAME="$LABEL" TYPE=$(echo $TYPE| tr 'A-Z' 'a-z') # use a while loop just for the 'break': while true; do case "$TYPE" in i) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="integer" [[ "$RANGE" ]] || break echo "$RANGE" | egrep -q "$GARGP_INT_RANGE_REGEX" && break ;; d) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="double" [[ "$RANGE" ]] || break echo "$RANGE" | egrep -q "$GARGP_FLOAT_RANGE_REGEX" && break ;; s) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="string" [[ "$RANGE" ]] || break # just test the regex: echo "" | egrep -q "$RANGE" [[ $? -eq 2 ]] || break ;; a) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="string" [[ "$RANGE" ]] || abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: array type must have a list of value for parameter '$ORIGINAL_NAME'." break ;; url) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="url" local SEP=${TYPE:1:1} TYPE=s$SEP RANGE="$GARGP_URL_REGEX" break ;; s*|a*|b) abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: illegal argument type ('$TYPE') for parameter '$ORIGINAL_NAME'." break ;; *) abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: need type for parameter '$ORIGINAL_NAME'." break ;; esac abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: bad type ('$TYPE') or range ('$RANGE') for parameter '$ORIGINAL_NAME'." done export ARGP_TYPE_$NAME="$TYPE" export ARGP_RANGE_$NAME="$RANGE" ARGP_PARAM_LIST="${ARGP_PARAM_LIST:-} $NAME" } add_opt() { local NAME DEFAULT DESC SOPT LABEL LOPT TYPE RANGE MANDATORY ORIGINAL_NAME ORIGINAL_NAME="$1" # ie (debug) NAME=$(convert_to_env_name "$1") # ie (debug => DEBUG) LOPT=$(convert_to_option_name "$1") # long name in 'command line option style' (ie ARGP_DEBUG => argp-debug) DEFAULT=${2:-} SOPT="${3:-}" # short option letter - optional LABEL="${4:-}" # argument label - optional TYPE="${5:-}" # type of the argument - optional MANDATORY="${6:-}" # mandatory or not - optional RANGE="${7:-}" # range for the argument - optional DESC="${8:-}" # if not set, the option is considered as hidden local ALLOWED_CHARS='[a-zA-Z0-9_][a-zA-Z0-9_]*' local OPT local PARAM [[ "$ARGP_DEBUG" ]] && debug_args "$@" [[ "$NAME" ]] || abend 1 "$ARGP_PROG: argp.sh: add_opt requires a name" # [[ "$NAME" =~ $ALLOWED_CHARS ]] || { ... this needs bash-3 [[ `echo $NAME |tr -d '[:alnum:]' |tr -d '[_]'` ]] && { abend 1 "argp.sh: apt_opt: NAME (\"$NAME\") must obey the regexp $ALLOWED_CHARS" } export ARGP_ORIGINAL_NAME_$NAME="$ORIGINAL_NAME" export ARGP_DEFAULT_$NAME="$DEFAULT" # check it's not already in use for OPT in ${ARGP_OPTION_LIST:-}; do if [[ "$NAME" = "$OPT" ]]; then abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: option name \"$NAME\" is already in use" fi # check that the (short) option letter is not already in use: if [[ "$SOPT" ]]; then if [[ "$SOPT" == "$(get_opt_letter $OPT)" ]]; then abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: short option \"$SOPT\" is already in use by $OPT" fi fi done for PARAM in ${ARGP_PARAM_LIST:-}; do if [[ "$NAME" = "$PARAM" ]]; then abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: opt name \"$NAME\" is already in use" fi done if [[ "$SOPT" ]]; then [[ ${#SOPT} -ne 1 ]] && { abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: short option \"$SOPT\" for option $ORIGINAL_NAME is not a single character" } export ARGP_SOPT_$NAME="$SOPT" fi export ARGP_LOPT_$NAME="$LOPT" if [[ "$DESC" ]]; then export ARGP_DESC_OPT_$NAME="$DESC" fi if [[ "$MANDATORY" == "1" ]]; then export ARGP_MANDATORY_$NAME="1" else export ARGP_MANDATORY_$NAME="0" fi [[ "$LABEL" ]] && export ARGP_LABEL_$NAME="$LABEL" TYPE=$(echo $TYPE| tr 'A-Z' 'a-z') # use a while loop just for the 'break': while true; do case "$TYPE" in b) [[ "$LABEL" ]] && abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: boolean type can not have label for option '$ORIGINAL_NAME'." [[ "$DEFAULT" ]] || export ARGP_DEFAULT_$NAME="" export ARGP_LABEL_$NAME= break ;; i) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="integer" [[ "$RANGE" ]] || break echo "$RANGE" | egrep -q "$GARGP_INT_RANGE_REGEX" && break ;; d) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="double" [[ "$RANGE" ]] || break echo "$RANGE" | egrep -q "$GARGP_FLOAT_RANGE_REGEX" && break ;; s*) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="string" [[ "$RANGE" ]] || break # just test the regex: echo "" | egrep -q "$RANGE" [[ $? -eq 2 ]] || break ;; a) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="string" [[ "$RANGE" ]] || abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: array type must have a list of value for option '$ORIGINAL_NAME'." break ;; url) [[ "$LABEL" ]] || export ARGP_LABEL_$NAME="url" local SEP=${TYPE:1:1} TYPE=s$SEP RANGE="$GARGP_URL_REGEX" break ;; *) abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: need type for option '$ORIGINAL_NAME'." break ;; esac abend 1 "$ARGP_PROG: argp.sh: $FUNCNAME: bad type ('$TYPE') or range ('$RANGE') for option '$ORIGINAL_NAME'." done export ARGP_TYPE_$NAME="$TYPE" export ARGP_RANGE_$NAME="$RANGE" ARGP_OPTION_LIST="${ARGP_OPTION_LIST:-} $NAME" } get_opt_letter() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_SOPT_$NAME" printf %s "${!L:-}" [[ "$ARGP_DEBUG" ]] && echo "returning ${!L:-}" >&2 } # get original name of parameter get_param_original_name() { get_opt_original_name "$@" } # get original name of option get_opt_original_name() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_ORIGINAL_NAME_$NAME" printf %s "${!L:-}" } get_opt_long_name() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_LOPT_$NAME" printf %s "${!L:-}" } get_param_label() { get_opt_label "$@" } # option label get_opt_label() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_LABEL_$NAME" printf %s "${!L:-}" } # convert an environment name (eg ARGP_DEBUG) to a long option name (eg argp-debug) convert_to_option_name() { echo "$1" | tr '[:upper:]_' '[:lower:]-' } convert_to_env_name() { echo "$1" | tr '[:lower:]-' '[:upper:]_' } get_opt_type() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local T="ARGP_TYPE_$NAME" printf %s "${!T:-}" } get_param_type() { get_opt_type "$@" } get_opt_mandatory() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local T="ARGP_MANDATORY_$NAME" printf %s "${!T:-}" } get_param_range() { get_opt_range "$@" } get_opt_range() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local R="ARGP_RANGE_$NAME" printf %s "${!R:-}" } get_opt_default() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local D=ARGP_DEFAULT_$NAME local DEFAULT="${!D}" printf %s "${DEFAULT:-}" } get_opt_short_desc() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_DESC_OPT_$NAME" printf %s "${!L:-}" } get_param_short_desc() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_DESC_PARAM_$NAME" printf %s "${!L:-}" } get_param_desc() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_DESC_PARAM_$NAME" printf %s "${!L:-}" local TYPE=$(get_param_type "$NAME") local RANGE=$(get_param_range "$NAME") local MANDATORY=1 if [[ "$MANDATORY" == "1" ]]; then echo -n " Mandatory." fi if [[ "$TYPE" && "$TYPE" != "b" && "$TYPE" != "h" ]]; then if [[ "$TYPE" != s* || "$RANGE" ]]; then if [[ "$TYPE" != s* && "$TYPE" != "a" ]]; then echo -n " Must be of type '$TYPE'." fi if [[ "$RANGE" ]]; then case "$TYPE" in s*|S*) echo -n " Must fit the regex '$RANGE'." ;; a) echo -n " Must be one of these values '$RANGE'." ;; *) echo -n " Must be in the range '$RANGE'." ;; esac fi fi fi } get_opt_desc() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local NAME="$1" local L="ARGP_DESC_OPT_$NAME" printf %s "${!L:-}" local TYPE=$(get_opt_type "$NAME") local RANGE=$(get_opt_range "$NAME") local MANDATORY=$(get_opt_mandatory "$NAME") if [[ "$MANDATORY" == "1" ]]; then echo -n " Mandatory." fi DEFAULT=$(get_opt_default "$NAME") [[ "$DEFAULT" ]] && echo -n " Default is '$DEFAULT'." if [[ "$TYPE" && "$TYPE" != "b" && "$TYPE" != "h" ]]; then if [[ "$TYPE" != s* || "$RANGE" ]]; then if [[ "$TYPE" != s* && "$TYPE" != "a" ]]; then echo -n " Must be of type '$TYPE'." fi if [[ "$RANGE" ]]; then case "$TYPE" in s*|S*) echo -n " Must fit the regex '$RANGE'." ;; a) echo -n " Must be one of these values '$RANGE'." ;; *) echo -n " Must be in the range '$RANGE'." ;; esac fi fi fi } # allow them to specify the long option name or the environment parameter del_opt() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local OPT_NAME PRE ENV_NAME for OPT_NAME in "$@"; do ENV_NAME=$(convert_to_env_name "$OPT_NAME") OPT_NAME=$(convert_to_option_name "$OPT_NAME") for PRE in ARGP_SOPT_ ARGP_LOPT_ ARGP_DESC_OPT_ ARGP_LABEL_ ARGP_TYPE_ ARGP_ORIGINAL_NAME_ ARGP_MANDATORY_ ARGP_RANGE_; do local N=$PRE$ENV_NAME [[ "${!N:-}" ]] && unset $PRE$ENV_NAME done local OPT_LIST OPT OPT_LIST="" for OPT in ${ARGP_OPTION_LIST:-}; do [[ $OPT = $ENV_NAME ]] || OPT_LIST="$OPT_LIST $OPT" done ARGP_OPTION_LIST="$OPT_LIST" [[ "$OPT_NAME" == "$GARGP_HELP_loption" ]] && { GARGP_HELP_option= GARGP_HELP_loption= } [[ "$OPT_NAME" == "$GARGP_VERSION_loption" ]] && { GARGP_VERSION_option= GARGP_VERSION_loption= } [[ "$OPT_NAME" == "$GARGP_PRINTMAN_loption" ]] && { GARGP_PRINTMAN_loption= } [[ "$OPT_NAME" == "$GARGP_PRINTXML_loption" ]] && { GARGP_PRINTXML_loption= } done } # prints an abstract of short options that take no parameter print_abstract_opt_short_without_arg() { local NAME DESC L A FLAGS="" for NAME in ${ARGP_OPTION_LIST:-}; do [[ "$NAME" == $( convert_to_env_name "$GARGP_ENDOPTS_loption") ]] && continue DESC=$(get_opt_desc $NAME) [[ "$DESC" ]] || continue L=$(get_opt_letter $NAME) [[ "$L" ]] || continue A=$(get_opt_label $NAME) [[ "$A" ]] && continue FLAGS="$FLAGS$L" done printf %s "$FLAGS" } # prints an abstract of long options that take no parameter print_abstract_opt_long_without_arg() { local NAME local FLAGS="" local SPACE="" for NAME in ${ARGP_OPTION_LIST:-}; do local DESC=$(get_opt_desc $NAME) [[ "$DESC" ]] || continue local L=$(get_opt_long_name $NAME) [[ "$L" = "$GARGP_ENDOPTS_loption" ]] && continue [[ "$L" ]] || continue local A=$(get_opt_label $NAME) [[ "$A" ]] && continue printf -- "$SPACE--%s" $L SPACE=" " done printf %s "$FLAGS" } # prints an abstract of short and long options that take values print_abstract_opt_with_args() { local NAME FMT for NAME in ${ARGP_OPTION_LIST:-}; do local DESC=$(get_opt_desc $NAME) [[ "$DESC" ]] || continue local LABEL=$(get_opt_label "$NAME") [[ "$LABEL" ]] || continue local SOPT=$(get_opt_letter "$NAME") local LOPT=$(get_opt_long_name "$NAME") local MANDATORY=$(get_opt_mandatory "$NAME") echo -n " " [[ "$MANDATORY" == "0" ]] && echo -n "[" [[ "$SOPT" ]] && ( FMT="-%s <%s>" [[ "$LABEL" ]] && printf -- "$FMT" $SOPT $LABEL [[ "$LABEL" ]] && echo -n "," ) FMT="--%s=<%s>" [[ "$LABEL" ]] && printf -- "$FMT" $LOPT $LABEL [[ "$MANDATORY" == "0" ]] && echo -n "]" done } # prints an abstract of parameter print_abstract_param() { local NAME FMT for NAME in ${ARGP_PARAM_LIST:-}; do local DESC=$(get_param_desc $NAME) [[ "$DESC" ]] || continue local LABEL=$(get_param_label "$NAME") [[ "$LABEL" ]] || continue local ORIGINAL_NAME=$(get_param_original_name "$NAME") echo -n " " FMT="%s" printf -- "$FMT" $LABEL done } # print the help line for all options print_full_opts() { local NAME for NAME in ${ARGP_OPTION_LIST:-}; do print_opt $NAME done } # print the help line for all options print_full_params() { local NAME for NAME in ${ARGP_PARAM_LIST:-}; do print_param $NAME done } print_xml() { local NAME echo '<?xml version="1.0" encoding="UTF-8"?>' echo "<argp><prog>$ARGP_PROG</prog>" echo "<version>$GARGP_VERSION</version>" echo "<short_desc>$SHORT_DESC</short_desc>" echo "<long_desc>$LONG_DESC</long_desc>" echo "<delete_default_opt>$ARGP_DELETE</delete_default_opt>" for NAME in ${ARGP_PARAM_LIST:-}; do echo "<parameter name='$(get_param_original_name $NAME)' type='$(get_param_type $NAME)' mandatory='1' label='$(get_param_label $NAME)' range='$(get_param_range $NAME)'><short_desc>$(get_param_short_desc $NAME)</short_desc><long_desc>$(get_param_desc $NAME)</long_desc></parameter>" done for NAME in ${ARGP_OPTION_LIST:-}; do case $(convert_to_option_name $NAME) in $GARGP_PRINTXML_loption| \ $GARGP_ENDOPTS_loption) continue; esac echo "<option name='$(get_opt_original_name $NAME)' sname='$(get_opt_letter $NAME)' type='$(get_opt_type $NAME)' mandatory='$(get_opt_mandatory $NAME)' label='$(get_opt_label $NAME)' default='$(get_opt_default $NAME)' range='$(get_opt_range $NAME)'><short_desc>$(get_opt_short_desc $NAME)</short_desc><long_desc>$(get_opt_desc $NAME)</long_desc></option>" done echo "</argp>" } #NAME=DEFAULT 'SHORT_NAME' 'LABEL' TYPE MANDATORY 'RANGE' DESCRIPTION #NAME 'LABEL' TYPE 'RANGE' DESCRIPTION #TODO read_xml_format() { type xmlstarlet &>/dev/null || abend 1 "Please install xmlstarlet" xmlstarlet sel --text -t -m '/argp' \ -v "concat('ARGP_PROG=', prog)" -n \ -v "concat('ARGP_VERSION=',version)" -n \ -v "concat('ARGP_SHORT=', short_desc)" -n \ -v "concat('ARGP_LONG_DESC=', long_desc)" -n \ -v "concat('ARGP_DELETE=', delete_default_opt)" -n \ -t -m '/argp/parameter' \ -t -m '/argp/option' \ -v "concat(@name, \"='\", @default, \"' '\", @sname, \"' '\", @label, \"' \", @type, \" \", @mandatory, \" '\", @range, \"' \", self::option)" -n } add_std_opts() { get_opt_name -$GARGP_HELP_option >/dev/null && GARGP_HELP_option= get_opt_name --$GARGP_HELP_loption >/dev/null && GARGP_HELP_loption= if [[ "$GARGP_HELP_option$GARGP_HELP_loption" ]]; then add_opt "$GARGP_HELP_loption" "" "$GARGP_HELP_option" "" b 0 "" "print this help and exit" fi get_opt_name -$GARGP_VERSION_option >/dev/null && GARGP_VERSION_option= get_opt_name --$GARGP_VERSION_loption >/dev/null && GARGP_VERSION_loption= if [[ "$GARGP_VERSION_option$GARGP_VERSION_loption" ]]; then add_opt "$GARGP_VERSION_loption" "" "$GARGP_VERSION_option" "" b 0 "" "print version and exit" fi get_opt_name -$GARGP_VERBOSE_option >/dev/null && GARGP_VERBOSE_option= get_opt_name --$GARGP_VERBOSE_loption >/dev/null && GARGP_VERBOSE_loption= if [[ "$GARGP_VERBOSE_option$GARGP_VERBOSE_loption" ]]; then add_opt "$GARGP_VERBOSE_loption" "" "$GARGP_VERBOSE_option" "" b 0 "" "do it verbosely" fi get_opt_name -$GARGP_QUIET_option >/dev/null && GARGP_QUIET_option= get_opt_name --$GARGP_QUIET_loption >/dev/null && GARGP_QUIET_loption= if [[ "$GARGP_QUIET_option$GARGP_QUIET_loption" ]]; then add_opt "$GARGP_QUIET_loption" "" "$GARGP_QUIET_option" "" b 0 "" "do it quietly" fi add_opt "$GARGP_PRINTXML_loption" "" "" "" b 0 "" add_opt "$GARGP_ENDOPTS_loption" "" "-" "" b 0 "" "explicitly ends the options" } print_param() { local NAME="$1" local L N DESC ORIGINAL_NAME LABEL DESC=$(get_param_desc $NAME) [[ "$DESC" ]] || return 0 ORIGINAL_NAME=$(get_param_original_name $NAME) LABEL=$(get_param_label $NAME) LINE="" for (( N=0 ; ${#LINE} < GARGP_SHORT_OPT_COL ; N++ )) ; do LINE="$LINE " done if [[ "$ORIGINAL_NAME" ]]; then LONG_START=$GARGP_SHORT_OPT_COL for (( N=0 ; ${#LINE} < LONG_START ; N++ )); do LINE="$LINE " done [[ "$LABEL" ]] && LINE="${LINE}$LABEL" #[[ "$LABEL" ]] && LINE="$LINE ($LABEL)" fi LINE="$LINE " while (( ${#LINE} < GARGP_OPT_DOC_COL - 1)) ; do LINE="$LINE " ; done # NB 'echo "-E"' swallows the -E!! and it has no -- so use printf printf -- "%s" "$LINE" FIRST="FIRST_yes" if (( ${#LINE} >= GARGP_OPT_DOC_COL )); then echo FIRST="" fi local WIDTH=$(( GARGP_RMARGIN - GARGP_OPT_DOC_COL )) if ! type fmt &> /dev/null || [[ "$WIDTH" -lt 10 ]]; then printf -- "%s\n" "$DESC" return 0 fi export ARGP_INDENT="" while (( ${#ARGP_INDENT} < GARGP_OPT_DOC_COL - 1)); do ARGP_INDENT="$ARGP_INDENT " done echo "$DESC" |fmt -w "$WIDTH" -s | { while read L; do [[ "$FIRST" ]] || printf %s "$ARGP_INDENT"; FIRST=""; printf -- "%s\n" "$L" done } unset ARGP_INDENT } print_opt() { local NAME="$1" local L N DESC SOPT LOPT LABEL DESC=$(get_opt_desc $NAME) [[ "$DESC" ]] || return 0 SOPT=$(get_opt_letter $NAME) LOPT=$(get_opt_long_name $NAME) LABEL=$(get_opt_label $NAME) # if LABEL is not set (so the description, this option is hidden) LINE="" for (( N=0 ; ${#LINE} < GARGP_SHORT_OPT_COL ; N++ )) ; do LINE="$LINE " done [[ "$SOPT" ]] && LINE="${LINE}-$SOPT" [[ "$SOPT" ]] && [[ "$LABEL" ]] && LINE="${LINE} $LABEL" if [[ "$GARGP_LONG_GETOPT" && "$LOPT" != "$GARGP_ENDOPTS_loption" ]]; then [[ "$SOPT" ]] && [[ "$LOPT" ]] && LINE="$LINE, " if [[ "$LOPT" ]]; then if [[ "$SOPT" ]]; then LONG_START=${LONG_COL_OPT:-} else LONG_START=$GARGP_SHORT_OPT_COL fi for (( N=0 ; ${#LINE} < LONG_START ; N++ )); do LINE="$LINE " done [[ "$LOPT" ]] && LINE="${LINE}--$LOPT" [[ "$LOPT" ]] && [[ "$LABEL" ]] && LINE="$LINE=$LABEL" fi fi LINE="$LINE " while (( ${#LINE} < GARGP_OPT_DOC_COL - 1)) ; do LINE="$LINE " ; done # NB 'echo "-E"' swallows the -E!! and it has no -- so use printf printf -- "%s" "$LINE" FIRST="FIRST_yes" if (( ${#LINE} >= GARGP_OPT_DOC_COL )); then echo FIRST="" fi local WIDTH=$(( GARGP_RMARGIN - GARGP_OPT_DOC_COL )) if ! type fmt &> /dev/null || [[ "$WIDTH" -lt 10 ]]; then printf -- "%s\n" "$DESC" return 0 fi export ARGP_INDENT="" while (( ${#ARGP_INDENT} < GARGP_OPT_DOC_COL - 1)); do ARGP_INDENT="$ARGP_INDENT " done echo "$DESC" |fmt -w "$WIDTH" -s | { while read L; do [[ "$FIRST" ]] || printf %s "$ARGP_INDENT"; FIRST=""; printf -- "%s\n" "$L" done } unset ARGP_INDENT } # honour GNU ARGP_HELP_FMT parameter load_help_fmt() { [[ "${ARGP_HELP_FMT:-}" ]] || return 0 OFS="$IFS" IFS=',' set -- $ARGP_HELP_FMT IFS="$OFS" while [[ "$1" ]]; do case "$1" in short-opt-col*) GARGP_SHORT_OPT_COL=$(echo "$1"|cut -d'=' -f 2) shift ;; long-opt-col*) GARGP_LONG_OPT_COL=$(echo "$1"|cut -d'=' -f 2) shift ;; opt-doc-col*) GARGP_OPT_DOC_COL=$(echo "$1"|cut -d'=' -f 2) shift ;; rmargin*) GARGP_RMARGIN=$(echo "$1"|cut -d'=' -f 2) shift ;; *) shift ;; esac done } default_usage() { local FLAGS=$(print_abstract_opt_short_without_arg) [[ "$FLAGS" ]] && FLAGS="[-$FLAGS]" local LFLAGS=$(print_abstract_opt_long_without_arg) [[ "$LFLAGS" ]] && LFLAGS=" [$LFLAGS]" local OPT_ARGS=$(print_abstract_opt_with_args) local PARAM_ABSTRACT=$(print_abstract_param) local FMT="fmt -w $GARGP_RMARGIN -s" type fmt &> /dev/null || FMT=cat echo "${SHORT_DESC:-}" echo echo -e "Usage: $ARGP_PROG ${PARAM_ABSTRACT:-} $FLAGS$LFLAGS $OPT_ARGS" |$FMT echo echo "${LONG_DESC:-}" echo echo "Parameters:" echo print_full_params echo echo "Options:" echo print_full_opts } check_type_and_value() { local NAME="$1" local VALUE="$2" local TYPE="$3" local RANGE="$4" [[ "$ARGP_DEBUG" ]] && echo "$FUNCNAME: NAME='$NAME' VALUE='$VALUE' TYPE='$TYPE' RANGE='$RANGE'" >&2 # just using 'while' for the sake of the 'break': while [[ "$TYPE" ]]; do case "$TYPE" in i) [[ "$VALUE" =~ $GARGP_INT_REGEX ]] || break [[ "$RANGE" ]] && { local LOWER=$(echo "$RANGE" | cut -d: -f1) local UPPER=$(echo "$RANGE" | cut -d: -f2) [[ "$LOWER" && "$VALUE" -lt "$LOWER" ]] && break [[ "$UPPER" && "$VALUE" -gt "$UPPER" ]] && break } return 0 ;; d) [[ "$VALUE" =~ $GARGP_FLOAT_REGEX ]] || break [[ "$RANGE" ]] && { local LOWER=$(echo "$RANGE" | cut -d: -f1) local UPPER=$(echo "$RANGE" | cut -d: -f2) [[ "$LOWER" ]] && { awk "BEGIN {if ($VALUE < $LOWER) {exit 1} else {exit 0}}" || break } [[ "$UPPER" ]] && { awk "BEGIN {if ($VALUE > $UPPER) {exit 1} else {exit 0}}" || break } } return 0 ;; s*) [[ "$RANGE" ]] && { [[ "$VALUE" =~ $RANGE ]] || break } return 0 ;; a) local VAL for VAL in $RANGE; do [[ "$VAL" == "$VALUE" ]] && return 0 done break ;; esac done MSG="$ARGP_PROG: value '$VALUE' given for '$NAME'" if [[ "$TYPE" != s* ]]; then MSG+=" must be of type '$TYPE'" fi [[ "$RANGE" ]] && { case "$TYPE" in s*) MSG+=" and must fit the regex '$RANGE'" ;; a) MSG+=" and must be one of these values: $RANGE" ;; f|d|i) MSG+=" and in the range '$RANGE'" ;; esac } abend 1 "$MSG" } get_opt_name() { # returns the name for an option letter or word local OPT="$1" # an option eg -c or --foobar local NAME for NAME in ${ARGP_OPTION_LIST:-}; do local ARGP_L=ARGP_LOPT_$NAME local ARGP_S=ARGP_SOPT_$NAME if [[ "--${!ARGP_L:-}" = "$OPT" ]] || \ [[ "-${!ARGP_S:-}" = "$OPT" ]]; then echo "${NAME}" return 0 fi done return 1 } process_params() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local SHIFT_NUM=0 PARAM PARAM_NAME TYPE RANGE MANDATORY VALUE for PARAM_NAME in $ARGP_PARAM_LIST; do VALUE="${1:-}" MANDATORY=1 TYPE=$(get_param_type "$PARAM_NAME") [[ "$TYPE" ]] || { abend 1 "$ARGP_PROG: argp.sh: no type for param \"$PARAM_NAME\"" } RANGE=$(get_param_range "$PARAM_NAME") ((SHIFT_NUM++)) shift [[ "$VALUE" ]] || { [[ "$MANDATORY" == "1" ]] && abend 1 "$PARAM_NAME is mandatory" } [[ "$ARGP_DEBUG" ]] && echo "process_params: param='$PARAM_NAME' value='$VALUE' type='$TYPE' range='$RANGE'" check_type_and_value "$PARAM_NAME" "$VALUE" "$TYPE" "$RANGE" export $PARAM_NAME="$VALUE" set +x done return $SHIFT_NUM } process_opts() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local SHIFT_NUM=0 OPTION OPT_NAME TYPE RANGE while true; do OPTION="${1:-}" if [[ "$GARGP_HELP_option" && "-$GARGP_HELP_option" == "$OPTION" ]] || [[ "$GARGP_HELP_loption" && "--$GARGP_HELP_loption" == "$OPTION" ]]; then usage 2>/dev/null || default_usage echo "exit 0;" >&3 exit 0 fi if [[ "$GARGP_VERSION_option" && "-$GARGP_VERSION_option" == "$OPTION" ]] || [[ "$GARGP_VERSION_loption" && "--$GARGP_VERSION_loption" == "$OPTION" ]]; then echo "echo $ARGP_PROG: version: '$ARGP_VERSION'; exit 0;" >&3 exit 0 fi if [[ "$GARGP_PRINTXML_loption" && --$GARGP_PRINTXML_loption == "$OPTION" ]]; then print_xml echo "exit 0;" >&3 exit 0 fi ((SHIFT_NUM++)) shift [[ "$OPTION" == "--" ]] && break # here is where all the user options get done: OPT_NAME=$(get_opt_name "$OPTION") [[ "$OPT_NAME" ]] || { abend 1 "$ARGP_PROG: argp.sh: no name for option \"$OPTION\"" } TYPE=$(get_opt_type "$OPT_NAME") [[ "$TYPE" ]] || { abend 1 "$ARGP_PROG: argp.sh: no type for option \"$OPTION\"" } RANGE=$(get_opt_range "$OPT_NAME") [[ "$ARGP_DEBUG" ]] && echo "process_opts: option='$OPTION' name='$OPT_NAME' type='$TYPE' range='$RANGE'" case $TYPE in b) if [[ "$RANGE" ]]; then export $OPT_NAME="$RANGE" else # if no previous value, reset it [[ "${!OPT_NAME}" ]] || export $OPT_NAME= if [[ "${!OPT_NAME}" =~ ^[0-9]+$ ]]; then export $OPT_NAME=$(( OPT_NAME + 1 )) else export $OPT_NAME=1 fi fi ;; *) local VALUE="$1" [[ "$RANGE" ]] && check_type_and_value "$OPT_NAME" "$VALUE" "$TYPE" "$RANGE" case $TYPE in a|s*) local SEP=${TYPE:1} if [[ "$SEP" && "${!OPT_NAME}" ]]; then export $OPT_NAME="${!OPT_NAME}${SEP}$VALUE" elif [[ "$OPTION_SEP" && "${!OPT_NAME}" ]]; then export $OPT_NAME="${!OPT_NAME}${OPTION_SEP}$VALUE" else export $OPT_NAME="$VALUE" fi ;; *) export $OPT_NAME="$VALUE" ;; esac ((SHIFT_NUM++)) shift set +x ;; esac done return $SHIFT_NUM } output_values_param() { local PARAM_NAME VALUE MANDATORY # NOTE : use local PARAM_NAME to not override param name which can be "NAME" for PARAM_NAME in $ARGP_PARAM_LIST; do VALUE="${!PARAM_NAME}" MANDATORY=1 [[ "$VALUE" ]] || { [[ "$MANDATORY" == "1" ]] && abend 1 "$PARAM_NAME is mandatory" } [[ "$VALUE" == *\'* ]] && VALUE=$(echo "${VALUE}" |sed -e "s/'/'\\\''/g") echo -n "export $PARAM_NAME='$VALUE'; " done echo -n "set -- " for VALUE in "$@"; do [[ "$VALUE" == *\'* ]] && VALUE=$(echo "${VALUE}" |sed -e "s/'/'\\\''/g") echo -n " '$VALUE'" ; done echo } output_values() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local OPT_NAME VALUE MANDATORY DEF # NOTE : use local OPT_NAME to not override option name which can be "NAME" for OPT_NAME in $ARGP_OPTION_LIST; do VALUE="${!OPT_NAME}" MANDATORY=$(get_opt_mandatory $OPT_NAME) [[ "$VALUE" ]] || { DEF=$(get_opt_default $OPT_NAME) [[ "$DEF" ]] || { [[ "$MANDATORY" == "1" ]] && abend 1 "$OPT_NAME is mandatory" } VALUE=$(get_opt_default $OPT_NAME) } [[ "$VALUE" == *\'* ]] && VALUE=$(echo "${VALUE}" |sed -e "s/'/'\\\''/g") echo -n "export $OPT_NAME='$VALUE'; " done #echo -n "set -- " #for VALUE in "$@"; do # [[ "$VALUE" == *\'* ]] && VALUE=$(echo "${VALUE}" |sed -e "s/'/'\\\''/g") # echo -n " '$VALUE'" ; done #echo } call_getopt() { [[ "$ARGP_DEBUG" ]] && debug_args "$@" local SHORT_OPTIONS="" local SHORT_OPTIONS_ARG="" local LONG_OPTIONS="" local LONG_OPTIONS_ARG="" local STOP_EARLY="" local OPT TEMP NAME LONG LABEL for NAME in $ARGP_OPTION_LIST; do OPT=$(get_opt_letter $NAME) LABEL=$(get_opt_label $NAME) LONG=$(get_opt_long_name $NAME) [[ "$OPT" == '-' ]] && continue if [[ "$OPT" ]]; then if [[ "$LABEL" ]]; then SHORT_OPTIONS_ARG+="$OPT:" else SHORT_OPTIONS+="$OPT" fi fi if [[ "$LABEL" ]]; then [[ "$LONG_OPTIONS_ARG" ]] && LONG_OPTIONS_ARG+="," LONG_OPTIONS_ARG+="$LONG:" else [[ "$LONG_OPTIONS" ]] && LONG_OPTIONS+="," LONG_OPTIONS+="$LONG" fi done [[ "$STOP_ON_FIRST_NON_OPT" ]] && STOP_EARLY="+" if [[ "${GARGP_LONG_GETOPT:-''}" ]]; then local SHORT_ARGS="" local LONG_ARGS="" [[ -n "$SHORT_OPTIONS$SHORT_OPTIONS_ARG" ]] && SHORT_ARGS="-o $STOP_EARLY$SHORT_OPTIONS$SHORT_OPTIONS_ARG" [[ -n "$LONG_OPTIONS" ]] && LONG_ARGS="--long $LONG_OPTIONS" [[ -n "$LONG_OPTIONS_ARG" ]] && LONG_ARGS="$LONG_ARGS --long $LONG_OPTIONS_ARG" [[ "$ARGP_DEBUG" ]] && echo "call_getopt: set -- \$($GETOPT_CMD $SHORT_ARGS $LONG_ARGS -n $ARGP_PROG -- $@)" >&2 TEMP=$($GETOPT_CMD $SHORT_ARGS $LONG_ARGS -n "$ARGP_PROG" -- "$@") || abend $? "$GETOPT_CMD failure" else [[ "$ARGP_DEBUG" ]] && echo "call_getopt: set -- \$($GETOPT_CMD $SHORT_OPTIONS$SHORT_OPTIONS_ARG $@)" >&2 TEMP=$($GETOPT_CMD $SHORT_OPTIONS$SHORT_OPTIONS_ARG "$@") || abend $? "$GETOPT_CMD failure" fi eval set -- "$TEMP" [[ "$ARGP_DEBUG" ]] && debug_args "$@" ARGS=( "$@" ) } sort_option_names_by_key() { [[ "$ARGP_DEBUG" ]] && echo "sort_option_names_by_key: before: $ARGP_OPTION_LIST" >&2 local NEW_OPTION_LIST= NAME= KEY= local TMP=/tmp/$$.options for NAME in ${ARGP_OPTION_LIST:-}; do KEY=$(get_opt_letter $NAME) [[ "$KEY" ]] || KEY="~" # ie collate last [[ "$KEY" == - ]] && KEY="~" # ie collate last echo "$KEY $NAME" done | sort -f >$TMP while read KEY NAME; do NEW_OPTION_LIST+="$NAME " done < $TMP rm -f $TMP ARGP_OPTION_LIST="$NEW_OPTION_LIST" [[ "$ARGP_DEBUG" ]] && echo "sort_option_names_by_key: after: $NEW_OPTION_LIST" >&2 } initialise() { GARGP_VERSION="2.3" STOP_ON_FIRST_NON_OPT=${POSIXLY_CORRECT:-} unset POSIXLY_CORRECT # by setting this env variable we can choose a getopt command [[ "$GETOPT_CMD" == "" ]] && GETOPT_CMD=getopt ARGP_PARAM_LIST="" LONG_DESC= ARGP_OPTION_LIST="" ARGP_OPTION_SEP= GARGP_LONG_GETOPT="" # decide if this getopt supports long options: { $GETOPT_CMD --test &>/dev/null; ARGP_STAT=$? } || : [[ $ARGP_STAT -eq 4 ]] && GARGP_LONG_GETOPT="GARGP_LONG_GETOPT_yes" GARGP_HELP_loption="help" GARGP_HELP_option="h" GARGP_VERBOSE_loption="verbose" GARGP_VERBOSE_option="v" VERBOSE= GARGP_QUIET_option="q" GARGP_QUIET_loption="quiet" QUIET= GARGP_VERSION_loption="version" GARGP_VERSION_option="V" GARGP_PRINTXML_loption="print-xml" GARGP_ENDOPTS_loption="end-all-options" GARGP_SHORT_OPT_COL=2 GARGP_LONG_OPT_COL=6 GARGP_OPT_DOC_COL=29 GARGP_INT_REGEX="[+-]*[[:digit:]]+" GARGP_INT_RANGE_REGEX="$GARGP_INT_REGEX:$GARGP_INT_REGEX" GARGP_FLOAT_REGEX="[+-]*[[:digit:]]+(\\.[[:digit:]]+)*" GARGP_FLOAT_RANGE_REGEX="$GARGP_FLOAT_REGEX:$GARGP_FLOAT_REGEX" # FIXME: this needs a few tweaks: GARGP_URL_REGEX="(nfs|http|https|ftp|file)://[[:alnum:]_.-]*[^[:space:]]*" # cron jobs have TERM=dumb and tput throws errors: type tput &>/dev/null && \ _GPG_COLUMNS=$( [[ "$TERM" && "$TERM" != "dumb" ]] && tput cols || echo 80) \ _GPG_COLUMNS=80 GARGP_RMARGIN=$_GPG_COLUMNS load_help_fmt [[ "$GARGP_RMARGIN" -gt "$_GPG_COLUMNS" ]] && GARGP_RMARGIN=$_GPG_COLUMNS # we're being called directly from the commandline (possibly in error # but maybe the guy is just curious): # fix : have problem in some case # tty -s && { # ARGP_VERSION=$GARGP_VERSION # add_std_opts # ARGP_PROG=${0##*/} # == basename # ARGP_argp_sh_usage # exit 0 # } } read_config() { # note that we can't use process substitution: # foobar < <( barfoo ) # as POSIXLY_CORRECT disables it! So we'll use a temp file for the xml. local TMP=/tmp/argp.sh.$$ trap "rm -f $TMP" EXIT local FILE_TYPE= LINE= local READING_OPT=0 local READING_PARAM=0 local READING_HEADER=0 local READING_LONG_DESC=0 while read LINE; do [[ "$FILE_TYPE" ]] || { [[ "$LINE" == "<?xml"* ]] && { FILE_TYPE="xml" { echo "$LINE" cat } | read_xml_format > $TMP exec <$TMP continue } } [[ "$ARGP_DEBUG" ]] && echo "read: $LINE" >&2 case "$LINE" in "--HEADER--") READING_HEADER=1 READING_PARAM=0 READING_OPT=0 READING_LONG_DESC=0 ;; "--PARAMETERS--") READING_HEADER=0 READING_PARAM=1 READING_OPT=0 READING_LONG_DESC=0 ;; "--OPTIONS--") READING_HEADER=0 READING_PARAM=0 READING_OPT=1 READING_LONG_DESC=0 ;; "ARGP_PROG="*) ARGP_PROG="${LINE#ARGP_PROG=}" ;; "ARGP_DELETE="*) del_opt ${LINE#ARGP_DELETE=} ;; "ARGP_SHORT="*) SHORT_DESC="${LINE#ARGP_SHORT=}" ;; "ARGP_VERSION="*) ARGP_VERSION="${LINE#ARGP_VERSION=}" ;; "ARGP_OPTION_SEP="*) ARGP_OPTION_SEP="${LINE#ARGP_OPTION_SEP=}" ;; "ARGP_LONG_DESC="*) READING_HEADER=1 READING_PARAM=0 READING_OPT=0 READING_LONG_DESC=1 if [[ "${LINE#ARGP_LONG_DESC=}" ]]; then LONG_DESC="${LINE#ARGP_LONG_DESC=} "$'\n' fi ;; *) case "$LINE" in [A-Za-z]*) if [[ "$READING_HEADER" == "1" ]]; then if [[ "$READING_LONG_DESC" == "1" ]]; then LONG_DESC+="$LINE"$'\n' fi fi if [[ "$READING_PARAM" == "1" ]]; then local NAME= REGEX= TYPE= RANGE= DESC= VAR= ORIGINAL_NAME= LABEL= NAME="${LINE%%=*}" LINE="${LINE#$NAME=}" ORIGINAL_NAME="$NAME" NAME=$(convert_to_env_name $NAME) # initial value could contain spaces, quotes, anything - # but I don't think we need to support escaped quotes: REGEX="^[[:space:]]*('[^']*'|[^[:space:]]+)[[:space:]]*(.*)" for VAR in LABEL TYPE RANGE; do [[ "$LINE" =~ $REGEX ]] || break V="${BASH_REMATCH[1]}" V="${V%\'}" V="${V#\'}" local $VAR="$V" LINE="${BASH_REMATCH[2]}" done DESC="$LINE" while [[ "$DESC" = *\\ ]]; do DESC="${DESC%\\}" read LINE DESC+="$LINE" [[ "$ARGP_DEBUG" ]] && echo "read for DESC: $LINE" >&2 done add_param "$ORIGINAL_NAME" "$LABEL" "$TYPE" "$RANGE" "$DESC" fi if [[ "$READING_OPT" == "1" ]]; then local NAME= REGEX= DEFAULT= SNAME= LABEL= TYPE= MANDATORY= RANGE= DESC= VAR= NAME="${LINE%%=*}" LINE="${LINE#$NAME=}" ORIGINAL_NAME="$NAME" NAME=$(convert_to_env_name $NAME) # initial value could contain spaces, quotes, anything - # but I don't think we need to support escaped quotes: REGEX="^[[:space:]]*('[^']*'|[^[:space:]]+)[[:space:]]*(.*)" for VAR in DEFAULT SNAME LABEL TYPE MANDATORY RANGE; do [[ "$LINE" =~ $REGEX ]] || break V="${BASH_REMATCH[1]}" V="${V%\'}" V="${V#\'}" local $VAR="$V" LINE="${BASH_REMATCH[2]}" done DESC="$LINE" while [[ "$DESC" = *\\ ]]; do DESC="${DESC%\\}" read LINE DESC+="$LINE" [[ "$ARGP_DEBUG" ]] && echo "read for DESC: $LINE" >&2 done add_opt "$ORIGINAL_NAME" "$DEFAULT" "$SNAME" "$LABEL" "$TYPE" "$MANDATORY" "$RANGE" "$DESC" fi ;; *) # includes comments ;; esac ;; esac done } main() { add_std_opts read_config sort_option_names_by_key call_getopt "$@" [[ "$ARGP_DEBUG" ]] && debug_args "$@" process_opts "${ARGS[@]}" ARGP_NUM_SHIFT=$? set -- "${ARGS[@]}" shift $ARGP_NUM_SHIFT [[ "$ARGP_DEBUG" ]] && debug_args "$@" output_values "$@" >&3 process_params "$@" ARGP_NUM_SHIFT=$? shift $ARGP_NUM_SHIFT [[ "$ARGP_DEBUG" ]] && debug_args "$@" output_values_param "$@" >&3 } check_bash() { [[ "$ARGP_DEBUG" ]] && echo "$ARGP_PROG: arpg.sh: debug is on" >&2 ARGP_GOOD_ENOUGH="" if [ "x$BASH_VERSION" = "x" -o "x$BASH_VERSINFO" = "x" ]; then : elif [ "${BASH_VERSINFO[0]}" -gt 2 ]; then ARGP_GOOD_ENOUGH="1" fi if [ "x$ARGP_GOOD_ENOUGH" = "x" ]; then echo "$0: This version of the shell does not support this program." >&2 echo "bash-3 or later is required" >&2 echo "exit 1;" >&3 exit 1 fi } try_c_version() { [[ "${ARGP_PROCESSOR##*/}" != "${0##*/}" ]] && type argp &>/dev/null && { [[ "$ARGP_DEBUG" ]] && echo "$ARGP_PROG: argp.sh exec'ing argp: you can use ARGP_PROCESSOR to override this" >&2 exec argp "$@" } } if [[ "$GETOPT_CMD" == "PURE_BASH" ]]; then # include pure-getopt from Aron Griffis https://github.com/agriffis/pure-getopt source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/../pool/artefact/pure-getopt/getopt.bash" GETOPT_CMD=getopt fi try_c_version "$@" check_bash initialise main "$@" # just to make sure we don't return with non-zero $?: :
C++
UTF-8
767
3.578125
4
[]
no_license
#include <iostream> #include <list> #include <map> #include <set> #include <string> #include <vector> using namespace std; int main(){ std::vector<int> v; std::set<int> s; std::list<int> l; std::map<string,int> m; v.push_back(5); v.push_back(10); v.push_back(15); for(vector<int>::iterator it = v.begin(); it != v.end(); it++){ cout << *it << endl; } l.push_back(2); l.push_back(4); l.push_back(6); l.push_back(8); // Add the for loop that iterates through the list here m["IfStmt"] = 0; m["Stmt"] = 20; m["ForStmt"] = 4; // Add the for loop that iterates over the map here s.insert(20); s.insert(45); // Add the for loop that iterates over the set here // READ THE Auto NOTES FIRST return 0; }
Shell
UTF-8
3,237
3.34375
3
[]
no_license
#------------------------- # Bash shopts. #------------------------- shopt -s histappend # appends to the history instead of overwriting it. shopt -s cmdhist # bash attemps to save multiple line commands in one history entry. shopt -s lithist # save multi-line commands using \n instead of , #shopt -s no_empty_cmd_completion # if using tab on empty line, don't do anything. shopt -s cdspell # if cd X, X is miss espelled, fix it. #------------------------- # Mist. #------------------------- # don't put duplicate lines or lines starting with space in the history. HISTCONTROL=ignoreboth # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=1000 HISTFILESIZE=2000 #------------------------- # Aliases. #------------------------- alias ls='ls -G' alias la='ls -la' alias artisan='php artisan' alias dartisan='docker-compose exec app php artisan' #------------------------- # Completion. #------------------------- complete -A alias alias unalias complete -A export export printenv complete -A shopt shopt complete -A directory cd rmdir complete -A signal kill killall complete -A job -P '%' fg jobs complete -A helptopic help complete -A command which #------------- # bash promtp. #------------- #if [[ $COLORTERM = gnome-* && $TERM = xterm ]] && infocmp gnome-256color >/dev/null 2>&1; then # export TERM=gnome-256color #elif infocmp xterm-256color >/dev/null 2>&1; then # if [ `toe -a | grep -q xterm-256color-italics` ]; then # export TERM=xterm-256color-italics # else # export TERM=xterm-256color # fi #fi if tput setaf 1 &> /dev/null; then tput sgr0 if [[ $(tput colors) -ge 256 ]] 2>/dev/null; then # Changed these colors to fit Solarized theme ORANGE=$(tput setaf 166) GREEN=$(tput setaf 64) PURPLE=$(tput setaf 61) WHITE=$(tput setaf 244) else ORANGE=$(tput setaf 4) GREEN=$(tput setaf 2) PURPLE=$(tput setaf 1) WHITE=$(tput setaf 7) fi BOLD=$(tput bold) RESET=$(tput sgr0) else ORANGE="\033[1;33m" GREEN="\033[1;32m" PURPLE="\033[1;35m" WHITE="\033[1;37m" RESET="\033[m" fi export ORANGE export GREEN export PURPLE export WHITE export BOLD export RESET function parse_git_dirty() { [[ $(git status 2> /dev/null | tail -n1) != *"working directory clean"* ]] && echo "*" } function parse_git_branch() { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1$(parse_git_dirty)/" } function minutes_since_last_commit() { now=`date +%s` last_commit=`git log --pretty=format:'%at' -1` seconds_since_last_commit=$((now-last_commit)) minutes_since_last_commit=$((seconds_since_last_commit/60)) echo $minutes_since_last_commit } export PS1="\[$ORANGE\]\h\[$WHITE\] \[$GREEN\]\w\[$WHITE\] \$([[ -n \$(git branch 2> /dev/null) ]] && echo \" on \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]\$ \[$RESET\]" export PS1="\[$ORANGE\]\h\[$WHITE\] \[$GREEN\]\w\[$WHITE\] \[$PURPLE\]\$\[$RESET\] " if [ -f /usr/local/share/bash-completion/bash_completion ]; then . /usr/local/share/bash-completion/bash_completion fi export NVM_DIR="$HOME/.nvm" . "/usr/local/opt/nvm/nvm.sh" if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi
Python
UTF-8
410
3.46875
3
[ "MIT" ]
permissive
import random sayi = random.randint(1 , 99) tahmin = 0 say = 0 while tahmin != sayi and tahmin != "exit": tahmin = input("tahmin et?") if tahmin == "exit": break guess = int(tahmin) say += 1 if guess < sayi: print("cok dusuk!") elif guess > sayi: print("cok yuksek!") else: print("harika!") print(":)" , say , ":))")
C
ISO-8859-1
635
3.609375
4
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include<ctype.h> #include<locale.h> #include<math.h> int main() { setlocale(LC_ALL,"Portuguese"); int A, B, C, D, S, P; A = B = C = D = S = P = 0; printf("\nDigite o primeiro valor: \n>>> "); scanf("%i", &A); printf("\nDigite o segundo valor: \n>>> "); scanf("%i", &B); printf("\nDigite o terceiro valor: \n>>> "); scanf("%i", &C); printf("\nDigite o quarto valor: \n>>> "); scanf("%i", &D); S = (A+C); P = (B*D); printf("\n O resultado da soma entre %i e %i %i. \n O resultado da multiplicao entre %i e %i %i.\n", A, C, S, B, D, P); system("\n\npause\n"); return 0; }
Java
UTF-8
5,561
1.796875
2
[]
no_license
//Auto Generated package com.kootour.mapper.entity; import java.util.Date; import java.util.List; import java.util.ArrayList; import com.kootour.common.BaseEntity; public class ScheduleOptionEntity extends BaseEntity{ private String langId; private String scheduleOptionIdentiNo; private String courseIdentiNo; private String courseScheuleName; private String bgnDate; private String endDate; private String startHour; private String latestStartHour; private Double retailPrice; private Double commision; private Double price; private String infantFree; private String promotionFLg; private String promotionBgnDate; private String promotionEndDate; private String discountFlg; private Double discountPercent; private Double discountValue; private String largeDiscountFlg; private String largeDiscountType; private Double largeDiscountPercent; private Double largeDiscountValue; private Integer largeGroupLimit; private String workDay; private String delFlg; private Date createTime; private Date modifyTime; private Double discountPrice; public String getLangId(){ return langId; } public void setLangId( String langId) { this.langId = langId; } public String getScheduleOptionIdentiNo(){ return scheduleOptionIdentiNo; } public void setScheduleOptionIdentiNo( String scheduleOptionIdentiNo) { this.scheduleOptionIdentiNo = scheduleOptionIdentiNo; } public String getCourseIdentiNo(){ return courseIdentiNo; } public void setCourseIdentiNo( String courseIdentiNo) { this.courseIdentiNo = courseIdentiNo; } public String getCourseScheuleName(){ return courseScheuleName; } public void setCourseScheuleName( String courseScheuleName) { this.courseScheuleName = courseScheuleName; } public String getBgnDate(){ return bgnDate; } public void setBgnDate( String bgnDate) { this.bgnDate = bgnDate; } public String getEndDate(){ return endDate; } public void setEndDate( String endDate) { this.endDate = endDate; } public String getStartHour(){ return startHour; } public void setStartHour( String startHour) { this.startHour = startHour; } public String getLatestStartHour(){ return latestStartHour; } public void setLatestStartHour( String latestStartHour) { this.latestStartHour = latestStartHour; } public Double getRetailPrice(){ return retailPrice; } public void setRetailPrice( Double retailPrice) { this.retailPrice = retailPrice; } public Double getCommision(){ return commision; } public void setCommision( Double commision) { this.commision = commision; } public Double getPrice(){ return price; } public void setPrice( Double price) { this.price = price; } public String getInfantFree(){ return infantFree; } public void setInfantFree( String infantFree) { this.infantFree = infantFree; } public String getPromotionFLg(){ return promotionFLg; } public void setPromotionFLg( String promotionFLg) { this.promotionFLg = promotionFLg; } public String getPromotionBgnDate(){ return promotionBgnDate; } public void setPromotionBgnDate( String promotionBgnDate) { this.promotionBgnDate = promotionBgnDate; } public String getPromotionEndDate(){ return promotionEndDate; } public void setPromotionEndDate( String promotionEndDate) { this.promotionEndDate = promotionEndDate; } public String getDiscountFlg(){ return discountFlg; } public void setDiscountFlg( String discountFlg) { this.discountFlg = discountFlg; } public Double getDiscountPercent(){ return discountPercent; } public void setDiscountPercent( Double discountPercent) { this.discountPercent = discountPercent; } public Double getDiscountValue(){ return discountValue; } public void setDiscountValue( Double discountValue) { this.discountValue = discountValue; } public String getLargeDiscountFlg(){ return largeDiscountFlg; } public void setLargeDiscountFlg( String largeDiscountFlg) { this.largeDiscountFlg = largeDiscountFlg; } public String getLargeDiscountType(){ return largeDiscountType; } public void setLargeDiscountType( String largeDiscountType) { this.largeDiscountType = largeDiscountType; } public Double getLargeDiscountPercent(){ return largeDiscountPercent; } public void setLargeDiscountPercent( Double largeDiscountPercent) { this.largeDiscountPercent = largeDiscountPercent; } public Double getLargeDiscountValue(){ return largeDiscountValue; } public void setLargeDiscountValue( Double largeDiscountValue) { this.largeDiscountValue = largeDiscountValue; } public Integer getLargeGroupLimit(){ return largeGroupLimit; } public void setLargeGroupLimit( Integer largeGroupLimit) { this.largeGroupLimit = largeGroupLimit; } public String getWorkDay(){ return workDay; } public void setWorkDay( String workDay) { this.workDay = workDay; } public String getDelFlg(){ return delFlg; } public void setDelFlg( String delFlg) { this.delFlg = delFlg; } public Date getCreateTime(){ return createTime; } public void setCreateTime( Date createTime) { this.createTime = createTime; } public Date getModifyTime(){ return modifyTime; } public void setModifyTime( Date modifyTime) { this.modifyTime = modifyTime; } public Double getDiscountPrice(){ return discountPrice; } public void setDiscountPrice( Double discountPrice) { this.discountPrice = discountPrice; } }
Java
UTF-8
964
2.828125
3
[]
no_license
package Codechef; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; /** * @author Aakansha Doshi * */ public class SimpleEditor { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter p=new BufferedWriter(new OutputStreamWriter(System.out)); p.flush(); int T=Integer.parseInt(br.readLine());int index;String s[]; StringBuilder st=new StringBuilder(300001); while(T-->0) { s=br.readLine().split(" "); index=Integer.parseInt(s[1]); if(s[0].charAt(0)=='+') { st.insert(index,s[2]); } else { int start=index-1; int len=Integer.parseInt(s[2]); p.write( st.substring(start,start+len)+"\n"); } } p.close(); } }
Python
UTF-8
1,512
3.9375
4
[]
no_license
Guardar = print ('Hola') print (Guardar) Guardar = round (14.2534897,2) print (Guardar) def linedesign (cantidad,simbolo): print (simbolo*cantidad) return None linedesign (30,'#') linedesign (10,'*') linedesign (100,'🙃') #----Muestre la lista ----# def MostrarLista (ListaEntrada = []): for elemento in ListaEntrada: print (elemento) return None Lista = [213,32,23123,321,321,233,1232,23] Lista2 = [564654,645,64543,547,57865] linedesign (30, ':*') MostrarLista (Lista2) #----Sumar 2 numeros----# def sumar (a =0,b = 0): suma = a + b return suma linedesign (30,'*') resultado = sumar () print (resultado) print (sumar(12,14)) round (12.234897,2) #----Restar 2 numeros----# def restar (a =0,b = 0): resta = a - b return resta #----Multiplicar 2 numeros----# def multiplicar (a =0,b = 0): multiplica = a * b return multiplica #----Dividir 2 numeros----# def dividir (a = 0,b = 1): dividi = a / b return dividi #----Potenciar 2 numeros----# def potenciar (base = 0,exponente = 1): potencia = base ** exponente return potencia #----Funciones dependientes de otras----# def calcular (operacion,NumeroA,NumeroB): print (operacion(NumeroA,NumeroB)) BaseIngresada = int (input('Ingrese una base entera: ')) ExponenteIngresado = int (input('Ingrese un exponente entero: ')) print (restar(83,87)) print (multiplicar(83,87)) print (dividir(83,87)) print (dividir()) print (potenciar(BaseIngresada,ExponenteIngresado)) calcular (sumar,63,67)
SQL
UTF-8
2,014
3.015625
3
[]
no_license
CREATE OR ALTER PROCEDURE TOTAIS_DMED returns ( ra varchar(10), razaosocial varchar(50), vlr_mensal double precision, valorrp1 double precision, valor_total double precision, valorr double precision, pago double precision, valorrps double precision, valortre double precision, final double precision) as BEGIN FOR select ra , RAZAOSOCIAL from clientes where segmento = 0 and GRUPO_CLIENTE = 'ASH' and ((dataresc is null) or (dataresc > '12/31/10')) and cnpj <> '000.000.000-00' order by ra into :ra ,:razaosocial do begin FOR select dm.razaosocial, sum(dm.vlr_mensal) from dmed_mensalidade dm where dm.razaosocial = :razaosocial /*:titular */ group by dm.razaosocial ORDER BY dm.razaosocial INTO :RAZAOSOCIAL,:VLR_MENSAL DO BEGIN /*imprimiu = 'N'; */ valor_total = 0; valorrp1 = 0; pago = 0; select sum(preco) from lan_dmed where lan_dmed.razaosocial = :RAZAOSOCIAL and lan_dmed.preco > 0 INTO :valorRp1 ; begin IF(valorRP1 IS NULL)THEN valorRP1 = 0; valor_total = VLR_MENSAL + valorRP1; end select sum(preco) from lan_dmed where lan_dmed.razaosocial = :RAZAOSOCIAL and lan_dmed.preco < 0 and lan_dmed.produto <> 'REEMB. P/ SOCIOS' INTO :valorR ; begin valor_total = VLR_MENSAL + valorRP1; IF(valorr IS NULL ) THEN VALORR = 0; pago = valor_total + valorR ; select sum(preco) from lan_dmed where lan_dmed.razaosocial = :RAZAOSOCIAL and lan_dmed.preco < 0 and lan_dmed.produto = 'REEMB. P/ SOCIOS' INTO :valorRPS ; begin -- valor_total = VLR_MENSAL + valorRP1; IF(valorRPS IS NULL ) THEN valorRPS = 0; -- pago = pago + valorRPS ; valorTRE = valorR + valorRPS; end end final = valor_total + valorTRE ; SUSPEND; VLR_MENSAL = 0; valor_total = 0 ; valorrp1 = 0; valorr = 0; PAGO =0 ; END end END
PHP
UTF-8
2,370
2.546875
3
[]
no_license
<?php // Damage Engine Copyright 2012-2015 Massive Damage, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under // the License. class Features { static $features = null; static function enabled( $name ) { return array_key_exists($name, static::$features) && static::$features[$name]; } static function disabled( $name ) { return array_key_exists($name, static::$features) && !static::$features[$name]; } static function reset( $name ) { unset(static::$features[$name]); } static function enable( $name ) { static::$features[$name] = true; class_exists("Script") and Script::signal("feature_enabled", $name); } static function disable( $name ) { static::$features[$name] = false; class_exists("Script") and Script::signal("feature_disabled", $name); } static function enable_all( $list ) { foreach( $list as $name ) { static::enable($name); } } static function disable_all( $list ) { foreach( $list as $name ) { static::disable($name); } } static function __callStatic( $name, $args ) { if( substr($name, -8) == "_enabled" ) { return static::enabled(substr($name, 0, -8)); } elseif( substr($name, -9) == "_disabled" ) { return static::disabled(substr($name, 0, -9)); } elseif( substr($name, 0, 7) == "enable_" ) { return static::enable(substr($name, 7)); } elseif( substr($name, 0, 8) == "disable_" ) { return static::disable(substr($name, 8)); } abort($name); } static function initialize() { static::$features = array(); } } Features::initialize();
Java
UTF-8
5,265
2.421875
2
[]
no_license
package CustomerServiceDepartmentworker; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import Users.LoginContol; import client.ChatClient; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import javafx.beans.binding.*; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import Users.LoginContol; /**a controller for the ManageComplaintFrame, * gives the ability to edit an active complaint. * * @author Alex * */ public class ManageComplaintController extends LoginContol implements Initializable { @FXML public Label topic; @FXML public Label details; @FXML public Label customerID; @FXML public TextField topicField; @FXML public TextField detailsField; @FXML public TextField customerIDField; @FXML public Button save; @FXML public Label title; @FXML public Button UpdateProgress; @FXML public Button closeComplaint; public static complaintEntry currentComplaint; public void start(Stage primaryStage) { Parent root; try { root = FXMLLoader .load(getClass().getResource("/CustomerServiceDepartmentworker/ManageComplaintFrame.fxml")); Scene scene = new Scene(root); primaryStage.setTitle("Manage Open Complaint"); // name of the title of the window primaryStage.setScene(scene); primaryStage.show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void initialize(URL location, ResourceBundle resources) { if(CustomerServiceDepartmentworkerMainWindow.pressedComplaintIndex!=-1) { //attach an event to the save button save.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("lol that tickles"); try { SaveButtonClickHandler(event); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); //open a new update progress window on mouse click. UpdateProgress.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UpdateComplaintProgressButton(event); } }); //attach an event handler to the closeComplaint button. closeComplaint.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { closeComplaintButton(event); } }); //get current complaint index. int index=CustomerServiceDepartmentworkerMainWindow.pressedComplaintIndex; //generate a new complaint: currentComplaint=new complaintEntry(CustomerServiceDepartmentworkerMainWindow.activeComplaints.get(index)); //bind the GUI fields topicField.textProperty().bindBidirectional(currentComplaint.getTopic()); detailsField.textProperty().bindBidirectional(currentComplaint.getDetails()); customerIDField.textProperty().bindBidirectional(currentComplaint.getCustomerID()); } } /**save complaint editting button event handles, * sends a request to the server to update the complaint fields * @param event * @throws IOException */ public void SaveButtonClickHandler(ActionEvent event) throws IOException { //save the new data to a new complaint and send it to the server complaint editedComplaint=new complaint(currentComplaint.getCompliantID().getValue(), currentComplaint.getCustomerIDInteger().getValue(), currentComplaint.getEmpHandlingID().getValue(), currentComplaint.getTopic().getValue(), currentComplaint.getTime().getValue(), currentComplaint.getDate().getValue(), currentComplaint.getStatus().getValue(), currentComplaint.getDetails().getValue()); //mark complaint as an edited one editedComplaint.newComplaint=false; int port = LoginContol.PORT; String ip = LoginContol.ServerIP; myClient = new ChatClient(ip, port); // create new client myClient.sendRequestUpdateComplaint(editedComplaint); } /**update Complaint Progress button click handler, * opens a new window were the costumer service employee can update the progress of the * complaint. * @param event */ public void UpdateComplaintProgressButton(ActionEvent event) { /** open a new edit complaint, opens the "ManageComplaintFrame"*/ progressComplaintController editFrame = new progressComplaintController(); try { editFrame.start(new Stage()); } catch (Exception e) { System.out.print("Could not open an edit window\n"); e.printStackTrace(); /* if (mainstage != null) mainstage.toBack();*/ } } /**close the complaint event handler * opens a window for to file a clsing complaint report * @param event */ public void closeComplaintButton(ActionEvent event) { /** opens a closing complaint report window*/ closeComplaintController editFrame = new closeComplaintController(); try { editFrame.start(new Stage()); } catch (Exception e) { System.out.print("Could not open an edit window\n"); e.printStackTrace(); /* if (mainstage != null) mainstage.toBack();*/ } } }
C#
UTF-8
1,827
3.453125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mdfinder { public static class Extensions { /// <summary> Enumerates <paramref name="items"/> into bins of size <paramref name="binSize"/>. </summary> /// <typeparam name="T"> Generic type parameter. </typeparam> /// <param name="items"> The items to act on. </param> /// <param name="binSize"> Size of the bin. </param> /// <returns> /// An enumerator that allows foreach to be used to process bin in this collection. /// </returns> /// <remarks> Thanks to @juharr at Stack Overflow. https://stackoverflow.com/a/32970228/1210377 </remarks> public static IEnumerable<IEnumerable<T>> Bin<T>(this IEnumerable<T> items, int binSize) { if(binSize <= 0) { throw new ArgumentOutOfRangeException("binSize", Localization.Localization.BinSizeOutOfRangeExceptionMessage); } return items.Select((x, i) => new { x, i }) .GroupBy(a => a.i / binSize) .Select(grp => grp.Select(a => a.x)); } /// <summary> An IEnumerable<T> extension method that returns the first item or a given default value if no items are in the collection. </summary> /// <typeparam name="T"> Generic type parameter. </typeparam> /// <param name="items"> The items to act on. </param> /// <param name="default"> The default. </param> /// <returns> A T. </returns> public static T FirstOr<T>(this IEnumerable<T> items, T @default) { foreach(var t in items) { return t; } return @default; } } }
Python
UTF-8
1,305
3.359375
3
[]
no_license
import base64 from Crypto.Cipher import AES from Crypto import Random #stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256 #stackoverflow.com/questions/12562021/aes-decryption-padding-with-pkcs5-python BS = AES.block_size _pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) _unpad = lambda s: s[:-ord(s[len(s)-1:])] class AESCipher: def __init__(self, key): self.key = key def encrypt(self, raw): raw = _pad(raw) iv = Random.new().read(BS) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)) def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new(self.key, AES.MODE_CBC, iv) return _unpad(cipher.decrypt(enc[16:])) ### test-main ### import sys if __name__ == "__main__": if(len(sys.argv) != 2): print "Input missing. Program terminated." print "Usage: ./aes-rsa-crt.py 'input message'" sys.exit(0) else: input = sys.argv[1] print "User input: ", input key = "Not-a-random-key" aes128 = AESCipher(key) ciphertext = aes128.encrypt(input) print ciphertext plaintext = aes128.decrypt(ciphertext) print plaintext
Java
UTF-8
858
2.359375
2
[]
no_license
package com.gd.zhenghy.bean; /** * Created by zhenghy on 2016/7/14. */ public class MenuList { private String title; private int drawableId; private int highlighter; public MenuList() { } public MenuList(String title, int drawableId, int highlighter) { this.title = title; this.drawableId = drawableId; this.highlighter = highlighter; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getDrawableId() { return drawableId; } public void setDrawableId(int drawableId) { this.drawableId = drawableId; } public int getHighlighter() { return highlighter; } public void setHighlighter(int highlighter) { this.highlighter = highlighter; } }
Markdown
UTF-8
3,753
2.875
3
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
--- title: Converting Spreadsheet Dates to Javascript description: "Learn how to convert the {{ site.product }} Spreadsheet date column values from an Excel format to JavaScript." type: how-to page_title: Convert {{ site.product }} Spreadsheet Dates From MS Excel Date Format to JavaScript Date slug: spreadsheet-dates-to-javascript tags: excel dates, format, javascript, date, object, type, convert, spreadsheet, range, value res_type: kb component: spreadsheet --- ## Environment <table> <tr> <td>Product</td> <td>{{ site.product }} Soreadsheet</td> </tr> <tr> <td>Progress {{ site.product }} version</td> <td>Created with the 2023.1.314 version</td> </tr> </table> ## Description I access a range of cells in my Spreadsheet and utilize the [`value`](https://docs.telerik.com/kendo-ui/api/javascript/spreadsheet/range/methods/value) method of the Range's API to extract the date values of the range. However, I get numbers that are not usable in JavaScript. How can I format these dates to JavaScript? ## Solution Date values in the Spreadsheet are converted to numbers internally to maintain compatibility with the specifications of [Microsoft Excel's date formatting](https://xlsxwriter.readthedocs.io/working_with_dates_and_time.html). To convert the formatted dates back to JavaScript, pass the date value to the following __getJsDatesFromExcel__ function: ```JavaScript function getJsDateFromExcel(excelDate){ const SECONDS_IN_DAY = 24 * 60 * 60; const MISSING_LEAP_YEAR_DAY = SECONDS_IN_DAY * 1000; const MAGIC_NUMBER_OF_DAYS = (25567 + 2); if (!Number(excelDate)) { alert('wrong input format') } const delta = excelDate - MAGIC_NUMBER_OF_DAYS; const parsed = delta * MISSING_LEAP_YEAR_DAY; const date = new Date(parsed) return date } var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet"); var sheet = spreadsheet.activeSheet(); var range = sheet.range("B4"); var value = range.value(); var jsValue = getJsDateFromExcel(value); ``` To explore the complete behavior, see the Telerik REPL example on how to [format Excel dates to JavaScript Date objects](https://netcorerepl.telerik.com/GxYdcsPe40nJkVs938). ## More {{ site.framework }} Spreadsheet Resources * [{{ site.framework }} Spreadsheet Documentation]({%slug htmlhelpers_spreadsheet_aspnetcore%}) * [{{ site.framework }} Spreadsheet Demos](https://demos.telerik.com/{{ site.platform }}/spreadsheet/index) {% if site.core %} * [{{ site.framework }} Spreadsheet Product Page](https://www.telerik.com/aspnet-core-ui/spreadsheet) * [Telerik UI for {{ site.framework }} Video Onboarding Course (Free for trial users and license holders)]({%slug virtualclass_uiforcore%}) * [Telerik UI for {{ site.framework }} Forums](https://www.telerik.com/forums/aspnet-core-ui) {% else %} * [{{ site.framework }} Spreadsheet Product Page](https://www.telerik.com/aspnet-mvc/spreadsheet) * [Telerik UI for {{ site.framework }} Video Onboarding Course (Free for trial users and license holders)]({%slug virtualclass_uiformvc%}) * [Telerik UI for {{ site.framework }} Forums](https://www.telerik.com/forums/aspnet-mvc) {% endif %} ## See Also * [Client-Side API Reference of the Spreadsheet's Range for {{ site.framework }}](https://docs.telerik.com/kendo-ui/api/javascript/spreadsheet/range) * [Server-Side API Reference of the Spreadsheet for {{ site.framework }}](https://docs.telerik.com/{{ site.platform }}/api/spreadsheet) * [Telerik UI for {{ site.framework }} Breaking Changes]({%slug breakingchanges_2023%}) * [Telerik UI for {{ site.framework }} Knowledge Base](https://docs.telerik.com/{{ site.platform }}/knowledge-base)
Java
UTF-8
361
3.171875
3
[]
no_license
package demo1; import java.util.Scanner; public class Findingfactors { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("enter the number to find the factor\n"); int no = in.nextInt(); for(int i=1;i<=no;i++) { if(no%i==0) System.out.println(i); } } }
Java
UTF-8
4,216
2.953125
3
[]
no_license
package apitests; import io.restassured.http.ContentType; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static io.restassured.RestAssured.baseURI; import static io.restassured.RestAssured.given; import static org.testng.Assert.assertEquals; import utilities.ConfigurationReader; public class day5_1_CBTrainingWithJsonPath { //day 5.1 @BeforeClass public void beforeclass(){ baseURI= ConfigurationReader.get("cbt_api_url"); } @Test public void test1(){ Response response = given().accept(ContentType.JSON) .and().pathParam("id", 24112) //17982 .when().get("/student/{id}"); //verify status code assertEquals(response.statusCode(),200); //assign response to jsonpath JsonPath jsonPath = response.jsonPath(); //get values from jsonpath String firstName = jsonPath.getString("students.firstName[0]"); System.out.println("firstName = " + firstName); String lastName = jsonPath.get("students.lastName[0]"); System.out.println("lastName = " + lastName); String phone = jsonPath.getString("students.contact[0].phone"); System.out.println("phone = " + phone); //get me city and zipcode, do assertion String city = jsonPath.getString("students.company[0].address.city"); System.out.println("city = " + city); assertEquals(city,"string"); String zipCode = jsonPath.getString("students.company[0].address.zipCode"); System.out.println("zipCode = " + zipCode); assertEquals(zipCode,0); String firstname2 = jsonPath.getString("students.firstName"); System.out.println("firstname2 = " + firstname2); // String firstname3 =response.path("students.firstName"); // System.out.println("firstname3 = " + firstname3); String zipCode2= response.path("students.company[0].address.zipCode"); System.out.println("zipCode2 = " + zipCode2); //try to arraylist and integer with string response path } @Test public void test3(){ //self study Response response = given().accept(ContentType.JSON).and().pathParam("id",24112) .when().get("/student/{id}"); JsonPath jsonPath=response.jsonPath(); System.out.println("response.statusCode() = " + response.statusCode()); int studentId0 = jsonPath.getInt("students.studentId[0]"); System.out.println("d = " + studentId0); System.out.println("response.path(\"student.studentId[0]\") = " + response.path("students.studentId[0]")); Response response2 = given().accept(ContentType.JSON) .and().pathParam("id", 24112) .when().get("/student/{id}"); System.out.println("response.path(\"student.studentId[0]\") = " + response2.path("students.studentId[0]")); // String firstname3 =response.path("students.firstName"); // it complains , you will get error. ArrayList cannot cast to String // System.out.println("firstname3 = " + firstname3); String fistName2 = jsonPath.getString("students.firstName");//but jasonPath can not complain you can get a result inside [Mira] System.out.println("fistName2 = " + fistName2); int zipCode =jsonPath.getInt("students.company[0].address.zipCode"); System.out.println("zipCode = " + zipCode); assertEquals(zipCode,0); String zipCode1 =jsonPath.getString("students.company[0].address.zipCode");// you can convert directyl integer value to String System.out.println("zipCode = " + zipCode1); assertEquals(zipCode,"0"); String zipCode2 =response.path("students.company[0].address.zipCode"); // cannot be cast to String System.out.println("zipCode = " + zipCode2); //response.path you can not int to String but jasonPath possible //assertEquals(zipCode,"0"); System.out.println("response.path(\"students.company[0].address.zipCode\") = " + response.path("students.company[0].address.zipCode")); } }
Python
UTF-8
1,486
2.578125
3
[]
no_license
from django import template from django.conf import settings import os.path register = template.Library() @register.filter(name='split') def split(value, key): """ Returns the value turned into a list. """ return value.split(key) @register.filter(name='color') def color(value): tipo = value.split('|')[1] if tipo == 'distri': return "#a6c4a6" elif tipo == 'eess': return "#aacbe5;" @register.filter(name='product_path') def product_path(value): path = settings.MEDIA_ROOT + 'product/' file = str(value).zfill(5) + '.jpg' # if os.path.isfile(path + file): if os.path.exists(path + file): return path + file else: return path + 'none.webp' @register.filter(name='thumb_product_path') def thumb_product_path(value): """Agregar thumb/ a la ruta de la imagen""" return str(value.name).replace('product/', 'product/thumb/') @register.filter def greeting_to_time(user): import datetime, pytz from django.conf import settings if user.first_name: name = user.first_name if user.last_name: name = name + ' ' + user.last_name else: name = user.username cur_time = datetime.datetime.now(tz=pytz.timezone(str(settings.TIME_ZONE))) if cur_time.hour < 12: return 'Buenos días {}'.format(name) elif cur_time.hour < 20: return 'Buenas tardes {}'.format(name) else: return 'Buena noches {}'.format(name)
JavaScript
UTF-8
1,117
2.96875
3
[ "ISC" ]
permissive
"use strict"; var test = require("tape"); var mapDom = require("./"); var testContents = "<div data-foo='bar'>" + "<div data-index='1' data-cats-are='cool'></div>" + "<div data-index='2' data-cats-are='cool'></div>" + "<div data-index='3' data-cats-are='cool'>Text is ignored! :D</div>" + "<div data-index='4' data-cats-are='cool'></div>" + "</div>"; test("kitchen sink", function(t) { t.plan(1); document.body.innerHTML = testContents; var element = document.body.children[0]; var results = mapDom(element, map); var expected = { foo: "bar", children: [{ index: "1", catsAre: "cool", children: [] }, { index: "2", catsAre: "cool", children: [] }, { index: "3", catsAre: "cool", children: [] }, { index: "4", catsAre: "cool", children: [] }] }; t.deepEqual(results, expected, "mapped tree contains all children and data attributes"); function map(element, children) { var data = toPlainObject(element.dataset); data.children = children(); return data; } function toPlainObject(object) { return JSON.parse(JSON.stringify(object)); } });
C#
UTF-8
2,685
3.453125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment_2 { class Account { private int accountNumber = 1; private static int myaccountnumber; private string accountName; private Double balance; private Address address; private Birthday birthday; //private string v1; //private int v2; public Account(string accountName, double balance, Address address,Birthday birthday) { accountNumber = ++myaccountnumber; this.AccountName = accountName; this.Balance = balance; this.Address = address; this.birthday = birthday; } // /* public Account(string v1, int v2, Address address) // { // this.v1 = v1; // this.v2 = v2; // this.address = address; // } //*/ //public int AccountNumber //{ // set { accountNumber = value; } // get { return accountNumber; } //} public String AccountName { set { this.accountName = value; } get { return accountName; } } public double Balance { set { this.balance = value; } get { return this.balance; } } public Address Address { set { this.address = value; } get { return this.address; } } public void Withdraw(double amount) { if (this.Balance - amount >= 200) { this.Balance = this.Balance - amount; Console.WriteLine("Withdraw successful"); } else { Console.WriteLine("No Balance"); } } public void Deposit(double amount) { this.Balance = this.Balance + amount; Console.WriteLine("Deposit Successful"); } public void Transfer(double amount, Account receiver) { this.Withdraw(amount); receiver.Deposit(amount); Console.WriteLine("Transfer succcessful"); } public void ShowAccountInformation() { Console.WriteLine("Account No:{0}\nAccount Name:{1}\nBalance:{2}", accountNumber, this.accountName, this.balance); Console.WriteLine(this.Address.GetAddress()); } internal void Transfer(int amount, int receiver) { throw new NotImplementedException(); } } }
C#
UTF-8
2,050
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace 建造者模式 { public class ResourcePoolConfig { private String name; public int maxTotal; private int maxIdle; private int minIdle; public string Message { get; set; } private ResourcePoolConfig(Builder builder) { this.name = builder.name; this.maxTotal = builder.maxTotal; this.maxIdle = builder.maxIdle; this.minIdle = builder.minIdle; } //...省略getter方法... //我们将Builder类设计成了ResourcePoolConfig的内部类。 //我们也可以将Builder类设计成独立的非内部类ResourcePoolConfigBuilder。 public class Builder { private const int DEFAULT_MAX_TOTAL = 8; private const int DEFAULT_MAX_IDLE = 8; private const int DEFAULT_MIN_IDLE = 0; public String name; public int maxTotal = DEFAULT_MAX_TOTAL; public int maxIdle = DEFAULT_MAX_IDLE; public int minIdle = DEFAULT_MIN_IDLE; public ResourcePoolConfig build() { // 校验逻辑放到这里来做,包括必填项校验、依赖关系校验、约束条件校验等 return new ResourcePoolConfig(this); } public Builder setName(String name) { this.name = name; return this; } public Builder setMaxTotal(int maxTotal) { this.maxTotal = maxTotal; return this; } public Builder setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; return this; } public Builder setMinIdle(int minIdle) { this.minIdle = minIdle; return this; } } } }
Python
UTF-8
935
3.0625
3
[]
no_license
from PIL import Image, ImageFilter import tkinter as tk image = Image.open('atat.jpg') image = image.filter(ImageFilter.FIND_EDGES) image.save('new_name.png') image = image.convert('1') image.save('new_name2.png') pixels = image.load() width, height = image.size all_pixels = [] coords = [] for x in range(width): for y in range(height): cpixel = pixels[x, y] # bw_value = int(round(sum(cpixel) / float(len(cpixel)))) # if bw_value >= 200: # (x, y, (r,g,b)) # coords.append((x, y, cpixel)) if cpixel == 255: coords.append((x, y)) canvas_width = width canvas_height = height master = tk.Tk() w = tk.Canvas(master, width=canvas_width, height=canvas_height) w.pack() for i in coords: # print(i) x1, y1 = i[0] - 1, i[1] - 1 x2, y2 = i[0] + 1, i[1] + 1 w.create_oval(x1, y1, x2, y2, fill="black") print(width) print(height) tk.mainloop()
SQL
WINDOWS-1250
1,418
2.90625
3
[]
no_license
-------------------------------------------------------- -- DDL for Trigger TRG_HIS_PRODHERENCIA_COLECT -------------------------------------------------------- CREATE OR REPLACE EDITIONABLE TRIGGER "AXIS"."TRG_HIS_PRODHERENCIA_COLECT" BEFORE UPDATE OR DELETE ON PRODHERENCIA_COLECT FOR EACH ROW DECLARE vaccion VARCHAR2(2); BEGIN IF UPDATING THEN vaccion := 'U'; ELSE vaccion := 'D'; END IF; -- crear registro histrico INSERT INTO his_PRODHERENCIA_COLECT( SPRODUC, CAGENTE, CFORPAG, RECFRA, CCLAUSU, CGARANT, FRENOVA, CDURACI, CCORRET, CCOMPANI, CRETORNO, CREVALI, PIREVALI, CTIPCOM, CCOA, CTIPCOB, CBANCAR, CCOBBAN, CDOCREQ, CASEGURADO, CBENEFICIARIO, CUSUALT, FALTA, CUSUMOD, FMODIFI, CUSUHIST,FCREAHIST,ACCION) VALUES( :OLD.SPRODUC, :OLD.CAGENTE, :OLD.CFORPAG, :OLD.RECFRA, :OLD.CCLAUSU, :OLD.CGARANT, :OLD.FRENOVA, :OLD.CDURACI, :OLD.CCORRET, :OLD.CCOMPANI, :OLD.CRETORNO, :OLD.CREVALI, :OLD.PIREVALI, :OLD.CTIPCOM, :OLD.CCOA, :OLD.CTIPCOB, :OLD.CBANCAR, :OLD.CCOBBAN, :OLD.CDOCREQ, :OLD.CASEGURADO, :OLD.CBENEFICIARIO, :OLD.CUSUALT, :OLD.FALTA, :OLD.CUSUMOD, :OLD.FMODIFI, f_user, f_sysdate, ''||vaccion||''); EXCEPTION WHEN OTHERS THEN p_tab_error(f_sysdate, f_user, 'TRIGGER trg_his_PRODHERENCIA_COLECT', 1, SQLCODE, SQLERRM); RAISE; END trg_his_PRODHERENCIA_COLECT; / ALTER TRIGGER "AXIS"."TRG_HIS_PRODHERENCIA_COLECT" ENABLE;
JavaScript
UTF-8
549
2.65625
3
[]
no_license
import World from "../world" export default class HarshWorld { constructor() { this.world = new World(200, 100); this.world.setRules((cell, neighborCount) => { if (cell.alive) return neighborCount === 2 || neighborCount === 3; else return neighborCount === 3; }); this.world.setSeed(cell => { return (Math.random() * 100) > 70; //return cell.index % 3 === 0; }); this.world.initialize(); console.log(this.world._current.toString()); } }
Java
UTF-8
3,283
1.882813
2
[ "BSD-2-Clause" ]
permissive
package com.shinobicontrols.charts; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.view.MotionEvent; import android.view.View.MeasureSpec; import android.view.ViewGroup; import com.shinobicontrols.charts.Annotation.Position; import com.shinobicontrols.charts.ShinobiChart.OnGestureListener; @SuppressLint({"ViewConstructor"}) class w extends ViewGroup { private final cy dB; private final ew dC; private float dD = 0.0f; private float dE = 0.0f; final ag dF; private final fn dG; w(Context context, ag agVar) { super(context); setWillNotDraw(false); this.dF = agVar; this.dB = new cy(agVar.J); this.dC = new ew(agVar.J, this.dB); this.dG = ba.cn() ? new fn(context) : null; } public boolean onTouchEvent(MotionEvent event) { event.offsetLocation(this.dD, this.dE); return this.dC.onTouchEvent(event) || super.onTouchEvent(event); } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = MeasureSpec.getSize(widthMeasureSpec); int size2 = MeasureSpec.getSize(heightMeasureSpec); size = MeasureSpec.makeMeasureSpec(size, Integer.MIN_VALUE); size2 = MeasureSpec.makeMeasureSpec(size2, Integer.MIN_VALUE); if (this.dF.J.ev != null) { this.dF.J.ev.measure(size, size2); } this.dF.J.eN.a(size, size2, Position.IN_FRONT_OF_DATA); } protected void onLayout(boolean changed, int l, int t, int r, int b) { if (this.dF.J.ev != null) { this.dF.J.ev.layout(this.dF.aX.left, this.dF.aX.top, this.dF.aX.right, this.dF.aX.bottom); } this.dF.J.eN.a(this.dF.aX.left, this.dF.aX.top, this.dF.aX.right, this.dF.aX.bottom, Position.IN_FRONT_OF_DATA); if (ba.cn()) { this.dG.c(this.dF.aX.left, this.dF.aX.top, this.dF.aX.right, this.dF.aX.bottom); } } protected void onDraw(Canvas canvas) { canvas.clipRect(this.dF.aX); this.dF.c(canvas); this.dF.d(canvas); } void a(OnGestureListener onGestureListener) { this.dB.a(onGestureListener); } void b(OnGestureListener onGestureListener) { this.dB.b(onGestureListener); } void c(OnGestureListener onGestureListener) { this.dB.c(onGestureListener); } void d(OnGestureListener onGestureListener) { this.dB.d(onGestureListener); } void f(float f) { this.dD = f; } void g(float f) { this.dE = f; } void az() { this.dC.az(); } protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (ba.cn()) { a(canvas); } } private void a(Canvas canvas) { Rect rect = this.dF.aX; int width = rect.left + (rect.width() / 2); width -= this.dG.getWidth() / 2; int height = ((rect.height() / 2) + rect.top) - (this.dG.getHeight() / 2); canvas.save(); canvas.translate((float) width, (float) height); this.dG.draw(canvas); canvas.restore(); } }
Go
UTF-8
387
3.515625
4
[]
no_license
package main import ( "bytes" "fmt" ) func main() { fmt.Println(comma("100")) } func comma(s string) string { sl := len(s) if sl < 4 { return s } var buf bytes.Buffer buf.WriteString(s[:sl%3]) for i, c := range s[sl%3:] { if i%3 == 0 { buf.WriteString(",") } buf.WriteRune(c) } ret := buf.String() if string(ret[0]) == "," { return ret[1:] } return ret }
Java
UTF-8
6,615
1.71875
2
[]
no_license
package com.acerosocotlan.entregasacerosocotlan.controlador; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.acerosocotlan.entregasacerosocotlan.Adaptador.AdapterRecyclerViewEntregaCamion; import com.acerosocotlan.entregasacerosocotlan.Adaptador.AdapterRecyclerViewRutaCamion; import com.acerosocotlan.entregasacerosocotlan.R; import com.acerosocotlan.entregasacerosocotlan.modelo.AvisoPersonal_retrofit; import com.acerosocotlan.entregasacerosocotlan.modelo.EntregasCamion_retrofit; import com.acerosocotlan.entregasacerosocotlan.modelo.InformacionAvisos_retrofit; import com.acerosocotlan.entregasacerosocotlan.modelo.MetodosSharedPreference; import com.acerosocotlan.entregasacerosocotlan.modelo.NetworkAdapter; import com.acerosocotlan.entregasacerosocotlan.modelo.RutaCamion_retrofit; import com.acerosocotlan.entregasacerosocotlan.modelo.ValidacionConexion; import com.squareup.picasso.Picasso; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; public class ActivityEntregas extends AppCompatActivity { //VIEWS private RecyclerView entregaRecycler; //DATOS EXTERNOS private ProgressDialog progressDoalog; //SHARED PREFERENCE private SharedPreferences prs; private SwipeRefreshLayout swipeRefreshLayout; private TextView txt_id_ruta_entregas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_entregas); //Iniciamos los componentes de la vista Inicializador(); /* * swipe refresh sirve para que haga una función al momento de arrastrar el cardview hacia abajo * en este caso vuelve a cargar la lista de entregas */ swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { ObtenerEntrega(); } }); } public void Inicializador(){ prs = getSharedPreferences("Login", Context.MODE_PRIVATE); MetodosSharedPreference.BorrarFolioEntrega(prs); entregaRecycler = (RecyclerView) findViewById(R.id.entregas_recycler); txt_id_ruta_entregas = (TextView) findViewById(R.id.txt_id_ruta_entregas); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout); //configuración de color del swipe refresh layout swipeRefreshLayout.setColorSchemeResources(R.color.colorAzulGoogle); progressDoalog = new ProgressDialog(ActivityEntregas.this); progressDoalog.setMessage("Preparando los datos"); progressDoalog.setCancelable(false); progressDoalog.setProgressStyle(ProgressDialog.STYLE_SPINNER); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); txt_id_ruta_entregas.setText("Esta en la ruta " + MetodosSharedPreference.ObtenerFolioRutaPref(prs)); ObtenerEntrega(); } public void AbrirSinEntregas(){ Intent i = new Intent(ActivityEntregas.this, SinEntregasActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); } //RETROFIT2 public void ObtenerEntrega(){ progressDoalog.show(); Call<List<EntregasCamion_retrofit>> call = NetworkAdapter.getApiService(MetodosSharedPreference.ObtenerPruebaEntregaPref(prs)).EntregasCamiones( "entregasmovil_"+MetodosSharedPreference.ObtenerFolioRutaPref(prs)+"/"+MetodosSharedPreference.getSociedadPref(prs)); call.enqueue(new Callback<List<EntregasCamion_retrofit>>() { @Override public void onResponse(Call<List<EntregasCamion_retrofit>> call, Response<List<EntregasCamion_retrofit>> response) { progressDoalog.dismiss(); if (response.isSuccessful()){ swipeRefreshLayout.setRefreshing(false); List<EntregasCamion_retrofit> entrega_retrofit = response.body(); if(entrega_retrofit.isEmpty()){ AbrirSinEntregas(); }else{ LlenarRecyclerView(entrega_retrofit); } } } @Override public void onFailure(Call<List<EntregasCamion_retrofit>> call, Throwable t) { progressDoalog.dismiss(); swipeRefreshLayout.setRefreshing(false); //MostrarDialogCustomNoConfiguracion(); Log.i("ERROR", t.toString()); } }); } public void LlenarRecyclerView(List<EntregasCamion_retrofit> camion){ LinearLayoutManager l = new LinearLayoutManager(getApplicationContext()); l.setOrientation(LinearLayoutManager.VERTICAL); entregaRecycler.setLayoutManager(l); AdapterRecyclerViewEntregaCamion arv = new AdapterRecyclerViewEntregaCamion(camion,R.layout.cardview_entregas, ActivityEntregas.this, getApplicationContext()); entregaRecycler.setAdapter(arv); } @Override public void onBackPressed() { Intent i = new Intent(ActivityEntregas.this, ScrollingRutasActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); } }
PHP
UTF-8
1,786
2.578125
3
[]
no_license
<html> <head> <title>data show</title> <link rel="stylesheet" href="css/bootstrap.css"/> </head> <body> <?php include ('connection.php'); session_start(); if (isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['password']; //$pass = md5($password); // object oriented query $query = $conn->query("SELECT * FROM users WHERE email = '$email' and pass_word = '$password'"); if ($query->num_rows > 0) { while($row = $query->fetch_assoc()) { //session_start(); $_SESSION['email'] = $row['email']; $_SESSION['pass_word'] = $row['pass_word']; header('Location: show.php'); exit; } } else { echo "User name or password invalid"; } } ?> <div class="container"> <div class="row"> <div class="col-sm-4"> </div> <div class="col-sm-4"> <h1 class="page-header">Sign In</h1> <hr> <form class="form-signin" action="" method="post"> <h2 class="form-signin-heading">Please sign in</h2> <label for="username" class="sr-only">Email address</label> <input type="text" id="username" name="email" class="form-control" placeholder="Email or Username" required autofocus> <label for="password" class="sr-only">Password</label> <input type="password" id="password" name="password" class="form-control" placeholder="Password or your identity number" required> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <input type="submit" class="btn btn-lg btn-primary btn-block" type="submit" name="login" id="admin_login" value="Submit"> </form> </div> <div class="col-sm-4"> </div> </div> </div> <!-- container end--> </body> </html>
JavaScript
UTF-8
2,623
2.734375
3
[]
no_license
var mdns = require('mdns'), util = require('util'), EventEmitter = require('events').EventEmitter, airAPI = require("./"); /** * Returns a new AirLocator that is looking up for ZeptreonAir Devices (Airs) with help of mDNS on the Network and start scanning * The AirLocator sents the following events: * @event start if the Scanner starts scanning * @event serviceUp if a new Air has registered on the mDNS Service * @event serviceDown if the Air has deregistered on the mDNS Service * @event stop if the Scanner stops scanning * @return returns a AirLocator */ var startAirLocator = function() { return new AirLocator(); } module.exports.startAirLocator = startAirLocator; /** * Returns a new AirLocator that is looking up for ZeptreonAir Devices (Airs) with help of mDNS on the Network and start scanning * The AirLocator sents the following events: * @event start if the Scanner starts scanning * @event serviceUp if a new Air has registered on the mDNS Service and sent the Air promise with the event * @event serviceDown if the Air has deregistered on the mDNS Service and sent the Air promise with the event * @event stop if the Scanner stops scanning * @event error if the Scanner stops scanning and sent the error with the event * The AirLocator has the following Methods: * @method startScanning() starts scanning * @method getAllFoundAirs() return all already found airs during scanning * @method stopScanning() stops scanning */ var AirLocator = function() { this.airs = {}; this.browser = mdns.createBrowser(mdns.tcp('zapp')); this.startScanning(); var self = this; EventEmitter.call(this); } util.inherits(AirLocator, EventEmitter); /** * starts scanning */ AirLocator.prototype.startScanning = function() { this.emit('start'); this.browser.on('serviceUp', function(service) { var air_promise = airAPI(service.addresses[0]); this.emit('serviceUp', air_promise); this.airs[service.name] = air_promise; }.bind(this)); this.browser.on("serviceDown", function(service) { if(service.name in this.airs){ air_promise = this.airs[service.name]; this.emit('serviceDown', air_promise); delete this.airs[service.name]; } }.bind(this)); this.browser.start(); } /** * return all already found airs (promise) in an Array during scanning */ AirLocator.prototype.getAllFoundAirs = function(){ return Object.getValues(this.airs); } /** * stops scanning */ AirLocator.prototype.stopScanning = function() { this.browser.stop(); this.emit('stop'); }
C#
UTF-8
2,707
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CSH_projekt { public partial class Form1 : Form { double zoomFactor = 1.5; Image slika; Size novaVelicina; Point mouseLoc = new Point(); bool Dragging = false; public Form1() { InitializeComponent(); } private void zoomInButton_Click(object sender, EventArgs e) { novaVelicina = new Size((int)(novaVelicina.Width * zoomFactor), (int)(novaVelicina.Height * zoomFactor)); pictureBox1.Image = Zoom(slika, novaVelicina); } private void zoomOutButton_Click(object sender, EventArgs e) { novaVelicina = new Size((int)(novaVelicina.Width / zoomFactor), (int)(novaVelicina.Height / zoomFactor)); pictureBox1.Image = Zoom(slika, novaVelicina); } private void uploadImageButton_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Files|*.jpg;*.jpeg;*.png;", Multiselect = false }) if (openFileDialog.ShowDialog() == DialogResult.OK) { String path = openFileDialog.FileName; slika = Image.FromFile(path); pictureBox1.Image = slika; novaVelicina = new Size(slika.Width, slika.Height); } if (slika != null) { zoomInButton.Enabled = true; zoomOutButton.Enabled = true; } } private Image Zoom(Image image, Size size) { Bitmap bmp = new Bitmap(image, size.Width, size.Height); Graphics graphics = Graphics.FromImage(bmp); graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pictureBox1.Size = size; return bmp; } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { Dragging = false; } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { mouseLoc = e.Location; Dragging = true; } } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if(Dragging == false || slika == null) { return; } Point currentMousePos = e.Location; int distanceX = currentMousePos.X - mouseLoc.X; int distanceY = currentMousePos.Y - mouseLoc.Y; int newX = pictureBox1.Location.X + distanceX; int newY = pictureBox1.Location.Y + distanceY; if(newX > panel1.Left && newX < panel1.Right) { pictureBox1.Location = new Point(newX, pictureBox1.Location.Y); } if(newY > panel1.Top && newY < panel1.Bottom) { pictureBox1.Location = new Point(pictureBox1.Location.X, newY); } } } }
Go
UTF-8
1,205
3.453125
3
[]
no_license
package main import "fmt" func profitPairs(sp []int32, target int32) (total int) { var pos int var pairs [][]int32 for { if pos == len(sp) { // looped over every element in the array // exit break } var i, j int var paired bool Loop: for i = pos; i < len(sp); i++ { for j = i + 1; j < len(sp); j++ { if sp[i]+sp[j] == target { paired = true break Loop } } } if paired { pairs = append(pairs, []int32{sp[i], sp[j]}) // remove the paired profits from the array sp = append(sp[:j], sp[j+1:]...) sp = append(sp[:i], sp[i+1:]...) total++ } else { pos++ } } // fmt.Println(pairs) // fmt.Println(total) return total } func main() { fmt.Println(profitPairs([]int32{1, 2, 2, 2, 3, 4, 4, 4}, 5) == 2) fmt.Println(profitPairs([]int32{1, 2, 3, 6, 7, 8, 9, 1}, 10) == 3) fmt.Println(profitPairs([]int32{3, 2, 1, 45, 27, 6, 78, 9, 0}, 9) == 2) fmt.Println(profitPairs([]int32{3, 3, 2, 1, 45, 27, 6, 78, 9, 0}, 9) == 2) fmt.Println(profitPairs([]int32{1, 5, 66, 2, 3, 4, 7, 0, 2, 5}, 7) == 4) fmt.Println(profitPairs([]int32{}, 5) == 0) fmt.Println(profitPairs([]int32{5}, 5) == 0) fmt.Println(profitPairs([]int32{3, 4}, 7) == 1) }
Python
UTF-8
1,222
2.546875
3
[]
no_license
#%% from sklearn.model_selection import train_test_split import torch.utils.data as data import torchvision from torchvision import transforms from PIL import Image class Dataset(data.Dataset): def __init__(self): super().__init__() transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) def __len__(self): return len(self.x) def __getitem__(self, index): with open(path, 'rb') as f: image = Image.open(f) image = image.convert('RGB') return x def load_dataloaders(batch_size=64, seed=0): dataset = data.TensorDataset(torch.tensor(x), torch.tensor(y)) idx = range(10) datasets, dataloaders, indices = {}, {}, {} indices['train'], indices['val'] = train_test_split(idx, test_size=0.2, random_state=seed) for phase in ['train', 'val']: datasets[phase] = data.Subset(dataset, indices[phase]) dataloaders[phase] = data.DataLoader(datasets[phase], batch_size=batch_size, shuffle=True) return datasets, dataloaders
C++
UTF-8
3,513
3.109375
3
[]
no_license
#ifndef PLAYER_PROCESSHITCONTROL_HPP #define PLAYER_PROCESSHITCONTROL_HPP #include "rtos.hpp" #include "ADTs.hpp" #include "IRunGameTask.hpp" #include "Entities.hpp" #include "DisplayControl.hpp" #include "TransferData.hpp" /// @file /// \brief /// Task for Registering Hits from other players /// \details /// the function of this task is to set the playernumber, firepower, and time. After all these variables have been set this task starts the game. /// The playernumber and firepower are set using an keypad. The playerNumber and firepower are set by pressing A or B Respectivly. Followed by a single digit (that is greater than 0). /// The time and the signal to start the game are set by receiving an Message ADT through an rtos channel. /// once the game has been started(a start signal has been received) this task wil be put in an eternal suspend. class ProcessHitControl: public rtos::task<>, public IRunGameTask{ rtos::channel<Message,10> MessagesReceivedRunQueue; rtos::flag StartFlagHit; rtos::flag GameOverFlagHit; rtos::timer ProcessHitTimer; IRunGameTask& gameTimeControl; IRunGameTask& shootControl; RemainingTime& time; HitDatas& hitdatas; PlayerData& playerData; DisplayControl& displayControl; TransferDataControl& transferDataControl; enum class STATE {WAITING_ON_START, GAME_RUNNING}; enum class SUBSTATE {WAITING_ON_HIT, WAITING_ON_TIMER}; HitData hit; void main(); public: ///@fn ProcessHitControl::ProcessHitControl(const unsigned int priority, const char* name, RemainingTime& time, HitDatas& hitdatas, PlayerData& playerData, IRunGameTask& _gameTimeControl, IRunGameTask& _shootControl, DisplayControl& _displayControl): ///@brief The constructor for the ProcessHitControl class. ///@details This contructor creates a ProcessHitControl object. ///@param priority Priority of the task. ///@param name Name of the task. ///@param time Entity object where the remaining game time is stored. ///@param hitdatas Entity object where every hit received is recorded. ///@param playerData Entity object where the players data is stored. ///@param _gameTimeControl RTOS Task that keeps track of the remaining time. ///@param _gameTimeControl RTOS Task that keeps track of the remaining time. ///@param _shootControl RTOS Task for shooting other players ///@param _displayControl RTOS Task for Displaying information ///@param _transferDataControl RTOS Task that is responsible for displaying information at the end of the game ProcessHitControl(const unsigned int priority, const char* name, RemainingTime& time, HitDatas& hitdatas, PlayerData& playerData, IRunGameTask& _gameTimeControl, IRunGameTask& _shootControl, DisplayControl& _displayControl, TransferDataControl& _transferDataControl): task(priority, name), MessagesReceivedRunQueue(this, "MessagesReceivedRunQueue"), StartFlagHit(this, "startFlagHit"), GameOverFlagHit(this, "GameOverFlagHit"), ProcessHitTimer(this, "ProcessHitTimer"), gameTimeControl(_gameTimeControl), shootControl(_shootControl), time(time), hitdatas(hitdatas), playerData(playerData), displayControl(_displayControl), transferDataControl(_transferDataControl){}; ///@fn void ProcessHitControl::Start() ///@brief Starts this task. void Start(); ///@fn void ProcessHitControl::GameOver() ///@brief ends this task. void GameOver(); ///@fn void ProcessHitControl::HitReceived(Message hit) ///@brief call this to start registering a hit. ///@param hit The hit message. void HitReceived(Message hit); }; #endif
Python
UTF-8
2,116
2.703125
3
[]
no_license
#This was mostly a lot of testing. #This wasn't used in production #import busio #import adafruit_amg88xx #import board import time import socket import matplotlib.pyplot as plt import numpy as np import random import queue #queues #from dataclasses import dataclass, field #from typing import Any mAvgCreated = False randArray = [] tmp = [] Mavg = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]] q = queue.Queue(0) #i2c_bus = busio.I2C(board.SCL, board.SDA) #amg = adafruit_amg88xx.AMG88XX(i2c_bus) #amg = adafruit_amg88xx.AMG88XX(i2c_bus, addr=0x69) #plt.ion() #plt.show(block=False) #fig = plt.figure() #str1 = ''.join(str(e) for e in amg.pixels) #print (type(str1)) while True: #data = amg.pixels #create a bunch of random numbers randArray = np.random.randint(0,50, size=(8,8)) #print the array, just so I know you're not broken #for x in randArray: # print(x) if (mAvgCreated): print("New array", randArray) for i in range (0,8): for j in range (0,8): dif = Mavg[i][j] - randArray[i][j] if(abs(dif) > 4): print (abs(dif)) Mavg = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]] if (q.qsize() <= 3): q.put(randArray) print("<=3") #for elem in list(q.queue): # print(elem) else: tmp = q.get() q.put(randArray) print(">3") #for elem in list(q.queue): # print(elem) for i in range (0,8): for j in range (0,8): for elem in list(q.queue): Mavg[i][j] = elem[i][j] + Mavg[i][j] Mavg[i][j] = Mavg[i][j]/4 print("Mavg = ", Mavg) mAvgCreated = True print("Pausing...") time.sleep(10) #working on images #This is my attempt to clear. #if (first == False): # plt.clf() #first = False #basical visualization #ax = fig.add_subplot(111) #h = ax.imshow(randArray, cmap='hot', interpolation='nearest') #h.set() #plt.draw() #lt.show() #fig.canvas.draw() #fig.canvas.flush_events() #plt.canvas.draw() # plt.display.update
C++
UTF-8
487
3.34375
3
[]
no_license
/** * class Tree { * public: * int val; * Tree *left; * Tree *right; * }; */ bool solver(Tree* root, int d, int &rd) { if (!root) return true; if (!root->left && !root->right) { if (rd == -1) rd = d; else { if (d != rd) return false; } return true; } return (solver(root->left, d + 1, rd) && solver(root->right, d + 1, rd)); } bool solve(Tree* root) { int rd = -1; return solver(root, 0, rd); }
Java
UTF-8
1,737
2.359375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package citbyui.cit210.hangman.miscellaneous; /** * * @author Calvin */ public class HangmanGallows { public static final String Gallows1 = "\n\t\t |" + "\n\t\t |"; public static final String Gallows2 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )"; public static final String Gallows3 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )" + "\n\t\t |"; public static final String Gallows4 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )" + "\n\t\t |" + "\n\t\t––|"; public static final String Gallows5 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )" + "\n\t\t |" + "\n\t\t––|––"; public static final String Gallows6 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )" + "\n\t\t |" + "\n\t\t––|––" + "\n\t\t |"; public static final String Gallows7 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )" + "\n\t\t |" + "\n\t\t––|––" + "\n\t\t |" + "\n\t\t / "; public static final String Gallows8 = "\n\t\t |" + "\n\t\t |" + "\n\t\t ( )" + "\n\t\t |" + "\n\t\t––|––" + "\n\t\t |" + "\n\t\t / \\"; }
Python
UTF-8
520
4.34375
4
[]
no_license
# A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,... Faça um programa que gere a série até que # o valor seja maior que 500. termo = 1 f1= f2 = 0 while termo <= 610: # O laço está até 610 porque é o proximo número depois de 500 na sequencia de Fibonacci. if termo == 610: print(termo,end='') f2 = f1 f1 = termo termo = f1 + f2 else: print(termo, end=' ↠ ') f2 = f1 f1 = termo termo = f1 + f2
Python
UTF-8
349
3.421875
3
[]
no_license
#Grasshopper - Grade Book #https://www.codewars.com/kata/55cbd4ba903825f7970000f5 def get_grade(s1, s2, s3): mean = (s1+s2+s3)/3 if 100>=mean and mean>=90: return 'A' elif 90>mean and mean>=80: return 'B' elif 80>mean and mean>=70: return 'C' elif 70>mean and mean>=60: return 'D' return "F"
Python
UTF-8
10,085
3.015625
3
[]
no_license
import numpy as np import math import pickle class Connect4: def __init__(self, width=7, height=6, player1='player1', player2='player2'): self.__board = np.full((height, width), None) self.__pos = width * [height - 1] # list of next available move in each column self.__player1 = player1 self.__player2 = player2 self.__width = width self.__height = height self.__last_move = None # position of last move played self.__last_played = None # name of last player played self.__score = [276, 276] # initial score for each player "hard code" self.__depth = 4 # for difficulty def restart(self, width=7, height=6): self.__board = np.full((height, width), None) self.__pos = width * [height - 1] self.__width = width self.__height = height self.__last_move = None self.__last_played = None self.__score = [276, 276] #aywa hard code def save(self): try: dict = {} with open('state.p', 'wb') as handle: dict['board'] = self.__board dict['pos'] = self.__pos dict['player1'] = self.__player1 dict['player2'] = self.__player2 dict['width'] = self.__width dict['height'] = self.__height dict['last_move'] = self.__last_move dict['last_played'] = self.__last_played dict['score'] = self.__score pickle.dump(dict, handle) return 1 except: return 0 def load(self): try: with open('state.p', 'rb') as handle: dict = pickle.load(handle) self.__board = dict['board'] self.__pos = dict['pos'] self.__player1 = dict['player1'] self.__player2 = dict['player2'] self.__width = dict['width'] self.__height = dict['height'] self.__last_move = dict['last_move'] self.__last_played = dict['last_played'] self.__score = dict['score'] return 1 except: return 0 def play(self, player, col): row = self.__pos[col] assert row >= 0, 'this column is full can\'t put more pieces in it' assert player in [self.__player1, self.__player2], '{} is not a player in this game'.format(player) self.__board[row][col] = player self.__pos[col] -= 1 self.__last_move = (row, col) self.__last_played = player cost = self.cost(row, col) index = player is self.__player2 self.__score[(index+1)%2] -= cost ret = self.is_winner(self.get_full_state()) if ret == 1: print('game ended,', self.__last_played, 'is winner!') return 1 elif ret == -1: print('game ended, there is no winner!!!') return 0 elif index: return self.AI_play() def set_depth(self, d): self.__depth = d def get_state(self): return self.__board def get_full_state(self): return self.__last_played, self.__last_move, self.__score, self.__board def get_player1(self): return self.__player1 def get_player2(self): return self.__player2 def set_player1(self, player_name): assert not self.__board.any(), 'player name can\'t be set during the game' self.__player1 = player_name def set_player2(self, player_name): assert not self.__board.any(), 'player name can\'t be set during the game' self.__player2 = player_name def is_winner(self, state): player, (posh, posw),_ , board = state height, width = board.shape #detect vertical if posh < height-3: i = 0 while i < 4: if board[posh+i][posw]!=player: break i+=1 else: return 1 #detect horizontal i = max(0, posw-3) j = min(width, posw+4) count = 0 while i < j: if board[posh][i] != player: count = 0 else: count += 1 i+=1 if count >= 4: return 1 #detect diagonal / low = min(height-posh-1, posw, 3) #i, j = posh+low, posw-low high = min(posh, width-posw-1, 3) #i, j = posh-high, posw+high if high + low > 2: count = 0 i, j = posh+low, posw-low while i >= posh-high: if board[i][j] != player: count = 0 else: count += 1 i-=1; j+=1 if count >= 4: return 1 #detect diagonal \ low = min(height-posh-1, width-posw-1, 3) #i, j = posh+low, posw+low high = min(posh, posw, 3) #i, j = posh-high, posw-high if high + low > 2: count = 0 i, j = posh+low, posw+low while i >= posh-high: if board[i][j] != player: count = 0 else: count += 1 i-=1; j-=1 if count >= 4: return 1 if None in board: return 0 return -1 def next_state(self, state): players = self.__player1, self.__player2 index = state[0] is self.__player1 player_name = players[index] initial_board = state[3] height, width = initial_board.shape boards = [] for j in range(width): board = initial_board.copy() if board[0][j] is None: col_free_flag = 0 for i in range(1,height): if board[i][j] is not None: col_free_flag = 1 #the column not empty board[i-1][j] = player_name cost = self.cost(i-1, j) score = [None, None] score[(index+1)%2] = state[2][(index+1)%2] - cost score[index] = state[2][index] boards.append(( player_name, (i-1, j), score, board )) break if col_free_flag==0: board[height-1][j] = player_name cost = self.cost(height-1, j) score = [None, None] score[(index+1)%2] = state[2][(index+1)%2] - cost score[index] = state[2][index] boards.append(( player_name, (height-1, j), score, board )) return boards def eval_state(self, state, depth): player = state[0] ret = self.is_winner(state) if ret == 1: if player == self.__player1: return 1000*depth else: return -1000*depth elif ret == -1: return 0 else: cost = ((player is self.__player1)*2-1) * self.cost(*state[1]) return state[2][0] - state[2][1] + cost def cost(self, posh, posw): c = 4 - math.ceil(abs(posh-2.5)) # all destroyed vertical patterns c += 4 - abs(posw-3) # all destroyed horizontal patterns if posw == 0 or posw == 6: # following conditions to get all destroyed diagonal patterns c += 1 elif posw == 1 or posw == 5: c += 4 - math.ceil(abs(posh-2.5)) elif posw == 2 or posw == 4: c += 6 - 2*abs(posh-2.5) elif posw == 3: c += 2 * (4 - math.ceil(abs(posh-2.5))) return int(c) def dfs(self, state, path, alpha, beta ,depth, AI): if depth > 0: if self.is_winner(state) == 1: if AI: alpha = max(alpha, -1000*(depth+1)) else: beta = min(beta, 1000*(depth+1)) else: best_path = path modified = False for i, s in enumerate(self.next_state(state)): new_path, new_alpha, new_beta = self.dfs(s, path+[i], alpha, beta, depth-1, not AI) if AI: if new_beta > alpha: alpha = new_beta; modified = True else: if new_alpha < beta: beta = new_alpha; modified = True if modified: best_path = new_path; modified = False if alpha >= beta: #cut off break path = best_path else: score = self.eval_state(state, depth+1) if AI: alpha = max(alpha, score) else: beta = min(beta, score) return path, alpha, beta def AI_play(self): state = self.get_full_state() alpha, beta = -float("inf"), float("inf") path = [] depth = self.__depth path, new_alpha, new_beta = self.dfs(state, path, alpha, beta, depth, True) n_states = self.next_state(state) index = path[0] return self.play(self.__player1, n_states[index][1][1]) def start(self, first_play, col=None): assert not self.__board.any(), 'the game have already started' if first_play == self.__player1: self.play(first_play, np.random.randint(self.__width)) else: assert col in range(self.__width), 'invalid column to play' self.play(first_play, col) def show(self): p1 = self.__player1 p2 = self.__player2 length = max(len(p1), len(p2), 4) for i in self.__board: for j in i: print(str(j).ljust(length), end=" ") print()
Shell
UTF-8
505
3.890625
4
[]
no_license
#!/bin/bash if [ "$#" -ne 1 ] ; then echo "Please supply the domain name: $0 flamingcowpie.net" exit -1 fi DOMAIN=$1 CRT=$DOMAIN.crt KEY=$DOMAIN.key PFX="$DOMAIN".pfx if [ ! -f $CRT ] ; then echo "No $CRT found, have you actually copied-in the certificates you were issued?" exit -1 fi if [ ! -f $KEY ] ; then echo "No $KEY file found" exit -1 fi if [ -f $PFX ] ; then echo "$PFX already exists, exiting." exit -1 fi openssl pkcs12 -inkey $KEY -in $CRT -export -out $PFX echo "Created $PFX"
Python
UTF-8
581
4.53125
5
[]
no_license
#Exercício 35 – Analisando Triângulo v1.0 #Desenvolva um programa que leia o comprimento de três retas #e diga ao usuário se elas podem ou não formar um triângulo. print('Analisador de triângulos: ') reta1 = float(input('Digite a 1° reta: ')) reta2 = float(input('Digite a 2° reta: ')) reta3 = float(input('Digite a 3° reta: ')) if reta1 < reta2 + reta3 and reta2 < reta3 + reta1 and reta3 < reta1 + reta2:#Formula para saber se três retas #formam um triângulo print('Elas podem formar um triângulo!') else: print('Elas não podem formar um triângulo!')
Java
UTF-8
1,424
3.1875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.GeneticProgramming.gp.symbolic.example; /** * * @author Anna Dina */ import com.Genetic.gp.symbolic.ExpressionFitness; import com.GeneticProgramming.gp.symbolic.interpreter.Context; import com.GeneticProgramming.gp.symbolic.interpreter.Expression; public class Antiderivative implements ExpressionFitness { private static double dx = 1e-2; @Override public double fitness(Expression expression, Context context) { double delt = 0; // To guarantee monotonic of evolved antiderivative // the best approach is to trace each point through intervals of dx // for (double x = -10; x < 10; x += dx) { // but for small dx it works extremly slow for (double x = -10; x < 10; x += 1) { double target = this.targetDerivative(x); double exprDerivative = this.expressionDerivative(expression, context, x); delt += this.sqr(target - exprDerivative); } return delt; } private double expressionDerivative(Expression expression, Context context, double x) { context.setVariable("x", x); double exprX = expression.eval(context); context.setVariable("x", x + dx); double exprXPlusdX = expression.eval(context); return (exprXPlusdX - exprX) / dx; } private double targetDerivative(double x) { return x * Math.sin(x); } private double sqr(double x) { return x * x; } }
Rust
UTF-8
1,484
3.03125
3
[]
no_license
use std::io::{Error as IoError, ErrorKind}; use std::string::ToString; use futures::{Async, Poll}; use futures::future::Future; use super::entity::{Todo, TodoStatus}; pub enum TodoRepository { Error, Create(Todo), Read(usize), Update(Todo), Delete(usize) } impl Future for TodoRepository { type Item = Option<Todo>; type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self { &mut TodoRepository::Create(_) => { // TODO INSERT INTO DB Err(IoError::new(ErrorKind::Other, "Not implemented")) } &mut TodoRepository::Read(id) => { // TODO SELECT FROM DB Ok(Async::Ready(Some(Todo::new( id, "Do your future homework".to_string(), "Do your future homework using futures".to_string(), TodoStatus::InProgress )))) }, &mut TodoRepository::Update(_) => { // TODO UPDATE INTO DB Err(IoError::new(ErrorKind::Other, "Not implemented")) }, &mut TodoRepository::Delete(_) => { // TODO DELETE FROM DB Err(IoError::new(ErrorKind::Other, "Not implemented")) } &mut TodoRepository::Error => { Err(IoError::new(ErrorKind::Other, "Not implemented")) } } } }
Markdown
UTF-8
7,608
2.671875
3
[ "MIT" ]
permissive
--- title: "My Unrequited Love for Isolate Scope" authors: johnnyreilly tags: [Directives, TypeScript, javascript, UI Bootstrap, Isolated Scope, AngularJS] hide_table_of_contents: false --- [I wrote a little while ago about creating a directive to present server errors on the screen in an Angular application](http://icanmakethiswork.blogspot.com/2014/08/angularjs-meet-aspnet-server-validation.html). In my own (not so humble opinion), it was really quite nice. I was particularly proud of my usage of isolate scope. However, pride comes before a fall. It turns out that using isolate scope in a directive is not always wise. Or rather – not always possible. And this is why: `Error: [$compile:multidir] Multiple directives [datepickerPopup, serverError] asking for new/isolated scope on: &lt;input name="sage.dateOfBirth" class="col-xs-12 col-sm-9" type="text" value="" ng-click="vm.dateOfBirthDatePickerOpen()" server-error="vm.errors" ng-model="vm.sage.dateOfBirth" is-open="vm.dateOfBirthDatePickerIsOpen" datepicker-popup="dd MMM yyyy"&gt; `Ug. What happened here? Well, I had a date field that I was using my serverError directive on. Nothing too controversial there. The problem came when I tried to plug in [UI Bootstrap’s datepicker](http://angular-ui.github.io/bootstrap/) as well. That’s right the directives are fighting. Sad face. To be more precise, it turns out that only one directive on an element is allowed to create an isolated scope. So if I want to use UI Bootstrap’s datepicker (and I do) – well my serverError directive is toast. ## A New Hope So ladies and gentlemen, let me present serverError 2.0 – this time without isolated scope: ### serverError.ts ```ts (function () { "use strict"; var app = angular.module("app"); // Plant a validation message to the right of the element when it is declared invalid by the server app.directive("serverError", [function () { // Usage: // <input class="col-xs-12 col-sm-9" // name="sage.name" ng-model="vm.sage.name" server-error="vm.errors" /> var directive = { link: link, restrict: "A", require: "ngModel" // supply the ngModel controller as the 4th parameter in the link function }; return directive; function link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModelController: ng.INgModelController) { // Extract values from attributes (deliberately not using isolated scope) var errorKey: string = attrs["name"]; // eg "sage.name" var errorDictionaryExpression: string = attrs["serverError"]; // eg "vm.errors" // Bootstrap alert template for error var template = '<div class="alert alert-danger col-xs-9 col-xs-offset-2" role="alert"><i class="glyphicon glyphicon-warning-sign larger"></i> %error%</div>'; // Create an element to hold the validation message var decorator = angular.element('<div></div>'); element.after(decorator); // Watch ngModelController.$error.server & show/hide validation accordingly scope.$watch(safeWatch(() => ngModelController.$error.server), showHideValidation); function showHideValidation(serverError: boolean) { // Display an error if serverError is true otherwise clear the element var errorHtml = ""; if (serverError) { var errorDictionary: { [field: string]: string } = scope.$eval(errorDictionaryExpression); errorHtml = template.replace(/%error%/, errorDictionary[errorKey] || "Unknown error occurred..."); } decorator.html(errorHtml); } // wipe the server error message upon keyup or change events so can revalidate with server element.on("keyup change", (event) => { scope.$apply(() => { ngModelController.$setValidity("server", true); }); }); } }]); // Thanks @Basarat! http://stackoverflow.com/a/24863256/761388 function safeWatch<T extends Function>(expression: T) { return () => { try { return expression(); } catch (e) { return null; } }; } })(); ``` ### serverError.js ```js (function () { "use strict"; var app = angular.module("app"); // Plant a validation message to the right of the element when it is declared invalid by the server app.directive("serverError", [function () { // Usage: // <input class="col-xs-12 col-sm-9" // name="sage.name" ng-model="vm.sage.name" server-error="vm.errors" /> var directive = { link: link, restrict: "A", require: "ngModel" }; return directive; function link(scope, element, attrs, ngModelController) { // Extract values from attributes (deliberately not using isolated scope) var errorKey = attrs["name"]; var errorDictionaryExpression = attrs["serverError"]; // Bootstrap alert template for error var template = '<div class="alert alert-danger col-xs-9 col-xs-offset-2" role="alert"><i class="glyphicon glyphicon-warning-sign larger"></i> %error%</div>'; // Create an element to hold the validation message var decorator = angular.element('<div></div>'); element.after(decorator); // Watch ngModelController.$error.server & show/hide validation accordingly scope.$watch(safeWatch(function () { return ngModelController.$error.server; }), showHideValidation); function showHideValidation(serverError) { // Display an error if serverError is true otherwise clear the element var errorHtml = ""; if (serverError) { var errorDictionary = scope.$eval(errorDictionaryExpression); errorHtml = template.replace(/%error%/, errorDictionary[errorKey] || "Unknown error occurred..."); } decorator.html(errorHtml); } // wipe the server error message upon keyup or change events so can revalidate with server element.on("keyup change", function (event) { scope.$apply(function () { ngModelController.$setValidity("server", true); }); }); } }]); // Thanks @Basarat! http://stackoverflow.com/a/24863256/761388 function safeWatch(expression) { return function () { try { return expression(); } catch (e) { return null; } }; } })(); ``` This version of the serverError directive is from a users perspective identical to the previous version. But it doesn’t use isolated scope – this means it can be used in concert with other directives which do. It works by pulling the `name` and `serverError` values off the attrs parameter. `name` is just a string - the value of which never changes so it can be used as is. `serverError` is an expression that represents the error dictionary that is used to store the server error messages. This is accessed through use of `scope.$eval` as an when it needs to. ## My Plea What I’ve outlined here works. I’ll admit that usage of `$eval` makes me feel a little bit dirty (I’ve got [“eval is evil”](http://www.jslint.com/lint.html#evil) running through my head). Whilst it works, I’m not sure what I’ve done is necessarily best practice. After all [the Angular docs themselves say](https://docs.angularjs.org/guide/directive): > ***Best Practice:** Use the scope option to create isolate scopes when making components that you want to reuse throughout your app. * But as we’ve seen this isn’t always an option. I’ve written this post to document my own particular struggle and ask the question “is there a better way?” If you know then please tell me!
Swift
UTF-8
574
2.71875
3
[]
no_license
// // Course.swift // DeepProProd // // Created by Mushtaque Ahmed on 1/23/18. // Copyright © 2018 Mushtaque Ahmed. All rights reserved. // import Foundation enum LevelNames : String, Codable { case Basic case Intermediate case Advanced // ... } struct LevelList: Codable { struct Levels: Codable { let levelname: LevelNames let chapters: [Chapters] struct Chapters : Codable{ let name: String let isLocked: Bool let completedPercentage: Int? } } let levels : [Levels] }
Java
UTF-8
3,144
2.09375
2
[]
no_license
package com.yanpeng.website.service.manager.menu; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springside.modules.orm.hibernate.Page; import org.springside.modules.orm.hibernate.SimpleHibernateTemplate; import com.yanpeng.website.bean.entity.TGroups; import com.yanpeng.website.bean.entity.TMenus; import com.yanpeng.website.bean.entity.TUsers; import com.yanpeng.website.service.exception.ServiceException; /** * * @author yanpeng * */ @Service @Transactional public class MenuManager { private SimpleHibernateTemplate<TMenus, String> menuDao; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { menuDao = new SimpleHibernateTemplate<TMenus, String>(sessionFactory, TMenus.class); } @Transactional(readOnly = true) public List<TMenus> getMenusByIds(List rolesList) { Page page = new Page(); page.setOrder("asc"); page.setOrderBy("sort"); return menuDao.findByCriteria(page, Restrictions.in("id", rolesList)).getResult(); // return menuDao.createQuery("", rolesList.toArray()).list(); // return menuDao.findByCriteria(Restrictions.in("id", rolesList)); } @Transactional(readOnly = true) public Page<TMenus> findList(Page<TMenus> page, Map<String, Object> conditionsMap) { Criterion []criterion = new Criterion[conditionsMap.size()]; int cnt = 0; for(Iterator<String> names = conditionsMap.keySet().iterator();names.hasNext();) { String key = (String) names.next(); if(key.equals("displayName")) { criterion[cnt] = Restrictions.like("displayName", (String) conditionsMap.get(key), MatchMode.ANYWHERE); cnt++; }else if(key.equals("disabled")) { criterion[cnt] = Restrictions.eq("disabled", conditionsMap.get(key)); cnt++; } else if(key.equals("parentId")) { criterion[cnt] = Restrictions.like("TMenus.id", (String) conditionsMap.get(key), MatchMode.EXACT); cnt++; } } return menuDao.findByCriteria(page, criterion); } @Transactional(readOnly = true) public TMenus getMenu(String id) { return menuDao.get(id); } @Transactional(readOnly = true) public Page<TMenus> getAllMenus(Page<TMenus> page) { page.setOrder("asc"); page.setOrderBy("sort"); return menuDao.findAll(page); } public void saveMenu(TMenus menu) { menuDao.save(menu); } @Transactional(readOnly = true) public boolean isDisplayNameUnique(String displayName, String oldDisplayName) { return menuDao.isPropertyUnique("displayName", displayName, oldDisplayName); } // private void OrganizationalConditions(List<Map<String, Object>> conditionList, Criterion criterions){ // // } }
Python
UTF-8
74
3.09375
3
[]
no_license
n = int(raw_input()) if n == 1: print 2 elif n < 3: print 1 else: print 0
Python
UTF-8
33
2.796875
3
[]
no_license
a=int("enter number") print(a*a)
C++
UTF-8
4,050
2.75
3
[]
no_license
#pragma once #include "Collidable.h" #include "CollidableGroupBase.h" #include <set> #include <iostream> #include "Visualizer.h" template< typename C> //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> A Template Class that generates all the Collidable Groups that you have Registered. See testGo in the DemoFiles /// for a example of how this is used</summary> /// /// <remarks> Theonlyhunter, 3/13/2015. </remarks> //////////////////////////////////////////////////////////////////////////////////////////////////// class CollidableGroup : public CollidableGroupBase { friend class CollisionManager; friend class CollidableGroup; template <class T> friend class CollisionSingleProcessor; template <class T, class T2> friend class CollisionPairProcessor; //why is this template call needed? public: // Vectors for the Group Box static Vect MaxPoint; static Vect MinPoint; typedef std::set<C*> CollidableCollection; static void Register(C* p) { Instance().CollideCol.insert(p); //inserts into the CollideCollection //printf("I registered\n"); } static void deregister(C* p) { Instance().CollideCol.erase(p); //printf("I deregistered\n"); } static CollidableGroup<C>& Instance() { if(!gameInstance) gameInstance = new CollidableGroup<C>(); return *gameInstance; } void CleanUp() { delete gameInstance; } ~CollidableGroup() { Instance().CollideCol.clear(); gameInstance = NULL; } void UpdateVolData() { //printf("UpdateDatawas called \n"); if(!CollideCol.empty()) { for( CollidableCollection::iterator it_mine =Instance().CollideCol.begin(); it_mine != Instance().CollideCol.end(); ++it_mine) { //printf("UpdateDatawas called\n"); (*it_mine)->colVol; //these need to call update data (*it_mine)->outerSphere; } GroupBox(); } } //create Group aabb static void GroupBox() { std::set<C*>::iterator it = Instance().CollideCol.begin(); Instance().MaxPoint = (*it)->outerSphere->GetCenter(); Instance().MinPoint = (*it)->outerSphere->GetCenter(); for (it = Instance().CollideCol.begin(); it != Instance().CollideCol.end(); ++it) { Vect center = (*it)->outerSphere->GetCenter(); float rad = (*it)->outerSphere->GetRadius(); if(center[x] + rad > Instance().MaxPoint[x]) Instance().MaxPoint[x] = center[x] + rad; if(center[y] + rad > Instance().MaxPoint[y]) Instance().MaxPoint[y] = center[y] + rad; if(center[z] + rad > Instance().MaxPoint[z]) Instance().MaxPoint[z] = center[z] + rad; if(center[x] - rad < Instance().MinPoint[x]) Instance().MinPoint[x] = center[x] - rad; if(center[y] - rad < Instance().MinPoint[y]) Instance().MinPoint[y] = center[y] - rad; if(center[z] - rad < Instance().MinPoint[z]) Instance().MinPoint[z] = center[z] - rad; } //Visualizer::ShowAABB(Instance().MaxPoint, Instance().MinPoint, Vect(1,0,0)); } void Cleanup() { delete gameInstance; } private: CollidableCollection CollideCol; static CollidableGroup<C>* gameInstance; CollidableGroup<C>(){ CollideCol = std::set<C*>(); } //I really don't want this CollidableGroup<C>( const CollidableGroup<C> & ){} CollidableGroup<C>& operator = (const CollidableGroup<C>& ){ } //Delete this block when it is working to see if needed /*virtual ~CollidableGroup<C>(){ gameInstance().CollideCol.clear(); gameInstance = NULL; }*/ /*CollidableGroup(){}; CollidableGroup(const CollidableGroup&){}; CollidableGroup& operator=(const CollidableGroup&){}; static CollidableGroup<C>* gameInstance; */ }; template <typename C> CollidableGroup<C>* CollidableGroup<C>::gameInstance = NULL; //makes the game instance for each collidable group template <class C> Vect CollidableGroup<C>::MaxPoint = Vect(IceBlockMath::negativevalue,IceBlockMath::negativevalue,IceBlockMath::negativevalue); template <class C> Vect CollidableGroup<C>::MinPoint = Vect(IceBlockMath::positivevalue,IceBlockMath::positivevalue,IceBlockMath::positivevalue);
C#
UTF-8
1,108
2.703125
3
[]
no_license
// <copyright file="Program.cs" company="ALCPU"> // Copyright (c) 2010 All Right Reserved // </copyright> // <author>Arthur Liberman</author> // <email>Arthur_Liberman@hotmail.com</email> // <date>04-14-2010</date> // <summary>Holds the entry point function.</summary> namespace SolutionConverter { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; /// <summary> /// The main class which holds the program's entry point method. /// </summary> public static class Program { /// <summary> /// The main entry point for the application. /// </summary> /// <param name="args">The command line arguments.</param> [STAThread] public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Length > 0) { Application.Run(new Form1(args[0])); } else { Application.Run(new Form1()); } } } }
Java
UTF-8
944
2.578125
3
[]
no_license
package com.aitorgonzalez.challenge.service; import java.util.List; import java.util.Optional; import org.springframework.messaging.Message; import com.aitorgonzalez.challenge.vo.PokemonVO; import me.sargunvohra.lib.pokekotlin.model.Pokemon; /** * Service to manage Pokemons. * * @author aitor */ public interface PokemonService { public Optional<List<PokemonVO>> findByName(String name); /** * Calls the Message Producer to create a new request to search for Pokemons. * * @param name the name of the Pokemon. * @return the generated message. */ public Optional<Message<String>> findByNameAsync(String name); /** * Wraps a Pokemon into a Pokemon VO. * * @param pokemon the pokemon to wrap * @return the pokemon VO to return on the Controller */ default PokemonVO getPokemonVO(Pokemon pokemon) { return pokemon != null ? PokemonVO.builder().pokemon(pokemon).build() : PokemonVO.builder().build(); } }
PHP
UTF-8
11,797
2.84375
3
[]
no_license
<html> <head> <!-- 1er test --> <meta charset="utf-8" /> <title>Dictionnaire Francais/tiếng Việt</title> <link rel="stylesheet" href="includes/style.css" /> </head> <body> <?php $current = "bd"; session_start(); include("includes/menu.php"); $mot=''; ?> <?php try{ $bdd = new PDO('mysql:host=localhost;dbname=frenchvietnamesedictionnary;charset=utf8', 'root', ''); $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $e){ die('Erreur : ' . $e->getMessage()); } // Modification du mot if(isset($_GET["altertable"])&& ($_GET["altertable"]== 'true')){ if($_POST["pays"]=="fr"){ $req = $bdd->query('SELECT idF from motfr where mot="'.$_POST["mot"].'"'); $id = $req -> fetch(); $idF = $id["idF"]; $req->closeCursor(); if(!empty(trim($_POST["Description"]))){ $Description = $_POST["Description"]; $req = $bdd->prepare('INSERT INTO descriptionfr(idF,Description) VALUES(:idF,:Description)'); $req->execute(array( 'idF' => $idF, 'Description' => $Description, )); $req->closeCursor(); echo '<p class=green> Nouvelle description prise en compte</p>'; } else{ echo '<p class=red> Pas de nouvelle description</p>'; } $Traduction = $_POST['Traduction']; if(!empty(trim($_POST['Traduction']))){ $req = $bdd->prepare('INSERT INTO motvi(FL,Freq,mot) VALUES(:FL,:Freq,:mot)'); $req->execute(array( 'FL' => $Traduction[0], 'Freq' => 0, 'mot' => $Traduction )); echo '<p class=green>Nouvelle traduction pour '.$_POST["mot"].' : '.$_POST["Traduction"].'</p>'; $req->closeCursor(); $req = $bdd->query("SELECT idV from motvi where mot='$Traduction'"); $id = $req -> fetch(); $idV = $id["idV"]; $req = $bdd->prepare('INSERT INTO traduction(idF,idV) VALUES(:idF,:idV)'); $req->execute(array( 'idF' => $idF, 'idV' => $idV, )); $req->closeCursor(); echo '<p class=green> Nouvelle traduction prise en compte</p>'; } else{ echo '<p class=red> Pas de nouvelle traduction</p>'; } } if($_POST["pays"]=="vi"){ $req = $bdd->query('SELECT idV from motvi where mot="'.$_POST["mot"].'"'); $id = $req -> fetch(); $idV = $id["idV"]; $req->closeCursor(); if(!empty(trim($_POST["Description"]))){ $Description = $_POST["Description"]; $req = $bdd->prepare('INSERT INTO descriptionvi(idV,Description) VALUES(:idV,:Description)'); $req->execute(array( 'idV' => $idV, 'Description' => $Description, )); $req->closeCursor(); echo '<p class=green> Nouvelle description prise en compte</p>'; } else{ echo '<p class=red> Pas de nouvelle description</p>'; } $Traduction = $_POST['Traduction']; if(!empty(trim($_POST["Traduction"]))){ $req = $bdd->prepare('INSERT INTO motfr(FL,Freq,mot) VALUES(:FL,:Freq,:mot)'); $req->execute(array( 'FL' => $Traduction[0], 'Freq' => 0, 'mot' => $Traduction )); echo '<p class=green>Nouvelle traduction pour '.$_POST["mot"].' : '.$_POST["Traduction"].'</p>'; $req->closeCursor(); $req = $bdd->query("SELECT idF from motfr where mot='$Traduction'"); $id = $req -> fetch(); $idF = $id["idF"]; echo $idF; echo $idV; $req = $bdd->prepare('INSERT INTO traduction(idF,idV) VALUES(:idF,:idV)'); $req->execute(array( 'idF' => $idF, 'idV' => $idV )); $req->closeCursor(); echo '<p class=green> Nouvelle traduction prise en compte</p>'; } else{ echo '<p class=red> Pas de nouvelle traduction</p>'; } } } // Entrée d'un nouveau mot if(isset($_GET["altertable"])&& ($_GET["altertable"]== 'false')){ $Traduction = $_POST['Traduction']; $mot = $_POST['mot']; if($_POST["pays"]=="fr"){ $req3 = $bdd->query("SELECT mot from motfr where mot='$mot'"); if(!($res = $req3 -> fetch())){ $req = $bdd->prepare('INSERT INTO motfr(FL,Freq,mot) VALUES(:FL,:Freq,:mot)'); $req->execute(array( 'FL' => $mot[0], 'Freq' => 0, 'mot' => $mot )); $req->closeCursor(); echo '<p class=green> Un nouveau mot a été ajouté à la base de données</p>'; $req = $bdd->query('SELECT idF from motfr where mot="'.$_POST["mot"].'"'); $id = $req -> fetch(); $idF = $id["idF"]; $req->closeCursor(); $Description = $_POST["Description"]; if(!empty(trim($_POST["Description"]))){ $req = $bdd->prepare('INSERT INTO descriptionfr(idF,Description) VALUES(:idF,:Description)'); $req->execute(array( 'idF' => $idF, 'Description' => $Description, )); $req->closeCursor(); echo "<p class=green> Un nouvelle Description a été ajouté au mot : ".$_POST["mot"]." !"; } if(!empty(trim($_POST["Traduction"]))){ $req2 = $bdd->query("SELECT mot from motvi where mot='$Traduction'"); if(!($res = $req2 -> fetch())){ $req = $bdd->prepare('INSERT INTO motvi(FL,Freq,mot) VALUES(:FL,:Freq,:mot)'); $req->execute(array( 'FL' => $Traduction[0], 'Freq' => 0, 'mot' => $Traduction )); echo '<p class=green>Nouvelle traduction pour '.$_POST["mot"].' : '.$_POST["Traduction"].'</p>'; $req->closeCursor(); } else{ echo '<p class=green>Lien de traduction pour '.$_POST["mot"].' : '.$_POST["Traduction"].'</p>'; } $req = $bdd->query("SELECT idF from motfr where mot='$mot'"); $id = $req -> fetch(); $idF = $id["idF"]; $req->closeCursor(); $req = $bdd->query("SELECT idV from motvi where mot='$Traduction'"); $id = $req -> fetch(); $idV = $id["idV"]; $req->closeCursor(); $req = $bdd->prepare('INSERT INTO traduction(idF,idV) VALUES(:idF,:idV)'); $req->execute(array( 'idF' => $idF, 'idV' => $idV )); } } else{ echo '<p class=red> Le mot existe déjà </p>'; } } if($_POST["pays"]=="vi"){ $req3 = $bdd->query("SELECT mot from motvi where mot='$mot'"); if(!($res = $req3 -> fetch())){ $req = $bdd->prepare('INSERT INTO motvi(FL,Freq,mot) VALUES(:FL,:Freq,:mot)'); $req->execute(array( 'FL' => $mot[0], 'Freq' => 0, 'mot' => $mot )); $req->closeCursor(); echo '<p class=green> Un nouveau mot a été ajouté à la base de données</p>'; $req = $bdd->query('SELECT idV from motvi where mot="'.$_POST["mot"].'"'); $id = $req -> fetch(); $idV = $id["idV"]; $req->closeCursor(); $Description = $_POST["Description"]; if(!empty(trim($_POST["Description"]))){ $req = $bdd->prepare('INSERT INTO descriptionv)'); $req->execute(array( 'idV' => $idV, 'Description' => $Description, )); $req->closeCursor(); echo "<p class=green> Un nouvelle Description a été ajouté au mot : ".$_POST["mot"]." !"; } if(!empty(trim($_POST["Traduction"]))) { $req2 = $bdd->query("SELECT mot from motfr where mot='$Traduction'"); if(!($res = $req2 -> fetch())){ $req = $bdd->prepare('INSERT INTO motfr(FL,Freq,mot) VALUES(:FL,:Freq,:mot)'); $req->execute(array( 'FL' => $Traduction[0], 'Freq' => 0, 'mot' => $Traduction )); echo '<p class=green>Nouvelle traduction pour '.$_POST["mot"].' : '.$_POST["Traduction"].'</p>'; $req->closeCursor(); } else{ echo '<p class=green>Lien de traduction pour '.$_POST["mot"].' : '.$_POST["Traduction"].'</p>'; } $req = $bdd->query("SELECT idV from motvi where mot='$mot'"); $id = $req -> fetch(); $idV = $id["idV"]; $req->closeCursor(); $req = $bdd->query("SELECT idF from motfr where mot='$Traduction'"); $id = $req -> fetch(); $idF = $id["idF"]; $req->closeCursor(); $req = $bdd->prepare('INSERT INTO traduction(idF,idV) VALUES(:idF,:idV)'); $req->execute(array( 'idF' => $idF, 'idV' => $idV )); } } else{ echo '<p class=red> Le mot existe déjà </p>'; } } } if (isset($_SESSION['idU']) && isset($_SESSION['pseudo'])){ include("includes/formbd.php"); } else{ echo ' <p> Vous devez être connecté pour voir cette page! </p>'; } ?> <?php include("includes/pied.php"); ?> </body> </html>
Java
UTF-8
2,823
2.671875
3
[]
no_license
package com.test.demo.service; import com.test.demo.entity.Stock; import com.test.demo.repository.StockRepository; import org.hibernate.StaleStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class StockService { private StockRepository repository; private Logger LOG = LoggerFactory.getLogger(StockService.class); @Autowired public StockService(StockRepository repository) { this.repository = repository; } public Stock findStock(int id) { return repository.findById(id).orElse(null); } @Retryable(value = {StaleStateException.class}, maxAttempts = 5) @Transactional(propagation = Propagation.REQUIRES_NEW) public Stock addStock(int id, int value, int delay) { Stock stock = repository.findById(id).orElse(null); if (stock == null) { return null; } LOG.info("Stock: " + stock.getStockId() + " Quantity: " + stock.getStockQuantity() +" increasing in " + value); stock.setStockQuantity(stock.getStockQuantity() + value); LOG.info("Stock: " + stock.getStockId() + " New Quantity " + stock.getStockQuantity()); if (delay > 0) { try { Thread.sleep(delay * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } Stock result = repository.save(stock); LOG.info("Stock: " + result.getStockId() + " saved"); return result; } @Retryable(value = {StaleStateException.class}, maxAttempts = 5) @Transactional(propagation = Propagation.REQUIRES_NEW) public Stock decreaseStock(int id, int value, int delay) { Stock stock = repository.findById(id).orElse(null); if (stock == null) { return null; } LOG.info("Stock: " + stock.getStockId() + " Quantity: " + stock.getStockQuantity() +" decreasing in " + value); stock.setStockQuantity(stock.getStockQuantity() - value); LOG.info("Stock: " + stock.getStockId() + " New Quantity " + stock.getStockQuantity()); if (delay > 0) { try { Thread.sleep(delay * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } Stock result = repository.save(stock); LOG.info("Stock: " + result.getStockId() + " saved"); return result; } }
JavaScript
UTF-8
187
2.578125
3
[]
no_license
const toggle = document.querySelector('.toggler'); const collapse = document.querySelector('.nav-collapse'); toggle.addEventListener('click', ()=>{ collapse.classList.toggle('show') });
C++
UTF-8
813
3.140625
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dh; ListNode* pre = &dh; int ac = 0; while (l1 || l2 || ac > 0) { int sum = ac; if (l1) sum += l1->val; if (l2) sum += l2->val; ListNode* n = new ListNode(sum % 10, nullptr); ac = sum / 10; pre->next = n; pre = pre->next; if (l1) l1 = l1->next; if (l2) l2 = l2->next; } return dh.next; } };
Java
UTF-8
1,057
3.25
3
[]
no_license
package ru.examples.fileIOExample; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileExampleNIO { public static void main(String[] args) throws IOException { StringBuilder data = new StringBuilder(); RandomAccessFile aFile = new RandomAccessFile("ReadMe.md", "rw"); FileChannel inChannel = aFile.getChannel(); char ch; ByteBuffer buf = ByteBuffer.allocate(64); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while (buf.hasRemaining()) { ch = (char) buf.get(); System.out.print(ch); data.append(ch); } System.out.print("\n"); buf.clear(); bytesRead = inChannel.read(buf); } aFile.close(); System.out.println("\n==============================\n" + data.toString()); } }
Python
UTF-8
547
2.796875
3
[]
no_license
from matplotlib import pyplot as plt import numpy as np import argparse import cv2 # fetching the arguments and save in dictionary ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Enter path to the image") args = vars(ap.parse_args()) # loading and converting the image into numpy array image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("GRAY", gray) cv2.waitKey(0) eq = cv2.equalizeHist(gray) cv2.imshow("Equilised" , np.hstack( [ gray , eq ] )) cv2.waitKey(0)
Python
UTF-8
778
3.390625
3
[]
no_license
from typing import List, Tuple, TypeVar T = TypeVar('T', int, float, str) def min_max(array: List[T]) -> Tuple[int, int]: isOdd: bool = len(array) % 2 min_el = float('inf') max_el = -float('inf') if isOdd: min_el = array[0] max_el = array[0] else: if array[0] < array[1]: min_el = array[0] max_el = array[1] else: min_el = array[1] max_el = array[0] start_index = 1 if isOdd else 2 for i in range(start_index, len(array), 2): if array[i] < array[i+1]: if min_el > array[i]: min_el = array[i] if max_el < array[i+1]: max_el = array[i+1] else: if min_el > array[i+1]: min_el = array[i+1] if max_el < array[i]: max_el = array[i] return [min_el, max_el]
Java
UTF-8
1,523
2.5625
3
[]
no_license
package com.mydomain.employeecontrol.api.repositories; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; 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.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.mydomain.employeecontrol.api.entities.Company; import com.mydomain.employeecontrol.api.repositories.CompanyRepository; @RunWith(SpringRunner.class) @SpringBootTest // o Spring criara um contexto de teste usando a classe 'SpringRunner' @ActiveProfiles("test") // defina o Profile 'test' para usar nossas configuracoes de teste. public class CompanyRepositoryTest { @Autowired private CompanyRepository empresaRepository; private static final String CNPJ = "51463645000100"; @Before public void setUp() throws Exception{ // Antes do teste sera criado uma empresa no banco de dados H2 Company empresa = new Company(); empresa.setCompanyName("Company de exemplo"); empresa.setCnpj(CNPJ); this.empresaRepository.save(empresa); } @After public final void tearDown() { // depois do teste sera removido toda empresa testada no banco de dados. this.empresaRepository.deleteAll(); } @Test public void testBuscarPorCnpj() { Company empresa = this.empresaRepository.findByCnpj(CNPJ); assertEquals(CNPJ, empresa.getCnpj()); } }
Swift
UTF-8
1,525
2.828125
3
[]
no_license
// // CurrencyService.swift // Forex // // Created by Subedi, Rikesh on 14/01/21. // import SwiftUI import Combine protocol Service { associatedtype T:Codable var baseURL: URL {get} var path: String {get} var parameters: [String:Any] {get} var headers: [String: Any]? {get} } extension Service { var request: URLRequest { guard var urlComponent = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: true) else { fatalError() } urlComponent.queryItems = parameters.map({ (keyValue) -> URLQueryItem in return URLQueryItem(name: keyValue.key, value: "\(keyValue.value)") }) let request = URLRequest(url: urlComponent.url!) return request } func execute() -> AnyPublisher<T, Error> { return APIClient() .run(request) .map(\.value) .eraseToAnyPublisher() } } enum CurrencyService: Service { typealias T = ExchangeResponse case getExchangeList(src: String = "USD") var baseURL: URL { return URL(string: "http://api.currencylayer.com")! } var path: String { switch self { case .getExchangeList: return "/live" } } var parameters: [String : Any] { switch self { case .getExchangeList(let src): return ["source": src, "access_key": "62f418a3130418ac9e645df3125de789", "format": "1"] } } var headers: [String : Any]? { return [:] } }
C++
UTF-8
878
3.296875
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; class Solution { private: vector<vector<int>> vec; vector<int> mv; public: vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { if(root != NULL){ mv.push_back(root->val); // 找到了 if(root->val == expectNumber && root->left == NULL && root->right == NULL){ vec.push_back(vector<int>{mv}); } // 小于,则去子树中找 if(root->val < expectNumber){ FindPath(root->left, expectNumber-root->val); FindPath(root->right, expectNumber-root->val); } mv.pop_back(); } return vec; } };