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
Shell
UTF-8
2,587
2.515625
3
[]
no_license
#!/bin/sh echo "================================================================================" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "================================================================================" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n\n\t\t$0" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ date" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt date >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ set -x" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt set -x echo "\n$ pwd" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt ; pwd >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ sudo service postgresql start" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt sudo service postgresql start >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ sudo service nginx start" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt sudo service nginx start >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ pwd" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt ; pwd >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ cd /home/kit/kit/ " >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt cd /home/kit/kit/ echo "\n$ pwd" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt ; pwd >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ sudo nohup shotgun config.ru -p 9000 -o 0.0.0.0 & " >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt sudo nohup shotgun config.ru -p 9000 -o 0.0.0.0 & >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt # ################################################################################ # echo "================================================================================" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n\n\t\tChecking status of VM ...\n" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ sudo lsof -i tcp:9000" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt sudo lsof -i tcp:9000 >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ sudo service postgresql status" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt sudo service postgresql status >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n$ sudo service nginx status" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt sudo service nginx status >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt echo "\n[DONE]\n================================================================================" >> /home/kit/kit/uploads/snk/kitvm/log_rc-local.txt
C++
UTF-8
3,440
2.703125
3
[]
no_license
#define BOOST_TEST_MAIN #include <boost/test/included/unit_test.hpp> #include "../src/neuron/neuron.hpp" #include "../src/layers/layer.hpp" #include "../src/neuralNetwork/neuralNetwork.hpp" BOOST_AUTO_TEST_SUITE(testNeuralNetwork) BOOST_AUTO_TEST_CASE(testGetNeuronQuantity) { NeuralNetwork neuralNetwork({1, 2, 4}, false); BOOST_CHECK_EQUAL(neuralNetwork[0]->getNeuronQuantity(), 1); BOOST_CHECK_EQUAL(neuralNetwork[1]->getNeuronQuantity(), 2); BOOST_CHECK_EQUAL(neuralNetwork[2]->getNeuronQuantity(), 4); } BOOST_AUTO_TEST_CASE(testSetInputData) { NeuralNetwork neuralNetwork({3, 2, 4}, false); neuralNetwork.feedForward({0, 1, 2}); BOOST_CHECK_CLOSE((*neuralNetwork[0])[0]->getInput(), 0, 0.1); BOOST_CHECK_CLOSE((*neuralNetwork[0])[1]->getInput(), 1, 0.1); BOOST_CHECK_CLOSE((*neuralNetwork[0])[2]->getInput(), 2, 0.1); } BOOST_AUTO_TEST_CASE(testForceDataFrom1To2) { NeuralNetwork neuralNetwork({2, 2, 2}, false); (*neuralNetwork[0])[0]->setWeight(0, 0.5); (*neuralNetwork[0])[0]->setWeight(1, 0.1); (*neuralNetwork[0])[1]->setWeight(0, 0.2); (*neuralNetwork[0])[1]->setWeight(1, 1); neuralNetwork.feedForward({1, 1}); BOOST_CHECK_CLOSE((*neuralNetwork[1])[0]->getInput(), 0.7, 0.1); BOOST_CHECK_CLOSE((*neuralNetwork[1])[1]->getInput(), 1.1, 0.1); BOOST_CHECK_CLOSE((*neuralNetwork[1])[0]->getOutput(), 0.668, 0.1); BOOST_CHECK_CLOSE((*neuralNetwork[1])[1]->getOutput(), 0.750, 0.1); } BOOST_AUTO_TEST_CASE(testForceDataFrom2To3) { NeuralNetwork neuralNetwork({2, 2, 2}, false); (*neuralNetwork[0])[0]->setWeight(0, 0.5); (*neuralNetwork[0])[0]->setWeight(1, 0.1); (*neuralNetwork[0])[1]->setWeight(0, 0.2); (*neuralNetwork[0])[1]->setWeight(1, 1); (*neuralNetwork[1])[0]->setWeight(0, 0.3); (*neuralNetwork[1])[0]->setWeight(1, 0.4); (*neuralNetwork[1])[1]->setWeight(0, 0.1); (*neuralNetwork[1])[1]->setWeight(1, 0.9); neuralNetwork.feedForward({1, 1}); BOOST_CHECK_CLOSE((*neuralNetwork[2])[0]->getInput(), 0.275, 1); BOOST_CHECK_CLOSE((*neuralNetwork[2])[1]->getInput(), 0.942, 1); BOOST_CHECK_CLOSE((*neuralNetwork[2])[0]->getOutput(), 0.568, 1); BOOST_CHECK_CLOSE((*neuralNetwork[2])[1]->getOutput(), 0.719, 1); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(testNeuron) BOOST_AUTO_TEST_CASE(testSetGetInput) { Neuron neuron; neuron.setInput(1); BOOST_CHECK_CLOSE(neuron.getInput(), 1, 0.1); } BOOST_AUTO_TEST_CASE(testSetGetOutput) { Neuron neuron; neuron.setOutput(1); BOOST_CHECK_CLOSE(neuron.getOutput(), 1, 0.1); } BOOST_AUTO_TEST_CASE(testActivation1) { Neuron neuron; neuron.setInput(1); neuron.activation(); BOOST_CHECK_CLOSE(neuron.getOutput(), 0.731, 0.1); } BOOST_AUTO_TEST_CASE(testActivation2) { Neuron neuron; neuron.setInput(10); neuron.activation(); BOOST_CHECK_CLOSE(neuron.getOutput(), 0.999, 0.1); } BOOST_AUTO_TEST_CASE(testSetGetWeight) { Neuron neuron; neuron.setWeights(4); neuron.setWeight(0, 0); neuron.setWeight(1, 1); neuron.setWeight(2, 2); neuron.setWeight(3, 3); BOOST_CHECK_CLOSE(neuron.getWeight(0), 0, 0.1); BOOST_CHECK_CLOSE(neuron.getWeight(1), 1, 0.1); BOOST_CHECK_CLOSE(neuron.getWeight(2), 2, 0.1); BOOST_CHECK_CLOSE(neuron.getWeight(3), 3, 0.1); } BOOST_AUTO_TEST_SUITE_END()
Java
UTF-8
2,432
2.296875
2
[]
no_license
package com.gzzhwl.rest.springmvc.annotation.support; import java.util.Map; import javax.servlet.ServletException; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver; import com.gzzhwl.core.data.model.AccountInfo; import com.gzzhwl.rest.exception.ExceptionCodeDef; import com.gzzhwl.rest.exception.RestException; import com.gzzhwl.rest.security.AuthorizationService; import com.gzzhwl.rest.springmvc.annotation.Authorization; public class AuthorizationArgumentResolver extends AbstractNamedValueMethodArgumentResolver { @Autowired private AuthorizationService authorizationService; @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(Authorization.class) && !Map.class.isAssignableFrom(parameter.getParameterType()); } @Override protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { Authorization annotation = parameter.getParameterAnnotation(Authorization.class); return new AuthorizationValueInfo(annotation); } @Override protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception { String authorization = request.getHeader(name); if (StringUtils.isEmpty(authorization)) { authorization = request.getParameter(name); } if (authorization != null) { AccountInfo accountInfo = authorizationService.getCurrentAccount(authorization); if (AccountInfo.class.isAssignableFrom(parameter.getParameterType())) { return accountInfo; } else { return accountInfo.getAccountId(); } } else { return null; } } @Override protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException { Class<?> paramType = parameter.getParameterType(); if (!paramType.getName().equals("java.util.Optional")) { throw new RestException(ExceptionCodeDef.SC_MISSING_FORBIDDEN, "token不存在");// token不存在,不支持匿名访问。 } } private class AuthorizationValueInfo extends NamedValueInfo { private AuthorizationValueInfo(Authorization annotation) { super(annotation.value(), annotation.required(), annotation.defaultValue()); } } }
PHP
UTF-8
1,303
2.796875
3
[]
no_license
<?php namespace Models; class FriendRequestAcceptHandler { public static function getDB() { require ("Cread.php"); return new \PDO("mysql:dbname={$creden['database']};host={$creden['host']}" , $creden['username'] , $creden['password']); } public static function acceptFR($user1 , $user2) { $db = self::getDB(); $me = 1; if($user1>$user2) { $temp = $user1; $user1 = $user2; $user2 = $temp; $me = 2; } $checkQuery = $db->prepare("SELECT * FROM relations WHERE user1 = :user1 AND user2 = :user2"); $checkQuery->bindValue(":user1" , $user1 , \PDO::PARAM_INT); $checkQuery->bindValue(":user2" , $user2 , \PDO::PARAM_INT); $checkQuery->execute(); if($row = $checkQuery->fetch(\PDO::FETCH_ASSOC)){ $status = $row['status']; if($status==3) return 2; if($status==1 || $status==2){ if($me==$status) return 3; $statement = $db->prepare("UPDATE relations SET status = 3 WHERE user1 = :user1 AND user2 = :user2"); $statement->bindValue(":user1" , $user1 , \PDO::PARAM_INT); $statement->bindValue(":user2" , $user2 , \PDO::PARAM_INT); $result = $statement->execute(); if($result) return 0; else return 7; } if($status==0){ return 1; } }else{ return 1; } } } ?>
Python
UTF-8
1,913
3.125
3
[]
no_license
# Lane Detection in images using mouse click event """ Right click -- To see your ROI Left click -- To detect lanes """ import cv2 import numpy as np def click_event(event, x,y,flags,param): if event == cv2.EVENT_LBUTTONDOWN: img = cv2.imread('road.jpg') roi_ver = [(0, height), (x, y), (width, height)] gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) canny_img = cv2.Canny(gray_img, 100, 200) cropped_img = roi(canny_img, np.array([roi_ver], np.int32)) lines = cv2.HoughLinesP(cropped_img, rho=6, theta=np.pi/60, threshold=160, lines=np.array([]), minLineLength=40, maxLineGap=25) img_with_lines = draw_lines(img, lines) cv2.imshow('image', img_with_lines) return if event == cv2.EVENT_RBUTTONDOWN: img = cv2.imread('road.jpg') img = cv2.line(img, (0,height), (x,y), (0,255,0), 2) img = cv2.line(img, (width,height), (x,y), (0,255,0), 2) cv2.imshow('road', img) return def roi(img, vertices): mask = np.zeros_like(img) match_mask_color = (255,) #* channel_count cv2.fillPoly(mask, vertices, match_mask_color) masked_img = cv2.bitwise_and(img, mask) cv2.imshow('masked', masked_img) return masked_img def draw_lines(img, lines): img = np.copy(img) blank_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) for line in lines: for x1, y1, x2, y2 in line: cv2.line(blank_img, (x1,y1), (x2,y2), (0,255,0), 2) img = cv2.addWeighted(img, 0.8, blank_img, 1, 0.0) return img img = cv2.imread('road.jpg') print(img.shape) height = img.shape[0] width = img.shape[1] cv2.imshow('road', img) cv2.setMouseCallback('road', click_event) cv2.waitKey(0) cv2.destroyAllWindows()
Shell
UTF-8
3,088
2.71875
3
[]
no_license
#------------------# #--- Env Distns ---# #------------------# wd=~/projects/ms1/analysis/huj_eobs src=~/projects/ms1/src panelOut=figs/env_dist figOut=~/projects/ms1/docs/ms/submission_natcom/submission_3/v25/figs cd $wd #Generate distributions for environmental variables dat=~/projects/ms1/data/derived/obs_anno.csv envs=(dist2forest dist2urban ndvi pct_bare pct_tree) outs=("${envs[@]/%/.pdf}") outs=("${outs[@]/#/$panelOut/}") for i in "${!envs[@]}"; do echo "Generating plot for ${envs[i]}" echo "Saving plot to ${outs[i]}" $src/figs/env_dist.r $dat ${outs[i]} ${envs[i]} -t done #Combine panels into a single figure cpdf "${outs[@]}" -o $figOut/S6.pdf #---------------------------------------------# #---- Repeatability under null hypotheses ----# #---------------------------------------------# #Didn't make a formal script for this yet. See poc/rpt_null.r #------------------# #---- Env maps ----# #------------------# wd=~/projects/ms1/analysis/huj_eobs src=~/projects/ms1/src cd $wd #---- Process layers ----# gcs=gs://mol-playground/benc/layer_export/huj_eobs out=/Volumes/WD4TB/projects/ms1/data/derived/layers #Exported all of these using layers/export_image.js gsutil -m cp $gcs/pct_tree.tif $out/pct_tree.tif gsutil -m cp $gcs/pct_bare.tif $out/pct_bare.tif gsutil -m cp $gcs/dist2forest.tif $out/dist2forest.tif gsutil -m cp $gcs/dist2urban.tif $out/dist2urban.tif #Exported ndvi_mean using layers/ndvi/mosiac_mean gsutil -m cp $gcs/ndvi_mean.tif $out/ndvi_mean_utm32n.tif #Exported ndvi_mean using layers/ndvi/mosiac_cv gsutil -m cp $gcs/ndvi_cv.tif $out/ndvi_cv_utm32n.tif #--- Set nodata values ---# gdal_edit.py -a_nodata 255 $layers/pct_tree.tif gdal_edit.py -a_nodata 255 $layers/pct_bare.tif #--- Convert wgs84 layers to utm32n layers=/Volumes/WD4TB/projects/ms1/data/derived/layers gdalwarp -tr 30 30 -tap -t_srs EPSG:32632 -co COMPRESS=LZW -r near $layers/pct_tree.tif $layers/pct_tree_utm32n.tif gdalwarp -tr 30 30 -tap -t_srs EPSG:32632 -co COMPRESS=LZW -r near $layers/pct_bare.tif $layers/pct_bare_utm32n.tif gdalwarp -tr 30 30 -tap -t_srs EPSG:32632 -co COMPRESS=LZW -r near $layers/dist2forest.tif $layers/dist2forest_utm32n.tif gdalwarp -tr 30 30 -tap -t_srs EPSG:32632 -co COMPRESS=LZW -r near $layers/dist2urban.tif $layers/dist2urban_utm32n.tif #--- Make the individual panels wd=~/projects/ms1/analysis/huj_eobs src=~/projects/ms1/src figout=/Users/benc/projects/ms1/docs/ms/submission_natcom/submission_3/v27/figs cd $wd buf=20000 $src/figs/env_maps.r 11.75705 52.95542 $buf figs/env_panels/beuster $src/figs/env_maps.r 11.03707 52.44954 $buf figs/env_panels/dromling $src/figs/env_maps.r 12.05762 52.13555 $buf figs/env_panels/loburg panels=(dist2forest.pdf dist2urban.pdf ndvi_mean.pdf ndvi_cv.pdf pct_bare.pdf pct_tree.pdf) #--- Beuster ---# figs=${panels[@]/#/figs/env_panels/beuster/} cpdf $figs -o $figout/S8.pdf #--- Dromling ---# figs=${panels[@]/#/figs/env_panels/dromling/} cpdf $figs -o $figout/S9.pdf #--- Loburg ---# figs=${panels[@]/#/figs/env_panels/loburg/} cpdf $figs -o $figout/S10.pdf
TypeScript
UTF-8
979
2.609375
3
[ "Apache-2.0" ]
permissive
/*! * Copyright 2021 Cognite AS */ import * as THREE from 'three'; import { vec3 } from 'gl-matrix'; import { Box3 } from './Box3'; export function toThreeVector3(out: THREE.Vector3, v: vec3): THREE.Vector3 { out.set(v[0], v[1], v[2]); return out; } function fromThreeVector3(out: vec3, m: THREE.Vector3): vec3 { const original = vec3.set(out, m.x, m.y, m.z); return original; } const toThreeJsBox3Vars = { outMin: new THREE.Vector3(), outMax: new THREE.Vector3() }; export function toThreeJsBox3(out: THREE.Box3, box: Box3): THREE.Box3 { const { outMin, outMax } = toThreeJsBox3Vars; out.set(toThreeVector3(outMin, box.min), toThreeVector3(outMax, box.max)); return out; } const fromThreeJsBox3Vars = { min: vec3.create(), max: vec3.create() }; export function fromThreeJsBox3(box: THREE.Box3): Box3 { const { min, max } = fromThreeJsBox3Vars; fromThreeVector3(min, box.min); fromThreeVector3(max, box.max); return new Box3([min, max]); }
PHP
UTF-8
742
2.6875
3
[]
no_license
<?php include("libs/LIB_parse.php"); # Include parse library include("libs/LIB_http.php"); # Include PHP/CURL library // Download the page $web_page = http_get($target="http://www.pals.gr", $referer=""); // Remove all JavaScript $noformat = remove($web_page['FILE'], "<script", "</script>"); // Strip out all HTML formatting $formatted = strip_tags($noformat); // Remove Special characters $formatted = str_replace("\t", "", $formatted); // Remove tabs $formatted = str_replace("&nbsp;", "", $formatted); // Remove &nbsp $formatted = str_replace("\n", "", $formatted); // Remove line feeds // Removes White Space echo $formatted; //Write file $file = fopen("clean.txt","w"); echo fwrite($file,$formatted); fclose($file); ?>
C
UTF-8
302
2.96875
3
[]
no_license
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include "libft.h" int main(int ac, char **av) { if (ac > 1) { printf("Num : %d (%c)\n", atoi(av[1]), (char)atoi(av[1])); printf("Libc : %d\n", isascii(atoi(av[1]))); printf("Out : %d\n", ft_isascii(atoi(av[1]))); } return (0); }
Python
UTF-8
566
2.546875
3
[]
no_license
from django import template from colour import Color register = template.Library() @register.filter(name='npc_kill_colour') def npc_kill_colour(value): colors = [ Color('white'), Color('#54C45E'), Color('#76A654'), Color('#98884A'), Color('#BA6B41'), Color('#DC4D37'), ] if value is None or type(value) == str: return colors[0] kills = value if kills < 5: return colors[0] elif kills <= 1000: return colors[(kills + 199) // 200] else: return colors[-1]
Shell
UTF-8
519
2.5625
3
[]
no_license
#!/bin/bash -eux # --disable-vmmraw: disable building 32-bit guest additions iso ./configure \ --target-arch=amd64 \ --target-cpu=k8 \ --with-linux="$(echo /lib/modules/*.x86_64/build/)" \ --disable-hardening \ --disable-java \ --disable-docs \ --disable-vmmraw source ./env.sh kmk all cd ./out/linux.amd64/release/bin/src # The variable KERN_DIR must be a kernel build folder and # end with /build without a trailing slash, or KERN_VER must be set. ub_make \ KERN_DIR="$(echo /lib/modules/*.x86_64/build)"
JavaScript
UTF-8
1,298
3.046875
3
[]
no_license
var paragraphError; var inputs; function validateError(){ var comparationDays = (dateFinishValue>dateStartValue) if((dateStartValue == "")||(comparationDays == false)){ inputs = document.querySelector("#error-date-start"); addError(); paragraphError.textContent = "Data de início inválida"; } if((dateFinishValue == "")||(comparationDays == false)){ inputs = document.querySelector("#error-date-finish"); addError(); paragraphError.textContent = "Data de témino inválida"; } if((lastWageValue == "")||(lastWageValue <=0)){ inputs = document.querySelector("#error-last-wage"); addError(); paragraphError.textContent = "Ultimo salário inválido"; } if(numberDependentsValue == ""){ inputs = document.querySelector("#error-number-dependents"); addError(); paragraphError.textContent = "Número de dependentes inválido"; } } function addError(){ paragraphError = document.createElement("p"); paragraphError.classList.add("paragraph-error"); inputs.appendChild(paragraphError); Swal.fire({ title: 'Erro!', text: 'Preencha os campos corretamente', icon: 'error', confirmButtonText: 'OK', }) count++; }
C++
UTF-8
398
3.28125
3
[]
no_license
// // Created by carmen on 13/08/2015. // #include <iostream> int main() { bool a{true}; bool b{false}; std::cout << "Is 4 = 4 (true or false)?\n"; std::cin >> std::boolalpha >> a; std::cout << "Is 3 = 4 (true or false)?\n"; std:: cin >> std::noboolalpha >> b; std::cout << "a = " << std::boolalpha << a << ", b = " << std::noboolalpha << b << "\n"; return 0; }
C
UTF-8
2,034
3.046875
3
[]
no_license
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_strtrim.c :+: :+: */ /* +:+ */ /* By: mmeyer <mmeyer@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/11/09 17:19:17 by mmeyer #+# #+# */ /* Updated: 2020/11/13 11:20:47 by mmeyer ######## odam.nl */ /* */ /* ************************************************************************** */ #include "libft.h" static int cmp_with_set(char c, const char *set) { int i; i = 0; while (set[i]) { if (c == set[i]) return (1); i++; } return (0); } static int find_start(char const *s1, char const *set) { int start; start = 0; while (cmp_with_set(s1[start], set)) ++start; return (start); } static int find_end(char const *s1, char const *set) { int end; const int s1_len = ft_strlen(s1); end = s1_len - 1; while (cmp_with_set(s1[end], set) && end > 0) --end; return (end); } static int calc_new_str_len(char const *s1, char const *set, int *start) { const int end = find_end(s1, set); *start = find_start(s1, set); if (*start == (int)ft_strlen((char *)s1)) return (0); else return (end - *start + 1); } char *ft_strtrim(char const *s1, char const *set) { int start; int new_len; char *new_str; int i; if (s1 == NULL || set == NULL) return (NULL); new_len = calc_new_str_len(s1, set, &start); new_str = (char *)ft_calloc(new_len + 1, sizeof(char)); if (new_str == NULL) return (NULL); i = 0; while (i < new_len && new_len != 0) { new_str[i] = s1[start + i]; i++; } return (new_str); }
C++
UTF-8
1,258
3.328125
3
[]
no_license
/** * @file:NumberFileGenerator.h * @author: Tim Elvart * KUID: 2760606 * Email: telvart@ku.edu * @date:10.26.15 * @brief:A class that will create .txt files to be used in the creation of arrays */ #ifndef NUMBERFILEGENERATOR_H #define NUMBERFILEGENERATOR_H #include <string> #include <fstream> #include <chrono> #include <random> class NumberFileGenerator { public: //For all files created with the following, the first line is the amount of numbers in the file /* @pre fileName is a valid path @post a file is created and filled with the amount of numbers in ascending order @return none */ static void ascending(std::string fileName, int amount); /* @pre fileName is a valid path @post a file is created and filled with the numbers in descending order @return none */ static void descending(std::string fileName, int amount); /* @pre fileName is a valid path @post a file is created and filled with random numbers within the range of min, max @return none */ static void random(std::string fileName, int amount, int min, int max); /* @pre fileName is a valid path @post a file is created and filled with a single value value, amount times @return none */ static void singleValue(std::string fileName, int amount, int value); }; #endif
PHP
UTF-8
1,313
2.984375
3
[]
no_license
<?php class UserListBuilder { protected $db; protected $usrObj; public function __construct($db, $usrObj) { $this->db = $db; $this->usrObj = $usrObj; } public function buildList() { $count = $this->getUserCount(); $array = $this->usrObj->getActiveUser(); $html = ''; for ($i = 0; $i < $count; $i++) { $user = $array[$i]; $name = $user['username']; $html .= '<br>'; $html .= "$name"; $html .= '<br>'; } return $html; } /*public function getChatContent($msgObj) { $lang = new LanguageParser('de'); $this->getMessageCount($msgObj); /* print all messages $htmlContent = ''; for ($i = $this->lastTen; $i < $this->msgCount; $i++) { $array = $this->msgObj->getMessage($i + 1); $time = $array['timestamp']; $name = $array['username']; $contentRaw = urldecode($array['content']); $content = $lang->translateSentence($contentRaw); $htmlContent .= '<br>'; $htmlContent .= "[$time] $name : $content"; $htmlContent .= '<br>'; } return $htmlContent; }*/ public function getUserCount() { /* number of users */ $sql = "select count(username) as 'count' from user where status = 'active'"; $result = $this->db->query($sql); $usrs = $result->fetch(); $usrCount = intval($usrs['count']); return $usrCount; } }
Markdown
UTF-8
3,558
3.046875
3
[]
no_license
# testing MANUAL TESTING 1. Software testing is a process of evaluating a system by manual or automatic means and verify that it satisfies specified requirements or identify differences between expected and actual results. Need of software testing. • To check the reliability of software. • To check the software meets its requirements. • To check that users are capable of using the software. 2. Defect means if tester found any mismatch between expected and actual value, it is also a undesirable state. 3. Quality is nothing but meeting the customer requirements for the first and every time. 4. QA • Developing the right product • It is process oriented • Defect prevention based • Review(verification) QC • Developed the right product • It is product oriented • Defect detection based • Testing(validation) 5. Requirement collection, Requirement analysis, Design, Coding, Testing, Implementation and maintainance 6. Srs means software requirements specification is a description of a software systems to be developed, laying out functional and non_functional requirements, and may include a set of use cases that describe interactions the users will have with the software. 7. FRS It describe the detailed functionality of the system in order to cover clint document to understand functionality of application. LLD It describes logic of the each module in order to develop programs 8. Test strategy, Test plan and review test plan, Test scenario and review test scenario, Test cases preparation and review test cases, Test cases executing defect tracking, test closure. 9. TEST STRATEGY It is a high level document which defines the approach of software testing.it is basically derived from BRS. TEST PLAN It is derived from SRS 10. TEST SCENARIO It is just a flow of the application What to test TEST CASES It is a set of procedures. How to test 11. REJECTED If the developer feels that the bug is not genuine, he rejects the bug DEFERRED The bug is expected to be fixed in next releases.priority 13. OPEN The developer has started analyzing and working on the defect fix. REOPEN If the bug still exists even after the bug is fixed by the developer, the tester changes the status to reopen. 14. ERROR: Programmatically mistake or syntax missing leads to error. DEFECT: mismatch between expected results and actual results BUG : once developer accepts testers identified defect. FAILURE: defect reaches the customers then is called failure 15. PRIORITY Important of the defect Inform to developer which defect to be fixed SEVERITY: Impact of the defect, how severity bug is affecting the application 16. Verification: developing the right product Validation: developed the product right 17. Entry: BRS complete, code build Exit: unit test has been passed, internal documentation has been updated to reflect the current state of the product. 18. unit testing, intergation testing, system testing, user acceptance testing 19. EP means equivalence partitioning, it is used to combine same type of test cases related to single functionality, feature, module 20. test driver is a software component or test tool that replaces a component that takes care of the control and or the calling of a component system. Test stub is a software component that usually minimally simulates the actions of called components that have not yet been integrated during top down testing 21. statement coverage means execute all statements at least once.
Java
UTF-8
1,317
2.484375
2
[]
no_license
/*- * Copyright © 2009 Diamond Light Source Ltd., Science and Technology * Facilities Council * * This file is part of GDA. * * GDA is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License version 3 as published by the Free * Software Foundation. * * GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>. */ package gda.data.metadata; /** * Holds information about a single visit ID which can be displayed to the user to help them choose which visit to * collect data under if several are valid for that user at that time. */ public class VisitEntry { private final String visitID; private final String title; public VisitEntry(String visitID, String title) { this.visitID = visitID; this.title = title; } public String getVisitID() { return visitID; } public String getTitle() { return title; } @Override public String toString() { return "VisitEntry [visitID=" + visitID + ", title=" + title + "]"; } }
PHP
UTF-8
414
2.625
3
[ "BSD-4-Clause-UC", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "TCL", "ISC", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "blessing", "MIT" ]
permissive
--TEST-- Bug #41815 (Concurrent read/write fails when EOF is reached) --FILE-- <?php $filename = dirname(__FILE__)."/concur_rw.txt"; @unlink($filename); $writer = fopen($filename, "wt"); $reader = fopen($filename, "r"); fread($reader, 1); fwrite($writer, "foo"); if (strlen(fread($reader, 10)) > 0) { echo "OK\n"; } fclose($writer); fclose($reader); @unlink($filename); echo "Done\n"; ?> --EXPECT-- OK Done
Java
UTF-8
1,548
2.640625
3
[]
no_license
package com.example.demodddaccount.boundaries.account.application; import com.example.demodddaccount.boundaries.account.domain.*; public class AccountUseCase implements AccountService { final AccountRepository repository; public AccountUseCase(AccountRepository repository) { this.repository = repository; } @Override public AccountVO createNewAccount(AccountRequest request) { Account account = Account.of(request.getPerson(), request.getAmount()); return account.createNewAccount(repository); } @Override public AccountVO createNewMovementOfCredit(String accountNumber, MovementRequest request) { AccountVO accountVO = repository.retrieveAccountByNumber(accountNumber); Account account = Account.of(accountVO); account.createNewMovementOfCreditAndUpdateAmountOfAccount(repository, request.getMovementValue()); return repository.retrieveAccountByNumber(accountNumber); } @Override public AccountVO createNewMovementOfDebit(String accountNumber, MovementRequest request) { AccountVO accountVO = repository.retrieveAccountByNumber(accountNumber); Account account = Account.of(accountVO); account.createNewMovementOfDebitAndUpdateAmountOfAccount(repository, request.getMovementValue()); return repository.retrieveAccountByNumber(accountNumber); } @Override public AccountVO retrieveAccountByNumber(String accountNumber) { return repository.retrieveAccountByNumber(accountNumber); } }
Java
UTF-8
661
2.21875
2
[]
no_license
package com.qby.servlet; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * 监听项目的启动 停止 * @author qby * @date 2020/6/16 11:01 */ public class UserListener implements ServletContextListener { // 监听 ServletContext 销毁 @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("UserListener contextInitialized"); } // 监听 ServletContext 启动初始化 @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("UserListener contextDestroyed"); } }
SQL
UTF-8
346
3.296875
3
[]
no_license
drop database if exists network_chess; create database network_chess; use network_chess; CREATE USER `chess_user`@`localhost` IDENTIFIED BY 'chess_user'; GRANT ALL PRIVILEGES ON network_chess.* TO `chess_user`@`localhost` WITH GRANT OPTION; create table user_stat ( user_id varchar(100), wins int, losses int, primary key(user_id) );
Java
UTF-8
769
3.71875
4
[]
no_license
package pattern.part4.chapter14.pattern; /** * Date: 2010-8-15 * Time: 12:27:49 */ public class InstitutionalInvestor implements StockBuyer { private String name; private float maxPrice; private float minPrice; public InstitutionalInvestor(String name, float maxPrice, float minPrice, Stock stock) { this.name = name; this.maxPrice = maxPrice; this.minPrice = minPrice; stock.addBuyers(this); } @Override public void update(float price) { if (price > maxPrice) { System.out.printf("%s is selling 100000 stocks...\n", name); } if (price < minPrice) { System.out.printf("%s is buying 20000 shares...\n", name); } } }
Markdown
UTF-8
1,016
2.828125
3
[ "MIT" ]
permissive
## MOSAD_HW0 #### 介绍 个人作业0-用于测试 #### 开发环境 xxxxxx #### DeadLine: x月x日 **xx** 点 #### 场景描述 xxxxxx #### 实现要求 - xxxxxx #### 提交要求及命名格式 - /src 存放项目文件 - /report 存放项目报告 ### 个人项目提交方式 1. 布置的个人项目先fork到个人仓库下; 2. clone自己仓库的个人项目到本地目录; 3. 在个人项目中,在src、report目录下,新建个人目录,目录名为“学号+姓名”,例如“**12345678WangXiaoMing**”; 4. 在“src\12345678WangXiaoMing”目录下,保存项目,按要求完成作业 5. 实验报告以md的格式,写在“report\12345678WangXiaoMing”目录下; 6. 完成任务需求后,Pull Request回主项目的master分支,PR标题为“学号+姓名”, 如“**12345678王小明**”; 7. 一定要在deadline前PR。因为批改后,PR将合并到主项目,所有同学都能看到合并的结果,所以此时是不允许再PR提交作业的。
Markdown
UTF-8
4,495
2.765625
3
[]
no_license
--- author: name: elaptics body: "Hi All,\r\n\r\nI'm new here, and new to typography in general. Though I've been interested in design for several years, I'm much more of a developer than designer but after watching a documentary about Gutenberg I've been bitten by the typography bug.\r\n\r\nAs I'm still very much in the early stages of learning about type I'd be interested in any recommendations for books or other resources I should investigate. I have just finished reading Robin Williams Non-designers design and type books which inspired me to create a design cheatsheet (using the techniques from the book) that I could have to hand to remind me of the main principles and ideas.\r\n\r\nI have attached it to this post and I would really appreciate any feedback or criticism you may have on the overall design and the typefaces I chose along with any tips you have for improvement." comments: - author: name: '1985' picture: 112115 body: "Hello, nice to meet you.\r\n\r\nI'm no expert, but here is my offering!\r\n\r\nType is all about rules, but also about breaking them, on several levels. It seems that you have observed the rules in reading but I think that you need to concentrate very hard on how to design this information in order that it doesn't contradict itself! It's quite a complex task to illustrate so many ideas without the design becoming cluttered.\r\n\r\nOne rule that a lot of typographers/designers observe is to avoid using too many typefaces/colours, try and combine that rule with your design and you may find it helps clarity.\r\n\r\nYou could expand the cheat sheet into several small posters or pages of a booklet to focus on the main points, white space for example. Maybe then you could get away with more typefaces. One per poster perhaps, or one typeface on all posters and one that changes to illustrate some of your points!\r\n\r\nThe best way to learn though (at least for me) is not to focus too much on the rules, which become apparent as you design and discover what works and what doesn't.\r\n\r\nHope I don't sound preachy :-) Feel free to throw it all back at me!\r\n\r\nAndy" created: '2008-07-08 15:07:58' - author: name: '1985' picture: 112115 body: "Hello, nice to meet you.\r\n\r\nI'm no expert, but here is my offering!\r\n\r\nType is all about rules, but also about breaking them, on several levels. It seems that you have observed the rules in reading but I think that you need to concentrate very hard on how to design this information in order that it doesn't contradict itself! It's quite a complex task to illustrate so many ideas without the design becoming cluttered.\r\n\r\nOne rule that a lot of typographers/designers observe is to avoid using too many typefaces/colours, Try to combine that rule with your design and you may find it helps give it some clarity.\r\n\r\nYou could expand the cheat sheet into several small posters or pages of a booklet to focus on the main points. Maybe then you could get away with more typefaces. One per poster perhaps, or one typeface that is constant and one that changes to illustrate some of your points!\r\n\r\nThe best way to learn though (at least for me) is not to focus too much on the rules, which become apparent as you design and discover what works and what doesn't.\r\n\r\nHope I don't sound preachy :-) Feel free to throw it all back at me!\r\n\r\nAndy" created: '2008-07-08 15:09:38' - author: name: elaptics body: "Hi Andy,\r\n\r\nThanks for taking the time to look and replying. I kind of know that I'm using a few too many typefaces but I was really struggling to put all the points I wanted to cover together on one page in a more interesting way than having it all in a typical bullet list style. I also know that I've broken some of the rules. It was intentional but I'm not sure it comes across appropriately.\r\n\r\nI like the top half of the page and feel that works quite well, but then I think it goes downhill somewhat after that and I'm at a bit of a loss as to how to approach making it better...\r\n\r\nAndy (I'm also an Andy :))" created: '2008-07-08 21:59:01' date: '2008-07-07 22:05:01' files: - filename: design principles cheatsheet.pdf uri: public://old-images/design principles cheatsheet.pdf node_type: forum title: 'Wanted: feedback on design and type choices' ---
JavaScript
UTF-8
327
2.625
3
[]
no_license
function validate(){ var username = document.getElementById("username").value; var password = document.getElementById("password").value; if ( username == "Najoua" && password == "web123456") { alert ("Connexion Réussie"); // Redirecting to other page. return false; } else alert("Impossible de se connecter"); return false; }
Shell
UTF-8
2,167
3.515625
4
[ "MIT" ]
permissive
#/bin/bash ( SERVER=amd012.utah.cloudlab.us USER=$USER LOG=/tmp/_tas_exp_log.txt OUTDIR=/tmp/out/ if [ ! -d $OUTDIR ]; then mkdir $OUTDIR fi function run_local { (sudo ./run.py --client --cores 8 --duration 30) } function run_remote { ssh $USER@$SERVER << EOF sudo pkill --signal SIGINT run.py sleep 1 cd /proj/uic-dcs-PG0/fshahi5/post-loom/exp/motivation/packet_drop_overhead sudo ./run.py $SERVER_CORES $SERVER_CPULIMIT EOF } function terminate_remote_seastar { ssh $USER@$SERVER << EOF sudo pkill --signal SIGINT run.py EOF } function usage { echo "Usage $0 server_cores server_cpulimit" } # --------------------------- # Start from here # --------------------------- if [ $# -lt 2 ]; then usage exit -1 fi SERVER_CORES="--cores $1" SERVER_CPULIMIT="--cpulimit $2" OUTPUT=$OUTDIR/$1_$2.txt echo "Running Server" run_remote &> $LOG & sleep 12 echo "Running Client" tmp="`run_local`" echo "Stopping Server" terminate_remote_seastar sleep 2 # Gather results REMOTE_SW_RES="`cat $LOG | grep -A 5 "Driver"`" LOCAL_SW_RES="`echo "$tmp" | grep -A 5 "Driver"`" LAST_STATS="`echo "$tmp" | grep stats | tail -n 1`" CLIENT_RES="`echo "$tmp" | grep "flow="`" echo "~~~~~~~~~~~~~~" >> $OUTPUT echo "Remote Bess" >> $OUTPUT echo "$REMOTE_SW_RES" >> $OUTPUT echo "Local Bess" >> $OUTPUT echo "$LOCAL_SW_RES" >> $OUTPUT echo "" >> $OUTPUT echo "$LAST_STATS" >> $OUTPUT echo "$CLIENT_RES" >> $OUTPUT # ( # tp=`echo "$MUTILATE_RES" | grep "Total QPS" | awk '{print $4}'` # tp=`echo "$tp / 1000" | bc` # tmp=`echo "$MUTILATE_RES" | grep read` # l50=`echo "$tmp" | awk '{print $7}'` # l99=`echo "$tmp" | awk '{print $10}'` # l999=`echo "$tmp" | awk '{print $11}'` # l9999=`echo "$tmp" | awk '{print $12}'` # ds=`echo "$SW_RES" | grep -A 5 "tmp_vhost0" | grep -A 1 "Out/TX" | grep "dropped" | awk '{print $2}'` # total_pkt=`echo "$SW_RES" | grep -A 5 "tmp_vhost0" | grep -A 1 "Out/TX" | grep "packets" | awk '{print $3}'` # echo "CPU Share Throughput (Kqps) RCT @50 (us) RCT @99 (us) RCT @99.9 (us) RCT @99.99 (us) Drop Server Side Total Packets" # printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" "=$1*$2" $tp $l50 $l99 $l999 $l9999 $ds $total_pkt # ) )
PHP
UTF-8
467
2.578125
3
[]
no_license
<?php require_once 'IAwsHelper.php'; class Ec2Helper implements IAwsHelper { static public function list_names( $client ) { $results = $client->describeInstances(); $names = array(); foreach ( $results['Reservations'] AS $reservations ) { foreach ( $reservations['Instances'] AS $instance ) { $names[] = $instance['InstanceId']; } } return $names; } }
Rust
UTF-8
5,373
2.859375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::hash::BuildHasher; use std::io; use std::rc::Rc; use crate::builtins_util::*; use crate::environment::*; use crate::shell::*; use crate::types::*; fn builtin_str_trim(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 1 { return Err(io::Error::new( io::ErrorKind::Other, "str-trim takes one form", )); } let arg = eval(environment, &args[0])?.make_string(environment)?; Ok(Expression::Atom(Atom::String(arg.trim().to_string()))) } fn builtin_str_ltrim(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 1 { return Err(io::Error::new( io::ErrorKind::Other, "str-ltrim takes one form", )); } let arg = eval(environment, &args[0])?.make_string(environment)?; Ok(Expression::Atom(Atom::String(arg.trim_start().to_string()))) } fn builtin_str_rtrim(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 1 { return Err(io::Error::new( io::ErrorKind::Other, "str-rtrim takes one form", )); } let arg = eval(environment, &args[0])?.make_string(environment)?; Ok(Expression::Atom(Atom::String(arg.trim_end().to_string()))) } fn builtin_str_replace( environment: &mut Environment, args: &[Expression], ) -> io::Result<Expression> { if args.len() != 3 { return Err(io::Error::new( io::ErrorKind::Other, "str-replace takes three forms", )); } let args = to_args_str(environment, args)?; let new_str = args[0].replace(&args[1], &args[2]); Ok(Expression::Atom(Atom::String(new_str))) } fn builtin_str_split(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 2 { return Err(io::Error::new( io::ErrorKind::Other, "str-split takes two forms", )); } let args = to_args_str(environment, args)?; let mut split_list: Vec<Expression> = Vec::new(); for s in args[1].split(&args[0]) { split_list.push(Expression::Atom(Atom::String(s.to_string()))); } Ok(Expression::List(split_list)) } fn builtin_str_cat_list( environment: &mut Environment, args: &[Expression], ) -> io::Result<Expression> { if args.len() != 2 { return Err(io::Error::new( io::ErrorKind::Other, "str-cat-list takes two forms", )); } let args = to_args(environment, args)?; let join_str = args[0].make_string(environment)?; let mut new_str = String::new(); if let Expression::List(list) = &args[1] { let mut first = true; for s in list { if !first { new_str.push_str(&join_str); } new_str.push_str(&s.make_string(environment)?); first = false; } } else { return Err(io::Error::new( io::ErrorKind::Other, "str-cat-list second form must be a list", )); } Ok(Expression::Atom(Atom::String(new_str))) } fn builtin_str_sub(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 3 { return Err(io::Error::new( io::ErrorKind::Other, "str-sub takes three forms (int, int String)", )); } let start = if let Expression::Atom(Atom::Int(i)) = args[0] { i as usize } else { return Err(io::Error::new( io::ErrorKind::Other, "str-sub first form must be an int", )); }; let len = if let Expression::Atom(Atom::Int(i)) = args[1] { i as usize } else { return Err(io::Error::new( io::ErrorKind::Other, "str-sub second form must be an int", )); }; let arg3 = eval(environment, &args[2])?; if let Expression::Atom(Atom::String(s)) = &arg3 { if (start + len) <= s.len() { Ok(Expression::Atom(Atom::String( s.as_str()[start..(start + len)].to_string(), ))) } else { Err(io::Error::new( io::ErrorKind::Other, "str-sub index out of range", )) } } else { Err(io::Error::new( io::ErrorKind::Other, "str-sub third form must be an String", )) } } pub fn add_str_builtins<S: BuildHasher>(data: &mut HashMap<String, Rc<Expression>, S>) { data.insert( "str-trim".to_string(), Rc::new(Expression::Func(builtin_str_trim)), ); data.insert( "str-ltrim".to_string(), Rc::new(Expression::Func(builtin_str_ltrim)), ); data.insert( "str-rtrim".to_string(), Rc::new(Expression::Func(builtin_str_rtrim)), ); data.insert( "str-replace".to_string(), Rc::new(Expression::Func(builtin_str_replace)), ); data.insert( "str-split".to_string(), Rc::new(Expression::Func(builtin_str_split)), ); data.insert( "str-cat-list".to_string(), Rc::new(Expression::Func(builtin_str_cat_list)), ); data.insert( "str-sub".to_string(), Rc::new(Expression::Func(builtin_str_sub)), ); }
Markdown
UTF-8
2,799
2.5625
3
[ "Apache-2.0", "EPL-1.0", "BSD-3-Clause", "CPL-1.0", "LicenseRef-scancode-generic-export-compliance", "MPL-1.1", "Apache-1.1" ]
permissive
# Layout of the filebased repository ## Typical layout Typically, all TOSCA components have the path `componenttype/ns/id`. ## Directory `imports` This directory stores files belonging to a CSAR. That means, when a definitions points to an external reference, the file has to be stored at the external location and not inside the repository ### Directory layout `imports/<encoded importtype>/<encoded namespace>/<id>/` In case no namespace is specified, then `__NONE__` is used as namespace. Handling of that is currently not supported. `id` is a randomly generated id reflecting a single imported file. Inside the directory, a `.tosca` is stored containing the import element only. In future, this can be used to contain the extensibility attributes, which are currently unsupported. `location` points to i) the local file or ii) to some external definition (absolute URL!) Currently, ii is not implemented and the storage is used as mirror only to be able to a) offer choice of known XML Schema definitions b) generate a UI for known XML Schemas (current idea: use http://sourceforge.net/projects/xsd2gui/) Typically, all TOSCA components have the path `componenttype/ns/id`. We add `imports` before to group the imports. The chosen ordering allows to present all available imports for a given import type by just querying the contents of `<encoded importtype>`. ### Handling of the extensibility parts Handling of the extensible part of `tImport` is not supported. A first idea is to store the Import XML Element as file in the respective directory. ### Special treatment of XSD definitions #### Knowing the definitions for a QName Currently, all contained XSDs are queried for their defined local names and this set is aggregated. The following is an implementation idea: Each namespace may contain multiple definitions. Therefore, each folder `<enocded namespace>` contains a file `import.properties`, which provides a mapping of local names to id. For instance, if `theElement`is defined in `myxmldefs.xsd` (being the human-readable id of the folder), `index.properties` contains `theElement = myxmldefs.xsd`. The local name is sufficient as the namespace is given by the parent directory. ## License Copyright (c) 2013-2014 University of Stuttgart. All rights reserved. This program and the accompanying materials are made available under the terms of the [Eclipse Public License v1.0] and the [Apache License v2.0] which both accompany this distribution, and are available at http://www.eclipse.org/legal/epl-v10.html and http://www.apache.org/licenses/LICENSE-2.0 Contributors: * Oliver Kopp - initial API and implementation [Apache License v2.0]: http://www.apache.org/licenses/LICENSE-2.0.html [Eclipse Public License v1.0]: http://www.eclipse.org/legal/epl-v10.html
PHP
UTF-8
1,189
2.546875
3
[]
no_license
<?php namespace app\models; use Yii; /** * This is the model class for table "areeSosta". * * @property integer $id * @property string $nomeArea * @property string $descrizione * @property string $comune * @property string $latitudine * @property string $longitudine */ class AreeSosta extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'areeSosta'; } /** * @inheritdoc */ public function rules() { return [ [['nomeArea', 'descrizione', 'comune', 'latitudine', 'longitudine'], 'required'], [['descrizione'], 'string'], [['latitudine', 'longitudine'], 'number'], [['nomeArea'], 'string', 'max' => 255], [['comune'], 'string', 'max' => 200] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'nomeArea' => 'Nome Area', 'descrizione' => 'Descrizione breve', 'comune' => 'Comune', 'latitudine' => 'Latitudine', 'longitudine' => 'Longitudine', ]; } }
Java
UTF-8
893
2.953125
3
[]
no_license
public class Persona { private String nombre; private String apellido; private Domicilio casa; public Persona() { super(); casa = new Domicilio(); System.out.println("YA HAY UNA REFERENCIA A DOMICILIO"); } public Persona(String nombre, String apellido) { super(); this.nombre = nombre; this.apellido = apellido; casa = new Domicilio(); System.out.println("YA HAY UNA REFERENCIA A DOMICILIO"); } public Persona(String nombre, String apellido,Domicilio dom) { super(); this.nombre = nombre; this.apellido = apellido; this.casa=dom; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public Domicilio getCasa() { return casa; } public void setCasa(Domicilio casa) { this.casa = casa; } }
Java
UTF-8
233
1.609375
2
[]
no_license
package com.suhid.practice.repository; import com.suhid.practice.model.CourseModel; import org.springframework.data.jpa.repository.JpaRepository; public interface CourseRepository extends JpaRepository<CourseModel,Long> { }
Java
UTF-8
1,678
2.234375
2
[ "MIT" ]
permissive
package org.kidneyomics.fluidigm; import org.junit.Assert; import java.io.File; import java.net.URL; import org.apache.log4j.Logger; import org.junit.Test; public class TestMakeFile { Logger logger = Logger.getLogger(TestMakeFile.class); @Test public void testWriteCommands1() { URL templateDirectory = ClassLoader.getSystemResource("st/makefile.stg"); String fullpath = templateDirectory.getPath(); File f = new File(fullpath); logger.info(fullpath); MakeFile m = new MakeFile(fullpath); MakeEntry e1 = new MakeEntry(); e1.setTarget("HELLO1.OK").setComment("ENTRY1");; e1.addDependency(new MakeEntry().setTarget("DEP1")).addDependency(new MakeEntry().setTarget("DEP2")); e1.addCommand("COMMAND1"); e1.addCommand("COMMAND2"); m.addMakeEntry(e1); MakeEntry e2 = new MakeEntry(); e2.setTarget("HELLO2.OK"); e2.addDependency(new MakeEntry().setTarget("DEP3")).addDependency(new MakeEntry().setTarget("DEP4")).addDependency(new MakeEntry().setTarget("DEP5")); e2.addCommand("COMMAND3"); e2.addCommand("COMMAND4"); e2.addCommand("COMMAND5"); m.addMakeEntry(e2); logger.info("\n" + m.writeTemplateToString()); String expected = "all:\tHELLO1.OK\tHELLO2.OK\t\n\ttouch $@.OK\n\n#ENTRY1\nHELLO1.OK:\tDEP1\tDEP2\t\n\tCOMMAND1\n\tCOMMAND2\n\nHELLO2.OK:\tDEP3\tDEP4\tDEP5\t\n\tCOMMAND3\n\tCOMMAND4\n\tCOMMAND5\n\n"; logger.info("\n" + expected); //logger.info("\n" + m.writeCommands().substring(0, 70)); //logger.info("\n" + expected.substring(0, 70)); //Assert.assertEquals(expected.substring(0, 80), m.writeCommands().substring(0, 80)); Assert.assertEquals(expected, m.writeTemplateToString()); } }
C++
UTF-8
2,442
2.640625
3
[]
no_license
// // Created by serdok on 05/03/19. // #include "StartScreen.h" StartScreen::StartScreen( Castle* const castle, Translation* const trans ) : Texture( "Image Accueil.png", true ), _castle( castle ), _translation( trans) { _inputs = InputsManager::GetInstance(); _shopText = new Texture( "1 : " + _translation->GetTranslation(2), "Roboto-Regular.ttf", 20, { 255, 255, 255 } ); _shopText->SetPosition( Vector2f( 100, 250 )); _startText = new Texture( "2 : " + _translation->GetTranslation(3), "Roboto-Regular.ttf", 20, { 255, 255, 255 } ); _startText->SetPosition( Vector2f( 680, 220 )); _tomb = new Texture( "Objets/Tombe.png" ); _tomb->SetScale( Vector2f( 0.1f, 0.1f )); _reset = new Texture( "0 : " + _translation->GetTranslation( 34 ), "Roboto-Regular.ttf", 10, { 255, 255, 255 } ); _reset->SetPosition( Vector2f( Graphics::SCREEN_WIDTH - _reset->GetWidth()/2.0f, Graphics::SCREEN_HEIGHT - _reset->GetHeight()/2.0f ) ); } StartScreen::~StartScreen() { _inputs = nullptr; delete _tomb; delete _shopText; delete _startText; delete _reset; } void StartScreen::Update() { } void StartScreen::Render() { // Render the background image Texture::Render(); // Render text textures _startText->Render(); _shopText->Render(); // Render the Tombs for (unsigned int i = 0 ; i < _castle->GetPlayer()->GetDeaths()%10 ; i++) { _tomb->SetPosition( Vector2f( 450 + 70*( i%5 )-(50*int( i/5 )), 500 + 50*int( i/5 ))); _tomb->Render(); } _reset->Render(); } void StartScreen::ProcessEvents( SDL_Event* event ) { // No events processing (for the moment) } void StartScreen::SetTranslation( Translation* const translation ) { _translation = translation; delete _shopText; delete _startText; delete _reset; _shopText = new Texture( "1 : " + _translation->GetTranslation(2), "Roboto-Regular.ttf", 20, { 255, 255, 255 } ); _shopText->SetPosition( Vector2f( 100, 250 )); _startText = new Texture( "2 : " + _translation->GetTranslation(3), "Roboto-Regular.ttf", 20, { 255, 255, 255 } ); _startText->SetPosition( Vector2f( 680, 220 )); _reset = new Texture( "3 : " + _translation->GetTranslation( 34 ), "Roboto-Regular.ttf", 10, { 255, 255, 255 } ); _reset->SetPosition( Vector2f( Graphics::SCREEN_WIDTH - _reset->GetWidth()/2.0f, Graphics::SCREEN_HEIGHT - _reset->GetHeight()/2.0f ) ); }
C++
UTF-8
17,842
2.96875
3
[]
no_license
#pragma once #include <vector> #include <fstream> //https://stackoverflow.com/a/217605 #include <algorithm> #include <functional> #include <Eigen/Geometry> #include <Eigen/StdVector> // //loguru #include <loguru.hpp> typedef std::vector<float> row_type_f; typedef std::vector<row_type_f> matrix_type_f; typedef std::vector<double> row_type_d; typedef std::vector<row_type_f> matrix_type_d; typedef std::vector<int> row_type_i; typedef std::vector<row_type_i> matrix_type_i; typedef std::vector<bool> row_type_b; typedef std::vector<row_type_b> matrix_type_b; namespace radu{ namespace utils{ // //append new_mat into a preallocated mat and check if we have enough size to append there // template<class T> // inline void eigen_append_in_preallocated(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& mat, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& new_mat){ // } inline void removeRow(Eigen::MatrixXd& matrix, unsigned int rowToRemove) { unsigned int numRows = matrix.rows()-1; unsigned int numCols = matrix.cols(); if( rowToRemove < numRows ) matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols); matrix.conservativeResize(numRows,numCols); } inline void removeColumn(Eigen::MatrixXd& matrix, unsigned int colToRemove) { unsigned int numRows = matrix.rows(); unsigned int numCols = matrix.cols()-1; if( colToRemove < numCols ) matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove); matrix.conservativeResize(numRows,numCols); } inline void eigen2file(Eigen::MatrixXd& src, std::string pathAndName) { std::ofstream fichier(pathAndName); if(fichier.is_open()) // si l'ouverture a réussi { // instructions fichier << src << "\n"; fichier.close(); // on referme le fichier } else // sinon { LOG(FATAL) << "Error opening " << pathAndName; } } //when using dyanmic vector we don't need an eigen alocator template<class T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> vec2eigen( const std::vector< Eigen::Matrix<T, Eigen::Dynamic, 1>>& std_vec ) { if(std_vec.size()==0){ //return empty eigen mat Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> eigen_vec; return eigen_vec; } const int dim=std_vec[0].size(); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> eigen_vec(std_vec.size(),dim); for (size_t i = 0; i < std_vec.size(); ++i) { eigen_vec.row(i)=std_vec[i]; } return eigen_vec; } //for the case of using fixed sized vector like Vector3f, it also works with dynamic types if you write the template explicitly template<class T, int rows > // Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> vec2eigen( const std::vector< Eigen::Matrix<T, rows, 1>, Eigen::aligned_allocator< Eigen::Matrix<T, rows, 1>> >& std_vec ) Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> vec2eigen( const std::vector< Eigen::Matrix<T, rows, 1>> & std_vec ) { if(std_vec.size()==0){ //return empty eigen mat Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> eigen_vec; return eigen_vec; } const int dim=std_vec[0].size(); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> eigen_vec(std_vec.size(),dim); for (size_t i = 0; i < std_vec.size(); ++i) { eigen_vec.row(i)=std_vec[i]; } return eigen_vec; } //for the case of using a vector of double of floats or whatever numeric type. It will only take numeric types and not anything else https://stackoverflow.com/a/14294277 template< class T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> vec2eigen( const std::vector< T >& std_vec ) { if(std_vec.size()==0){ //return empty eigen mat Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> eigen_vec; return eigen_vec; } Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> eigen_vec(std_vec.size(),1); for (size_t i = 0; i < std_vec.size(); ++i) { eigen_vec(i)=std_vec[i]; } return eigen_vec; } //when using dyanmic vector we don't need an eigen alocator template<class T> std::vector< T > eigen2vec( const Eigen::Matrix<T, Eigen::Dynamic, 1>& eigen ) { std::vector< T > std_vec(eigen.rows()); for (int i = 0; i < eigen.rows(); ++i) { std_vec[i] = eigen(i); } return std_vec; } //filters the rows of an eigen matrix and returns only those for which the mask is equal to the keep template <class T> inline T filter_impl(std::vector<int>&indirection, std::vector<int>&inverse_indirection, const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks ){ if(eigen_mat.rows()!=(int)mask.size() || eigen_mat.size()==0 ){ LOG_IF_S(WARNING, do_checks) << "filter: Eigen matrix and mask don't have the same size: " << eigen_mat.rows() << " and " << mask.size() ; return eigen_mat; } int nr_elem_to_keep=std::count(mask.begin(), mask.end(), keep); T new_eigen_mat( nr_elem_to_keep, eigen_mat.cols() ); indirection.resize(eigen_mat.rows(),-1); inverse_indirection.resize(nr_elem_to_keep, -1); int insert_idx=0; for (int i = 0; i < eigen_mat.rows(); ++i) { if(mask[i]==keep){ new_eigen_mat.row(insert_idx)=eigen_mat.row(i); indirection[i]=insert_idx; inverse_indirection[insert_idx]=i; insert_idx++; } } return new_eigen_mat; } template <class T> inline T filter( const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks=true){ std::vector<int> indirection; std::vector<int> inverse_indirection; return filter_impl(indirection, inverse_indirection, eigen_mat, mask, keep, do_checks); } template <class T> inline T filter_return_indirection(std::vector<int>&indirection, const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks=true){ std::vector<int> inverse_indirection; return filter_impl(indirection, inverse_indirection, eigen_mat, mask, keep, do_checks); } template <class T> inline T filter_return_inverse_indirection(std::vector<int>&inverse_indirection, const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks=true ){ std::vector<int> indirection; return filter_impl(indirection, inverse_indirection, eigen_mat, mask, keep, do_checks); } template <class T> inline T filter_return_both_indirection(std::vector<int>&indirection, std::vector<int>&inverse_indirection, const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks=true ){ return filter_impl(indirection, inverse_indirection, eigen_mat, mask, keep, do_checks); } //gets rid of the faces that are redirected to a -1 or edges that are also indirected into a -1 inline Eigen::MatrixXi filter_apply_indirection(const std::vector<int>&indirection, const Eigen::MatrixXi& eigen_mat ){ if(!eigen_mat.size()){ //it's empty return eigen_mat; } if(eigen_mat.maxCoeff() > (int)indirection.size()){ LOG(FATAL) << "filter apply_indirection: eigen_mat is indexing indirection at a higher position than allowed" << eigen_mat.maxCoeff() << " " << indirection.size(); } std::vector<Eigen::VectorXi> new_eigen_mat_vec; for (int i = 0; i < eigen_mat.rows(); ++i) { Eigen::VectorXi row= eigen_mat.row(i); bool should_keep=true; for (int j = 0; j < row.size(); ++j) { if (indirection[row(j)]==-1){ //it points to a an already removed point so we will not keep it should_keep=false; }else{ //it point to a valid vertex so we change the idx so that it point to that one row(j) = indirection[row(j)]; } } if(should_keep){ new_eigen_mat_vec.push_back(row); } } return vec2eigen(new_eigen_mat_vec); } //gets rid of the faces that are redirected to a -1 or edges that are also indirected into a -1 AND also returns a mask (size eigen_mat x 1) with value of TRUE for those which were keps inline Eigen::MatrixXi filter_apply_indirection_return_mask(std::vector<bool>& mask_kept, const std::vector<int>&indirection, const Eigen::MatrixXi& eigen_mat ){ if(!eigen_mat.size()){ //it's empty return eigen_mat; } if(eigen_mat.maxCoeff() > (int)indirection.size()){ LOG(FATAL) << "filter apply_indirection: eigen_mat is indexing indirection at a higher position than allowed" << eigen_mat.maxCoeff() << " " << indirection.size(); } std::vector<Eigen::VectorXi> new_eigen_mat_vec; mask_kept.resize(eigen_mat.rows(),false); for (int i = 0; i < eigen_mat.rows(); ++i) { // LOG_IF_S(INFO,debug) << "getting row " << i; Eigen::VectorXi row= eigen_mat.row(i); // LOG_IF_S(INFO,debug) << "row is" << row; bool should_keep=true; for (int j = 0; j < row.size(); ++j) { // LOG_IF_S(INFO,debug) << "value at column " << j << " is " << row(j); // LOG_IF_S(INFO,debug) << "indirection has size " << indirection.size(); // LOG_IF_S(INFO,debug) << "value of indirection at is " << indirection[row(j)]; if (indirection[row(j)]==-1){ //it points to a an already removed point so we will not keep it should_keep=false; }else{ //it point to a valid vertex so we change the idx so that it point to that one row(j) = indirection[row(j)]; } } if(should_keep){ // LOG_IF_S(INFO,debug) << "pushing new row " << row; new_eigen_mat_vec.push_back(row); // LOG_IF_S(INFO,debug) << "setting face " << i << " to kept"; mask_kept[i]=true; } } // LOG_IF_S(INFO,debug) << "finished, doing a vec2eigen "; return vec2eigen(new_eigen_mat_vec); } //filters that does not actually remove the points, but just sets them to zero template <class T> inline T filter_set_zero_impl(std::vector<int>&indirection, std::vector<int>&inverse_indirection, const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks ){ if(eigen_mat.rows()!=(int)mask.size() || eigen_mat.size()==0 ){ LOG_IF_S(WARNING, do_checks) << "filter: Eigen matrix and mask don't have the same size: " << eigen_mat.rows() << " and " << mask.size() ; return eigen_mat; } T new_eigen_mat( eigen_mat.rows(), eigen_mat.cols() ); new_eigen_mat.setZero(); indirection.resize(eigen_mat.rows(),-1); inverse_indirection.resize(eigen_mat.rows(), -1); for (int i = 0; i < eigen_mat.rows(); ++i) { if(mask[i]==keep){ new_eigen_mat.row(i)=eigen_mat.row(i); indirection[i]=i; inverse_indirection[i]=i; } } return new_eigen_mat; } //sets the corresponding rows to zero instead of removing them template <class T> inline T filter_set_zero( const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks=true){ std::vector<int> indirection; std::vector<int> inverse_indirection; return filter_set_zero_impl(indirection, inverse_indirection, eigen_mat, mask, keep, do_checks); } template <class T> inline T filter_set_zero_return_indirection(std::vector<int>&indirection, const T& eigen_mat, const std::vector<bool> mask, const bool keep, const bool do_checks=true){ std::vector<int> inverse_indirection; return filter_set_zero_impl(indirection, inverse_indirection, eigen_mat, mask, keep, do_checks); } template <class T> inline T concat(const T& mat_1, const T& mat_2){ if(mat_1.cols()!=mat_2.cols() && mat_1.cols()!=0 && mat_2.cols()!=0){ LOG(FATAL) << "concat: Eigen matrices don't have the same nr of columns: " << mat_1.cols() << " and " << mat_2.cols() ; } T mat_new(mat_1.rows() + mat_2.rows(), mat_1.cols()); mat_new << mat_1, mat_2; return mat_new; } //transform from a vector of xyz and qx,qy,qz,qw into a full Affine3d template <class T> inline Eigen::Transform<T,3,Eigen::Affine> tf_vec2matrix(const Eigen::Matrix< T, Eigen::Dynamic, 1 >& tf_vec){ CHECK(tf_vec.rows()==7) << "Expecting 7 elements corresponding to x,y,z, qx,qy,qz,qw"; Eigen::Transform<T,3,Eigen::Affine> tf; tf.setIdentity(); tf.translation().x() = tf_vec[0]; tf.translation().y() = tf_vec[1]; tf.translation().z() = tf_vec[2]; Eigen::Quaternion<T> q; q.x() = tf_vec[3]; q.y() = tf_vec[4]; q.z() = tf_vec[5]; q.w() = tf_vec[6]; q.normalize(); tf.linear()=q.toRotationMatrix(); return tf; } //transform from a vector of strings xyz and qx,qy,qz,qw into a full Affine3d template <class T> inline Eigen::Transform<T,3,Eigen::Affine> tf_vecstring2matrix(const std::vector<std::string>& tokens ){ CHECK(tokens.size()==7) << "Expecting 7 elements corresponding to x,y,z, qx,qy,qz,qw"; Eigen::Transform<T,3,Eigen::Affine> tf; tf.setIdentity(); tf.translation().x() = std::stod(tokens[0]); tf.translation().y() = std::stod(tokens[1]); tf.translation().z() = std::stod(tokens[2]); Eigen::Quaternion<T> q; q.x() = std::stod(tokens[3]); q.y() = std::stod(tokens[4]); q.z() = std::stod(tokens[5]); q.w() = std::stod(tokens[6]); q.normalize(); tf.linear()=q.toRotationMatrix(); return tf; } //transform from a Affine3d into a vec containing x,y,z, qx,qy,qz,qw template <class T> inline Eigen::Matrix< T, Eigen::Dynamic, 1 > tf_matrix2vec(const Eigen::Transform<T,3,Eigen::Affine> & tf){ Eigen::Quaternion<T> q (tf.linear()); auto t = tf.translation(); Eigen::Matrix< T, Eigen::Dynamic, 1 > vec; vec.resize(7); vec[0]=t.x(); vec[1]=t.y(); vec[2]=t.z(); vec[3]=q.x(); vec[4]=q.y(); vec[5]=q.z(); vec[6]=q.w(); return vec; } //transform from a Affine3d into a vector of strings containing x,y,z, qx,qy,qz,qw template <class T> inline std::vector<std::string> tf_matrix2vecstring(const Eigen::Transform<T,3,Eigen::Affine> & tf){ Eigen::Matrix< T, Eigen::Dynamic, 1 > vec; vec=tf_matrix2vec(tf); std::vector<std::string> tokens; for (int i=0; i<vec.rows(); i++){ std::string num_string=std::to_string(vec(i)); tokens.push_back(num_string); } return tokens; } //transform from a vector of fx,fy,cx,cy into a full Matrix3d template <class T> inline Eigen::Matrix<T,3,3> K_vec2matrix(const Eigen::Matrix< T, Eigen::Dynamic, 1 >& K_vec){ CHECK(K_vec.rows()==4) << "Expecting 4 elements corresponding to fx,fy,cx,cy"; Eigen::Matrix<T,3,3> K; K.setIdentity(); K(0,0)= K_vec[0]; K(1,1)= K_vec[1]; K(0,2)= K_vec[2]; K(1,2)= K_vec[3]; return K; } //transform from a Matrix3d template <class T> inline Eigen::Matrix< T, Eigen::Dynamic, 1 > K_matrix2vec(const Eigen::Matrix<T,3,3>& K){ Eigen::Matrix< T, Eigen::Dynamic, 1 > K_vec; K_vec.resize(4); K_vec(0)=K(0,0); K_vec(1)=K(1,1); K_vec(2)=K(0,2); K_vec(3)=K(1,2); return K_vec; } //from a series of tokens, fills a martrix, assuming row major; template <typename T, int R, int C> inline void tokens2matrix(const std::vector<std::string> tokens, Eigen::Matrix<T,R,C>& matrix, bool rowmajor=true){ size_t matrix_size=matrix.rows()*matrix.cols(); CHECK(matrix_size==tokens.size()) << "The nr of tokens does not correspond to the matrix size. Tokens has size " << tokens.size() << " matrix has rows and cols " << matrix.rows() <<" x " << matrix.cols(); //get the tokens into an vector; std::vector<T> array; for(size_t i=0;i<tokens.size();i++){ array.push_back( std::stod(tokens[i]) ); } if(rowmajor){ matrix = Eigen::Map<const Eigen::Matrix<T,R,C,Eigen::RowMajor> >(array.data() ); }else{ matrix = Eigen::Map<const Eigen::Matrix<T,R,C> >(array.data() ); } } // //in the case of a dynamic matrix we need to provide a size estimate to the MAP https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html //https://eigen.tuxfamily.org/dox/classEigen_1_1Map.html template <typename T> inline void tokens2matrix(const std::vector<std::string> tokens, Eigen::Matrix<T,Eigen::Dynamic,1>& matrix ){ size_t matrix_size=matrix.rows()*matrix.cols(); CHECK(matrix_size==tokens.size()) << "The nr of tokens does not correspond to the matrix size. Tokens has size " << tokens.size() << " matrix has rows and cols " << matrix.rows() <<" x " << matrix.cols(); //get the tokens into an vector; std::vector<T> array; for(size_t i=0;i<tokens.size();i++){ array.push_back( std::stod(tokens[i]) ); } matrix = Eigen::Map<const Eigen::Matrix<T,Eigen::Dynamic,1> >(array.data(), tokens.size()); } //has function for eigen matrices and vectors https://wjngkoh.wordpress.com/2015/03/04/c-hash-function-for-eigen-matrix-and-vector/ template<typename T> struct MatrixHash : std::unary_function<T, size_t> { std::size_t operator()(T const& matrix) const { // Note that it is oblivious to the storage order of Eigen matrix (column- or // row-major). It will give you the same hash value for two different matrices if they // are the transpose of each other in different storage order. size_t seed = 0; for (int i = 0; i < matrix.size(); ++i) { auto elem = *(matrix.data() + i); seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } }; } //namespace utils } //namespace radu
Python
UTF-8
1,385
2.703125
3
[]
no_license
import sys import os def readMap(): wrong_map = {} with open('wrong_map.txt', 'r') as f: for line in f: # print line wrong_index, index = map(int, line.split(' ')) # print wrong_index, index wrong_map[wrong_index] = index return wrong_map def getlist(data_dir): wrong_map = readMap() train_dir = os.path.join(data_dir, 'train') train_file = open('train.txt', 'w') num_dirs = os.listdir(train_dir) for num in num_dirs: val = wrong_map[int(num)] if val == -1: continue num_dir = os.path.join(train_dir, num) bmps = os.listdir(num_dir) for bmp in bmps: train_file.write(os.path.join(num_dir, bmp) + ' ' + str(val) + '\n') train_file.close() val_dir = os.path.join(data_dir, 'val') val_file = open('val.txt', 'w') num_dirs = os.listdir(val_dir) for num in num_dirs: val = wrong_map[int(num)] if val == -1: continue num_dir = os.path.join(val_dir, num) bmps = os.listdir(num_dir) for bmp in bmps: val_file.write(os.path.join(num_dir, bmp) + ' ' + str(val) + '\n') val_file.close() if __name__ == '__main__': if len(sys.argv) != 2: print 'Usage: python bmp data dir' exit(1) data_dir = sys.argv[1] getlist(data_dir)
PHP
UTF-8
2,224
2.515625
3
[]
no_license
<?php namespace App\Jobs; use App\Processors\PasswordProcessor; use Carbon\Carbon; use Cookie; use Exception; use Illuminate\{ Bus\Queueable, Contracts\Queue\ShouldQueue, Foundation\Bus\Dispatchable, Http\UploadedFile, Queue\InteractsWithQueue, Queue\SerializesModels}; class PasswordQueue implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; private const YEAR_IN_MINUTES = 525600; private const FAILED_JOBS_MEMCACHE_KEY = '___failed_jobs___'; public $tries = 2; public $timeout = Carbon::SECONDS_PER_MINUTE * 5; /** * @var string */ private $key; /** * @var object */ private $passwords; /** * @var string */ private $passwordProcessorClass; public function __construct(UploadedFile $file, ?string $passwordManagerType) { $file = $file->openFile(); $passwords = json_decode($file->fread($file->getSize())); $key = uniqid($file->getFilename(), true); Cookie::queue('file_hash', $key, self::YEAR_IN_MINUTES); $this->key = $key; $this->passwords = $passwords; $this->passwordProcessorClass = PasswordProcessor::getClass($passwordManagerType); } public static function getFailedJobs(): array { return cache(static::FAILED_JOBS_MEMCACHE_KEY) ?: []; } public static function hasJobFailed(string $key): bool { return in_array($key, static::getFailedJobs()); } public function handle() { $passwordProcessor = app($this->passwordProcessorClass); cache( [ PasswordProcessor::MEMCACHE_PREFIX . $this->key => $passwordProcessor->processPasswords($this->passwords) ], Carbon::now()->addYear() ); $this->passwords = null; } public function failed(Exception $exception) { $failedJobs = static::getFailedJobs(); $failedJobs[] = $this->key; cache( [static::FAILED_JOBS_MEMCACHE_KEY => $failedJobs], Carbon::now()->addDay() ); throw $exception; } }
C++
UTF-8
1,713
2.65625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <fstream> #include "common_inline.h" #include "chordDB.h" using namespace std; int interval = 1; int error(const string& msg); int main(){ string filenameChordDB = "chords2.csv"; string filenameTestChords = "to_test.txt"; chordDB db(filenameChordDB); ifstream fTestChords(filenameTestChords.c_str()); if(!fTestChords.good()) error("cannot open test chords file\n"); // first, create a vector for test chords string strTestChords; getline(fTestChords, strTestChords); vector<string> testChordNames; vtokenize(strTestChords, ",", testChordNames); if(testChordNames.size()==0) error("could not parse test chords string\n"); if(testChordNames.size() <= 1){ printf("Too few chords!\n"); exit(1); } for(int i=0; i<(int)testChordNames.size(); i++){ //printf("%s\n----\n",testChordNames[i].c_str()); db.check(testChordNames[i]); //printf("\n\n"); } int nTestChords = testChordNames.size(); int lastTestChord = -1; srand((unsigned)time(0)); while(1){ screenclear(); int nextTestChord; do{ nextTestChord = rand() % nTestChords; }while(nextTestChord == lastTestChord); db.display(testChordNames[nextTestChord]); printf("\n\n"); lastTestChord = nextTestChord; printf("5 "); fflush(stdout); dosleep(1000); printf("4 "); fflush(stdout); dosleep(1000); printf("3 "); fflush(stdout); dosleep(1000); printf("2 "); fflush(stdout); dosleep(1000); printf("1 "); fflush(stdout); dosleep(1000); } fTestChords.close(); } int error(const string& msg){ printf("%s\n",msg.c_str()); exit(1); }
Java
UTF-8
1,281
2.015625
2
[]
no_license
package com.scheduleyoga.dao; import java.util.HashMap; import java.util.Map; public class StudioOld { static public final int STUDIO_ID_BABTISTE = 1; static public final int STUDIO_ID_KAIAYOGA = 2; static public final int STUDIO_ID_JOSCHI_NYC = 3; static public final int STUDIO_ID_JIVAMUKTIYOGA = 4; static public final int STUDIO_ID_LAUGHING_LOTUS = 5; static public final int STUDIO_ID_OM_YOGA = 6; protected Map<String, String> xPathMap = new HashMap<String, String>(); protected Map<String, String> scheduleURL = new HashMap<String, String>(); protected int id; protected String name; protected String url; protected String xPath; protected StudioOld() { // TODO Auto-generated constructor stub } public static StudioOld createNew(int idParam){ StudioOld newObj = new StudioOld(); newObj.setId(idParam); return newObj; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getxPath() { return xPath; } public void setxPath(String xPath) { this.xPath = xPath; } }
TypeScript
UTF-8
25,465
2.578125
3
[ "MIT" ]
permissive
/** * TestReport Module */ import * as primitives from "@tangdrew/primitives"; import * as t from "io-ts"; import { Extension, ExtensionOutputType } from "./Extension"; import { Identifier, IdentifierOutputType } from "./Identifier"; import { Meta, MetaOutputType } from "./Meta"; import { Narrative, NarrativeOutputType } from "./Narrative"; import { Reference, ReferenceOutputType } from "./Reference"; import { Resource, ResourceOutputType } from "./Resource"; /** * A test operation or assert that was performed */ export interface TestReportTestAction { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** The operation performed */ operation?: TestReportSetupActionOperation; /** The assertion performed */ assert?: TestReportSetupActionAssert; } export interface TestReportTestActionOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** The operation performed */ operation?: TestReportSetupActionOperationOutputType; /** The assertion performed */ assert?: TestReportSetupActionAssertOutputType; } export const TestReportTestAction: t.RecursiveType< t.Type<TestReportTestAction, TestReportTestActionOutputType>, TestReportTestAction, TestReportTestActionOutputType > = t.recursion<TestReportTestAction, TestReportTestActionOutputType>( "TestReportTestAction", () => t.intersection( [ t.type({}), t.partial({ /** The assertion performed */ assert: TestReportSetupActionAssert, /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension), /** The operation performed */ operation: TestReportSetupActionOperation }) ], "TestReportTestAction" ) ); /** * A test executed from the test script */ export interface TestReportTest { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** Tracking/logging name of this test */ name?: t.TypeOf<primitives.R4.StringType>; /** Tracking/reporting short description of the test */ description?: t.TypeOf<primitives.R4.StringType>; /** A test operation or assert that was performed */ action: TestReportTestAction[]; } export interface TestReportTestOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** Tracking/logging name of this test */ name?: t.OutputOf<primitives.R4.StringType>; /** Tracking/reporting short description of the test */ description?: t.OutputOf<primitives.R4.StringType>; /** A test operation or assert that was performed */ action: TestReportTestActionOutputType[]; } export const TestReportTest: t.RecursiveType< t.Type<TestReportTest, TestReportTestOutputType>, TestReportTest, TestReportTestOutputType > = t.recursion<TestReportTest, TestReportTestOutputType>( "TestReportTest", () => t.intersection( [ t.type({ /** A test operation or assert that was performed */ action: t.array(TestReportTestAction) }), t.partial({ /** Tracking/reporting short description of the test */ description: primitives.R4.string, /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension), /** Tracking/logging name of this test */ name: primitives.R4.string }) ], "TestReportTest" ) ); /** * One or more teardown operations performed */ export interface TestReportTeardownAction { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** The teardown operation performed */ operation: TestReportSetupActionOperation; } export interface TestReportTeardownActionOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** The teardown operation performed */ operation: TestReportSetupActionOperationOutputType; } export const TestReportTeardownAction: t.RecursiveType< t.Type<TestReportTeardownAction, TestReportTeardownActionOutputType>, TestReportTeardownAction, TestReportTeardownActionOutputType > = t.recursion<TestReportTeardownAction, TestReportTeardownActionOutputType>( "TestReportTeardownAction", () => t.intersection( [ t.type({ /** The teardown operation performed */ operation: TestReportSetupActionOperation }), t.partial({ /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension) }) ], "TestReportTeardownAction" ) ); /** * The results of running the series of required clean up steps */ export interface TestReportTeardown { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** One or more teardown operations performed */ action: TestReportTeardownAction[]; } export interface TestReportTeardownOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** One or more teardown operations performed */ action: TestReportTeardownActionOutputType[]; } export const TestReportTeardown: t.RecursiveType< t.Type<TestReportTeardown, TestReportTeardownOutputType>, TestReportTeardown, TestReportTeardownOutputType > = t.recursion<TestReportTeardown, TestReportTeardownOutputType>( "TestReportTeardown", () => t.intersection( [ t.type({ /** One or more teardown operations performed */ action: t.array(TestReportTeardownAction) }), t.partial({ /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension) }) ], "TestReportTeardown" ) ); /** * The operation to perform */ export interface TestReportSetupActionOperation { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** pass | skip | fail | warning | error */ result: t.TypeOf<primitives.R4.CodeType>; /** A message associated with the result */ message?: t.TypeOf<primitives.R4.MarkdownType>; /** A link to further details on the result */ detail?: t.TypeOf<primitives.R4.URIType>; } export interface TestReportSetupActionOperationOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** pass | skip | fail | warning | error */ result: t.OutputOf<primitives.R4.CodeType>; /** A message associated with the result */ message?: t.OutputOf<primitives.R4.MarkdownType>; /** A link to further details on the result */ detail?: t.OutputOf<primitives.R4.URIType>; } export const TestReportSetupActionOperation: t.RecursiveType< t.Type< TestReportSetupActionOperation, TestReportSetupActionOperationOutputType >, TestReportSetupActionOperation, TestReportSetupActionOperationOutputType > = t.recursion< TestReportSetupActionOperation, TestReportSetupActionOperationOutputType >("TestReportSetupActionOperation", () => t.intersection( [ t.type({ /** pass | skip | fail | warning | error */ result: primitives.R4.code }), t.partial({ /** A link to further details on the result */ detail: primitives.R4.uri, /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** A message associated with the result */ message: primitives.R4.markdown, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension) }) ], "TestReportSetupActionOperation" ) ); /** * The assertion to perform */ export interface TestReportSetupActionAssert { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** pass | skip | fail | warning | error */ result: t.TypeOf<primitives.R4.CodeType>; /** A message associated with the result */ message?: t.TypeOf<primitives.R4.MarkdownType>; /** A link to further details on the result */ detail?: t.TypeOf<primitives.R4.StringType>; } export interface TestReportSetupActionAssertOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** pass | skip | fail | warning | error */ result: t.OutputOf<primitives.R4.CodeType>; /** A message associated with the result */ message?: t.OutputOf<primitives.R4.MarkdownType>; /** A link to further details on the result */ detail?: t.OutputOf<primitives.R4.StringType>; } export const TestReportSetupActionAssert: t.RecursiveType< t.Type<TestReportSetupActionAssert, TestReportSetupActionAssertOutputType>, TestReportSetupActionAssert, TestReportSetupActionAssertOutputType > = t.recursion< TestReportSetupActionAssert, TestReportSetupActionAssertOutputType >("TestReportSetupActionAssert", () => t.intersection( [ t.type({ /** pass | skip | fail | warning | error */ result: primitives.R4.code }), t.partial({ /** A link to further details on the result */ detail: primitives.R4.string, /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** A message associated with the result */ message: primitives.R4.markdown, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension) }) ], "TestReportSetupActionAssert" ) ); /** * A setup operation or assert that was executed */ export interface TestReportSetupAction { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** The operation to perform */ operation?: TestReportSetupActionOperation; /** The assertion to perform */ assert?: TestReportSetupActionAssert; } export interface TestReportSetupActionOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** The operation to perform */ operation?: TestReportSetupActionOperationOutputType; /** The assertion to perform */ assert?: TestReportSetupActionAssertOutputType; } export const TestReportSetupAction: t.RecursiveType< t.Type<TestReportSetupAction, TestReportSetupActionOutputType>, TestReportSetupAction, TestReportSetupActionOutputType > = t.recursion<TestReportSetupAction, TestReportSetupActionOutputType>( "TestReportSetupAction", () => t.intersection( [ t.type({}), t.partial({ /** The assertion to perform */ assert: TestReportSetupActionAssert, /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension), /** The operation to perform */ operation: TestReportSetupActionOperation }) ], "TestReportSetupAction" ) ); /** * The results of the series of required setup operations before the tests were executed */ export interface TestReportSetup { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** A setup operation or assert that was executed */ action: TestReportSetupAction[]; } export interface TestReportSetupOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** A setup operation or assert that was executed */ action: TestReportSetupActionOutputType[]; } export const TestReportSetup: t.RecursiveType< t.Type<TestReportSetup, TestReportSetupOutputType>, TestReportSetup, TestReportSetupOutputType > = t.recursion<TestReportSetup, TestReportSetupOutputType>( "TestReportSetup", () => t.intersection( [ t.type({ /** A setup operation or assert that was executed */ action: t.array(TestReportSetupAction) }), t.partial({ /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension) }) ], "TestReportSetup" ) ); /** * A participant in the test execution, either the execution engine, a client, or a server */ export interface TestReportParticipant { /** Unique id for inter-element referencing */ id?: t.TypeOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: Extension[]; /** test-engine | client | server */ type: t.TypeOf<primitives.R4.CodeType>; /** The uri of the participant. An absolute URL is preferred */ uri: t.TypeOf<primitives.R4.URIType>; /** The display name of the participant */ display?: t.TypeOf<primitives.R4.StringType>; } export interface TestReportParticipantOutputType { /** Unique id for inter-element referencing */ id?: t.OutputOf<primitives.R4.StringType>; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored even if unrecognized */ modifierExtension?: ExtensionOutputType[]; /** test-engine | client | server */ type: t.OutputOf<primitives.R4.CodeType>; /** The uri of the participant. An absolute URL is preferred */ uri: t.OutputOf<primitives.R4.URIType>; /** The display name of the participant */ display?: t.OutputOf<primitives.R4.StringType>; } export const TestReportParticipant: t.RecursiveType< t.Type<TestReportParticipant, TestReportParticipantOutputType>, TestReportParticipant, TestReportParticipantOutputType > = t.recursion<TestReportParticipant, TestReportParticipantOutputType>( "TestReportParticipant", () => t.intersection( [ t.type({ /** test-engine | client | server */ type: primitives.R4.code, /** The uri of the participant. An absolute URL is preferred */ uri: primitives.R4.uri }), t.partial({ /** The display name of the participant */ display: primitives.R4.string, /** Additional content defined by implementations */ extension: t.array(Extension), /** Unique id for inter-element referencing */ id: primitives.R4.string, /** Extensions that cannot be ignored even if unrecognized */ modifierExtension: t.array(Extension) }) ], "TestReportParticipant" ) ); /** * Describes the results of a TestScript execution */ export interface TestReport { /** Logical id of this artifact */ id?: t.TypeOf<primitives.R4.IDType>; /** Metadata about the resource */ meta?: Meta; /** A set of rules under which this content was created */ implicitRules?: t.TypeOf<primitives.R4.URIType>; /** Language of the resource content */ language?: t.TypeOf<primitives.R4.CodeType>; /** Text summary of the resource, for human interpretation */ text?: Narrative; /** Contained, inline Resources */ contained?: Resource[]; /** Additional content defined by implementations */ extension?: Extension[]; /** Extensions that cannot be ignored */ modifierExtension?: Extension[]; /** External identifier */ identifier?: Identifier; /** Informal name of the executed TestScript */ name?: t.TypeOf<primitives.R4.StringType>; /** completed | in-progress | waiting | stopped | entered-in-error */ status: t.TypeOf<primitives.R4.CodeType>; /** Reference to the version-specific TestScript that was executed to produce this TestReport */ testScript: Reference; /** pass | fail | pending */ result: t.TypeOf<primitives.R4.CodeType>; /** The final score (percentage of tests passed) resulting from the execution of the TestScript */ score?: t.TypeOf<primitives.R4.DecimalType>; /** Name of the tester producing this report (Organization or individual) */ tester?: t.TypeOf<primitives.R4.StringType>; /** When the TestScript was executed and this TestReport was generated */ issued?: t.TypeOf<primitives.R4.DateTimeType>; /** A participant in the test execution, either the execution engine, a client, or a server */ participant?: TestReportParticipant[]; /** The results of the series of required setup operations before the tests were executed */ setup?: TestReportSetup; /** A test executed from the test script */ test?: TestReportTest[]; /** The results of running the series of required clean up steps */ teardown?: TestReportTeardown; } export interface TestReportOutputType { /** Logical id of this artifact */ id?: t.OutputOf<primitives.R4.IDType>; /** Metadata about the resource */ meta?: MetaOutputType; /** A set of rules under which this content was created */ implicitRules?: t.OutputOf<primitives.R4.URIType>; /** Language of the resource content */ language?: t.OutputOf<primitives.R4.CodeType>; /** Text summary of the resource, for human interpretation */ text?: NarrativeOutputType; /** Contained, inline Resources */ contained?: ResourceOutputType[]; /** Additional content defined by implementations */ extension?: ExtensionOutputType[]; /** Extensions that cannot be ignored */ modifierExtension?: ExtensionOutputType[]; /** External identifier */ identifier?: IdentifierOutputType; /** Informal name of the executed TestScript */ name?: t.OutputOf<primitives.R4.StringType>; /** completed | in-progress | waiting | stopped | entered-in-error */ status: t.OutputOf<primitives.R4.CodeType>; /** Reference to the version-specific TestScript that was executed to produce this TestReport */ testScript: ReferenceOutputType; /** pass | fail | pending */ result: t.OutputOf<primitives.R4.CodeType>; /** The final score (percentage of tests passed) resulting from the execution of the TestScript */ score?: t.OutputOf<primitives.R4.DecimalType>; /** Name of the tester producing this report (Organization or individual) */ tester?: t.OutputOf<primitives.R4.StringType>; /** When the TestScript was executed and this TestReport was generated */ issued?: t.OutputOf<primitives.R4.DateTimeType>; /** A participant in the test execution, either the execution engine, a client, or a server */ participant?: TestReportParticipantOutputType[]; /** The results of the series of required setup operations before the tests were executed */ setup?: TestReportSetupOutputType; /** A test executed from the test script */ test?: TestReportTestOutputType[]; /** The results of running the series of required clean up steps */ teardown?: TestReportTeardownOutputType; } export const TestReport: t.RecursiveType< t.Type<TestReport, TestReportOutputType>, TestReport, TestReportOutputType > = t.recursion<TestReport, TestReportOutputType>("TestReport", () => t.intersection( [ t.type({ /** pass | fail | pending */ result: primitives.R4.code, /** completed | in-progress | waiting | stopped | entered-in-error */ status: primitives.R4.code, /** Reference to the version-specific TestScript that was executed to produce this TestReport */ testScript: Reference }), t.partial({ /** Contained, inline Resources */ contained: t.array(Resource), /** Additional content defined by implementations */ extension: t.array(Extension), /** Logical id of this artifact */ id: primitives.R4.id, /** External identifier */ identifier: Identifier, /** A set of rules under which this content was created */ implicitRules: primitives.R4.uri, /** When the TestScript was executed and this TestReport was generated */ issued: primitives.R4.dateTime, /** Language of the resource content */ language: primitives.R4.code, /** Metadata about the resource */ meta: Meta, /** Extensions that cannot be ignored */ modifierExtension: t.array(Extension), /** Informal name of the executed TestScript */ name: primitives.R4.string, /** A participant in the test execution, either the execution engine, a client, or a server */ participant: t.array(TestReportParticipant), /** The final score (percentage of tests passed) resulting from the execution of the TestScript */ score: primitives.R4.decimal, /** The results of the series of required setup operations before the tests were executed */ setup: TestReportSetup, /** The results of running the series of required clean up steps */ teardown: TestReportTeardown, /** A test executed from the test script */ test: t.array(TestReportTest), /** Name of the tester producing this report (Organization or individual) */ tester: primitives.R4.string, /** Text summary of the resource, for human interpretation */ text: Narrative }) ], "TestReport" ) );
Java
UTF-8
3,632
2.296875
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/* * Copyright (c) 2019 Cerus * File created at 13.04.19 18:02 * Last modification: 13.04.19 18:02 * All rights reserved. */ package de.cerus.toastbot.tasks; import com.electronwill.nightconfig.core.file.CommentedFileConfig; import de.cerus.toastbot.event.VoteEventCaller; import de.cerus.toastbot.util.VoteUtil; import net.dv8tion.jda.api.JDA; import org.discordbots.api.client.DiscordBotListAPI; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Deprecated public class VoteCheckerRunnable implements Runnable { private JDA jda; private DiscordBotListAPI discordBotListAPI; private List<Long> voters; private CommentedFileConfig voterConfig; private VoteEventCaller voteEventCaller; private boolean interrupted = false; public VoteCheckerRunnable(JDA jda, DiscordBotListAPI discordBotListAPI, VoteEventCaller voteEventCaller) { this.jda = jda; this.discordBotListAPI = discordBotListAPI; this.voteEventCaller = voteEventCaller; File file = new File("./Voters.toml"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } this.voterConfig = CommentedFileConfig.of(file); this.voterConfig.load(); if (this.voterConfig.isEmpty()) { this.voterConfig.set("voters", new ArrayList<Long>()); this.voterConfig.save(); } this.voters = this.voterConfig.get("voters"); voters.forEach(l -> VoteUtil.getHasVoted().put(l, true)); } @Override public void run() { /* AtomicBoolean isWeekend = new AtomicBoolean(false); discordBotListAPI.getVotingMultiplier().whenComplete((votingMultiplier, throwable) -> { if(throwable != null) isWeekend.set(votingMultiplier.isWeekend()); }); new ArrayList<>(jda.getGuilds().stream().filter(guild -> !guild.getId().equals(*//*DBL Guild: *//*"264445053596991498")).collect(Collectors.toList())).forEach(guild -> new ArrayList<>(guild.getMembers()).stream().filter(member -> !member.getUser().isBot()).forEach(member -> { if (isInterrupted()) return; try { Thread.sleep(5000); } catch (InterruptedException ignored) { } discordBotListAPI.hasVoted(member.getId()).whenComplete((hasVoted, throwable) -> { if (throwable != null) { } else if (hasVoted && !voters.contains(member.getIdLong())) { VoteUtil.getHasVoted().put(member.getIdLong(), true); voters.add(member.getIdLong()); voteEventCaller.call(member, guild, isWeekend.get()); } else if (!hasVoted && voters.contains(member.getIdLong())) { VoteUtil.getHasVoted().put(member.getIdLong(), false); voters.remove(member.getIdLong()); } }); })); if (isInterrupted()) return; try { Thread.sleep((2 * 60) * 1000); saveVoters(); run(); } catch (InterruptedException ignored) { }*/ } public void shutdown() { saveVoters(); } public void saveVoters() { this.voterConfig.set("voters", voters); this.voterConfig.save(); } public boolean isInterrupted() { return interrupted; } public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; } }
PHP
UTF-8
6,907
2.640625
3
[ "MIT" ]
permissive
<?php namespace Chadicus\Marvel\Api\Entities; use Chadicus\Marvel\Api\Client; use Chadicus\Marvel\Api\Assets\CharacterHandler; use GuzzleHttp\Client as GuzzleClient; /** * Unit tests for the Character class. * * @coversDefaultClass \Chadicus\Marvel\Api\Entities\Character * @covers ::<protected> */ final class CharacterTest extends \PHPUnit\Framework\TestCase { /** * Verify properties are set properly. * * @test * * @return void */ public function construct() { $guzzleClient = new GuzzleClient(['handler' => new CharacterHandler()]); $client = new Client('not under test', 'not under test', $guzzleClient); $now = new \DateTime(); $data = [ 'id' => 1, 'name' => 'a name', 'description' => 'a description', 'modified' => $now->format('r'), 'resourceURI' => 'a resource uri', 'urls' => [['type' => 'a type', 'url' => 'a url']], 'thumbnail' => ['path' => 'a path', 'extension' => 'an extension'], 'comics' => [ 'available' => 2, 'returned' => 1, 'collectionURI' => 'a comics collection uri', 'items' => [['resourceURI' => 'a comics resource uri', 'name' => 'a comics name']], ], 'stories' => [ 'available' => 2, 'returned' => 1, 'collectionURI' => 'a stories collection uri', 'items' => [['resourceURI' => 'a stories resource uri', 'name' => 'a stories name']], ], 'events' => [ 'available' => 2, 'returned' => 1, 'collectionURI' => 'a events collection uri', 'items' => [['resourceURI' => 'a events resource uri', 'name' => 'a events name']], ], 'series' => [ 'available' => 2, 'returned' => 1, 'collectionURI' => 'a series collection uri', 'items' => [['resourceURI' => 'a series resource uri', 'name' => 'a series name']], ], ]; $character = new Character($data); $this->assertSame(1, $character->getId()); $this->assertSame('a name', $character->getName()); $this->assertSame('a description', $character->getDescription()); $this->assertSame($now->getTimestamp(), $character->getModified()->getTimestamp()); $this->assertSame('a resource uri', $character->getResourceURI()); $this->assertSame(1, count($character->getUrls())); $this->assertSame('a type', $character->getUrls()[0]->getType()); $this->assertSame('a url', $character->getUrls()[0]->getUrl()); $this->assertSame('a path', $character->getThumbnail()->getPath()); $this->assertSame('an extension', $character->getThumbnail()->getExtension()); $this->assertSame(2, $character->getComics()->getAvailable()); $this->assertSame(1, $character->getComics()->getReturned()); $this->assertSame('a comics collection uri', $character->getComics()->getCollectionURI()); $this->assertSame(1, count($character->getComics()->getItems())); $this->assertSame('a comics resource uri', $character->getComics()->getItems()[0]->getResourceURI()); $this->assertSame('a comics name', $character->getComics()->getItems()[0]->getName()); $this->assertSame(2, $character->getStories()->getAvailable()); $this->assertSame(1, $character->getStories()->getReturned()); $this->assertSame(1, count($character->getStories()->getItems())); $this->assertSame('a stories resource uri', $character->getStories()->getItems()[0]->getResourceURI()); $this->assertSame('a stories name', $character->getStories()->getItems()[0]->getName()); $this->assertSame(2, $character->getEvents()->getAvailable()); $this->assertSame(1, $character->getEvents()->getReturned()); $this->assertSame('a events collection uri', $character->getEvents()->getCollectionURI()); $this->assertSame(1, count($character->getEvents()->getItems())); $this->assertSame('a events resource uri', $character->getEvents()->getItems()[0]->getResourceURI()); $this->assertSame('a events name', $character->getEvents()->getItems()[0]->getName()); $this->assertSame(2, $character->getSeries()->getAvailable()); $this->assertSame(1, $character->getSeries()->getReturned()); $this->assertSame('a series collection uri', $character->getSeries()->getCollectionURI()); $this->assertSame(1, count($character->getSeries()->getItems())); $this->assertSame('a series resource uri', $character->getSeries()->getItems()[0]->getResourceURI()); $this->assertSame('a series name', $character->getSeries()->getItems()[0]->getName()); } /** * Verify basic behavior of findAll(). * * @test * @covers ::findAll * * @return void */ public function findAll() { $guzzleClient = new GuzzleClient(['handler' => new CharacterHandler()]); $client = new Client('not under test', 'not under test', $guzzleClient); $characters = Character::findAll($client); $this->assertSame(5, $characters->count()); foreach ($characters as $key => $character) { $this->assertSame($key, $character->getId()); $this->assertSame("a name for character {$key}", $character->getName()); $this->assertSame("a description for character {$key}", $character->getDescription()); } } /** * Verify query parameters are set properly with findAll(). * * @test * @covers ::findAll * * @return void */ public function findAllParametersSetProperly() { $now = new \DateTime(); $criteria = [ 'name' => 'a name', 'modifiedSince' => $now->format('r'), 'comics' => [1,2,3], 'series' => [2,4,6], 'events' => [1,3,5], 'stories' => [7,8,9], 'orderBy' => 'name', ]; $handler = new CharacterHandler(); $guzzleClient = new GuzzleClient(['handler' => $handler]); $client = new Client('not under test', 'not under test', $guzzleClient); $characters = Character::findAll($client, $criteria); $characters->next(); $expectedParameters = [ 'name' => 'a name', 'modifiedSince' => $now->format('c'), 'comics' => '1,2,3', 'series' => '2,4,6', 'events' => '1,3,5', 'stories' => '7,8,9', 'orderBy' => 'name', ]; foreach ($expectedParameters as $key => $value) { $this->assertSame($value, $handler->parameters[$key]); } } }
C++
UTF-8
776
3.140625
3
[]
no_license
/********************************************************************* ** Program name:Zoo Tycoon ** Author: Derek Yang ** Date:10/14/2017 ** Description:This is the reusable menu class. This creates a vector for the menu and allows the user to input as many menu options as they want. *********************************************************************/ #include "menu.hpp" Menu::Menu() { } //mutator to add a menu item void Menu::appSelection(std::string selectionIn){ options.push_back(selectionIn); } //print menu item void Menu::printSelection(int loc){ std::cout<<options[loc]<<std::endl; } void Menu::printRange(int start, int end) { for (int i = start; i<=end; i++){ std::cout<<options[i]<<std::endl; } } //destructor Menu::~Menu() { }
C
UTF-8
610
3.0625
3
[]
no_license
#include <stdio.h> #include <string.h> #define IMAP_QUOTAROOT_NONEXISTENT (2390157849L) int return_an_error(const char *s) { if (!strcmp(s, "foo")) return IMAP_QUOTAROOT_NONEXISTENT; return 0; } void check_an_error(const char *s) { int r; printf("check_an_error(%s)\n", s); r = return_an_error(s); if (!r) printf("OK\n"); else if (r == IMAP_QUOTAROOT_NONEXISTENT) printf("IMAP_QUOTAROOT_NONEXISTENT\n"); else printf("unknown errors %ld\n", (long)r); } int main(int argc, char **argv) { check_an_error("foo"); check_an_error("bar"); return 0; }
Java
UTF-8
217
1.609375
2
[]
no_license
package Pages; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { LazadaHomePage homepage=new LazadaHomePage(); homepage.navigateToURL(); } }
Java
UTF-8
1,262
2.5
2
[ "BSD-2-Clause" ]
permissive
package org.notalgodemons.tokenservice.api; import com.twilio.Twilio; import com.twilio.base.ResourceSet; import com.twilio.rest.api.v2010.account.Message; import org.notalgodemons.tokenservice.wrappers.Course; import java.util.ArrayList; import java.util.List; public class Example { public static final String ACCOUNT_SID = ""; public static final String AUTH_TOKEN = ""; public static void main(String[] args) { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); ResourceSet<Message> messages = Message.reader() .setTo(new com.twilio.type.PhoneNumber("+")) .limit(20) .read(); List<String> AL=new ArrayList<>(); for(Message record : messages) { System.out.println(record.getSid()+" "+record.getBody()); AL.add(record.getBody()); } System.out.println(AL.get(0)); // String privateKey = AL.get(0).substring(0,AL.get(0).indexOf(' ')); // String courseAddress = AL.get(0).substring(AL.get(0).indexOf(' '),AL.get(0).lastIndexOf(' ')); // String fileHash = AL.get(0).substring(AL.get(0).lastIndexOf(' ')); // // Eduthon ed = new Eduthon(); // System.out.println(ed.submit(privateKey,courseAddress,fileHash)); } }
PHP
UTF-8
806
2.59375
3
[]
no_license
<?php App::uses('AppModel', 'Model'); /** * Category Model * * @property Post $Post */ class Category extends AppModel { /** * Behaviours * * @var array */ public $actsAs = array('Containable'); /** * Validation rules * * @var array */ public $validate = array( 'name' => array( 'notEmpty' => array( 'rule' => array('notEmpty') ), ), ); /** * hasMany associations * * @var array */ public $hasMany = array( 'Post' => array( 'className' => 'Post', 'foreignKey' => 'category_id' ) ); /** * Get Categories with total post * * @param int $limit Default amount that the query should return * @return array */ public function getCategoriesWithTotalPost($limit = 5) { $categories = $this->find('all', array('limit' => $limit)); return $categories; } }
C++
UTF-8
1,393
3.6875
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; double Mean(double x[], int N); double StdDev(double x[], double mean, int N); void instrucciones(int&); void SoliData(double x[], int);//esta función guarda los datos en el arreglo x[] //el arreglo se pasa a la función como de costumbre //aún cuando se escribe en él int main(int argc, char* argv[]) { int N; instrucciones(N); //Solicita el número N de datos a introducir double* x; x = new double [N]; SoliData(x, N); //Solicita los N datos double mean; mean = Mean(x, N); //se usa la variable mean para futuros cálculos cout << "Promedio de los datos introducidos: " << mean << endl; double dev; dev = StdDev(x, mean, N); cout << "Desviación estándar de los datos introducidos: " << dev << endl; delete[] x; return 0; } void instrucciones(int& N) { cout << "Este programa calcula la desviación estándar de un conjunto de números." << endl; cout << "Cuántos datos? "; cin >> N; } void SoliData(double x[], int N) { for(int i = 0; i < N; i++) { cout << "x_" << i + 1 << " = "; cin >> x[i]; } } double Mean(double x[], int N) { double sum = 0; for(int i = 0; i < N; i++) { sum += x[i]; } return sum/N; } double StdDev(double x[], double mean, int N) { double sum = 0; for(int i = 0; i < N; i++) { sum += pow((x[i]-mean),2); } return sqrt(sum/(N-1)); }
JavaScript
UTF-8
3,091
2.796875
3
[]
no_license
const config = require('../config'); const {callFunctionCode} = require('../utils'); function generateRandomJsKeySelector(length = 6) { const charCodes = config.payloadVariablePrefix.split('').map(c => c.charCodeAt(0)).join(); const randomNumber = Math.random().toString().slice(-length); return `String.fromCharCode(${charCodes})+${randomNumber}`; } function generateRandomClass(length = 6) { return `${config.payloadClassPrefix}${Math.random().toString().slice(-length)}`; } const triggerActionOnElementWithClass = (className, action) => { let elements = document.getElementsByClassName(className); for (let i = 0; i < elements.length; i++) { elements.item(i)[action](); } return elements.length; }; function getTriggerCodeForClass(className, action) { return callFunctionCode(triggerActionOnElementWithClass, className, action); } const triggerElementWithCode = code => { let found = false; let logs = []; function log(type, text) { logs.push({ type, text, }); } function find(node, parent) { switch (node.nodeType) { case 1: break; case 2: if (node.nodeValue.includes(code)) { let funcName = node.nodeName === 'href' ? 'click' : node.nodeName; if (typeof parent[funcName] === 'function') { try { found = true; parent[funcName](); } catch (e) { log('info', 'found code but threw an error'); log('debug', 'found code but threw an error.\n' + `attribute name: ${node.nodeName}\n` + `code: ${parent[funcName] && parent[funcName].toString()}\n` + e.toString()); } } else { log('info', 'found code but not a function'); log('debug', 'found code but not a function.\n' + `attribute name: ${node.nodeName}\n` + `value type: ${typeof parent[funcName]}\n` + `value type: ${parent[funcName]}`); } } return; default: return; } if (node.hasChildNodes()) { node.childNodes.forEach(function (child) { return find(child, node) }); } for (let i = 0; i < node.attributes.length; i++) { find(node.attributes[i], node); } } find(document.children[0]); if (!found) { log('info', 'did not found code.'); } return logs; } function getTriggerCodeForCode(jsCode) { return callFunctionCode(triggerElementWithCode, jsCode); } module.exports = { generateRandomJsKeySelector, generateRandomClass, getTriggerCodeForClass, getTriggerCodeForCode, }
Java
UTF-8
2,370
2.75
3
[]
no_license
package ua.kpi.training.model.entity; /** * Created by Anya on 14.05.2017. */ public class Communications { /** * The {@link Communications#phoneNumberHome} field representing the number of member's home phone. */ private String phoneNumberHome; /** * The {@link Communications#phoneNumberMobileFirst} field representing the member's first mobile number. */ private String phoneNumberMobileFirst; /** * The {@link Communications#phoneNumberMobileSecond} field representing the member's second mobile number if it is exist, or none. */ private String phoneNumberMobileSecond; /** * The {@link Communications#emailAddress} field representing the member's email. */ private String emailAddress; /** * The {@link Communications#skypeNickName} field representing the member's skype nickname. */ private String skypeNickName; public Communications() { } public String getPhoneNumberHome() { return phoneNumberHome; } public void setPhoneNumberHome(String phoneNumberHome) { this.phoneNumberHome = phoneNumberHome; } public String getPhoneNumberMobileFirst() { return phoneNumberMobileFirst; } public void setPhoneNumberMobileFirst(String phoneNumberMobileFirst) { this.phoneNumberMobileFirst = phoneNumberMobileFirst; } public String getPhoneNumberMobileSecond() { return phoneNumberMobileSecond; } public void setPhoneNumberMobileSecond(String phoneNumberMobileSecond) { this.phoneNumberMobileSecond = phoneNumberMobileSecond; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getSkypeNickName() { return skypeNickName; } public void setSkypeNickName(String skypeNickName) { this.skypeNickName = skypeNickName; } @Override public String toString() { return "phoneNumberHome= " + phoneNumberHome + ", phoneNumberMobileFirst= " + phoneNumberMobileFirst + ", phoneNumberMobileSecond= " + phoneNumberMobileSecond + ", emailAddress= " + emailAddress + ", skypeNickName= " + skypeNickName+" "; } }
C
UTF-8
1,028
3.890625
4
[]
no_license
/* amountcalculator_extended.c a program that reads in three real inputs: an account balance, an annual interest rate expressed as percentage and the time of investment. then display the peroid, interest made and the new balance during that year. (we are looking may at compounded interest) */ #include <stdio.h> int main() { float accountBalance, annualInterest, afterBalance, investmentTime; printf("enter the account balance: "); scanf("%f", &accountBalance); printf("enter the annual interest rate expressed as percentage: "); scanf("%f", &annualInterest); printf("enter the time of investment: "); scanf("%f", &investmentTime); for (int i = 0; i < investmentTime; i++) { afterBalance = ((accountBalance * 100) + (accountBalance * annualInterest)); afterBalance = afterBalance / 100.0; printf("At time %d, the balance after on %.2f at a rate of %.4f is %.2f\n", i + 1, accountBalance, annualInterest, afterBalance); accountBalance = afterBalance; } return 0; }
Markdown
UTF-8
2,078
2.75
3
[]
no_license
![](https://steemitimages.com/0x0/https://steemitimages.com/0x0/https://steemitimages.com/0x0/https://steemitimages.com/DQmXuu2Skv5DF1W5ePrmQ9caKHKDyN6xC4XjddHqKcknbgy/Idiom%20of%20the%20day-min.png) 오늘의 Idiom은 <center><b> beat around the bush </b></center> <center><b> beat about the bush </b></center> 입니다. If you beat around the bush, or beat about the bush, you don't say something directly, usually because you don't want to upset the person you're talking to. beat around the bush / beat about the bush는 한국말로 직역하면 '돌려 말하기, 요점을 피하다'가 됩니다. 이 표현을 쓴다면, 무언가 직접적으로 이야기하지 않는 것을 말하고, 그 이유는 주로 이야기하고 있는 상대방을 기분 나쁘지 않게 하려는 이유때문입니다. ![](https://steemitimages.com/DQmV3Ax7wg7cbyTLAVsVC7xpAketfMFEFojVPvejqjZk2Dk/image.png) For example: - I had trouble telling Pedro he'd lost his job. I started beating around the bush and talking about one door closing and another door opening. Pedro에게 그가 직업을 잃었다는 사실을 말하는 것이 어려웠습니다. 그래서 요점을 피하여 둘러 말하기 시작했고, 나쁜 일이 있다가 좋은 일도 생기는 것이라고 말해주었습니다. - Stop beating about the bush. Just tell me what's happened! 핵심을 흐리지마. 뭐가 일어났는지 그냥 말만 해! PS. 예시 문장에서 one door closing and another door opening 이라는 표현도 있는데, 이 표현도 나름 신선하고 새로운 표현이라고 볼 수 있겠습니다. 한 문이 닫히면, 한 문이 열린다는 뜻으로, 문이 닫힌다는 것은 행복의 문이 닫힌다는 것에서 유래했습니다. 즉, 나쁜일이 생기더라도 다시금 좋은 일이 생길 것이라는 뜻입니다. "전화위복"이나 "이 또한 지나가리라" 등의 표현으로 받아들이시면 됩니다. ![](https://img1.steemit.com/480x0/https://steemitimages.com/DQmUdNLJKzrFrZNgsc1c5UkZWHkTwPZj8KXApQcs6deGDK5/follow%20image-min.png)
Ruby
UTF-8
537
4.28125
4
[]
no_license
# unpacks ARGV and assigns it to three variables first, second, third = ARGV puts "Your first variable is #{first}" puts "Your second variable is #{second}" puts "Your third variable is #{third}" puts "Do something..." variable = $stdin.gets.chomp puts "Your variable is #{variable}" puts "Try this..." variable2 = gets.chomp # this returns an error since you need to use $stdin to get input from the command line puts "This is it: #{variable2}" # gets.chomp input keyboard while script is running # ARGV is input from command line
Markdown
UTF-8
710
2.828125
3
[]
no_license
# textoverflow - android ### Built With: - Phonegap ### Dependencies: - Cordova ### Synopsis Are you friends constantly on their phones at dinner? Use this app to get them off their phones by mass texting a series of photos of your choosing. ### Motivation I wanted to make my friends get off their phones at dinner and actually interact in person. ### Screenshots ![textoverflow-compiled-1](/screenshots/textoverflow-compiled-1.png) ![textoverflow-compiled-2](/screenshots/textoverflow-compiled-2.png) ### Installation View the web app repo [here](https://github.com/borderpointer/textoverflow) or alternatively download the android app [here](https://build.phonegap.com/apps/1821839/share)
Python
UTF-8
3,100
2.515625
3
[]
no_license
import re from insn_type import InsnTypeInt, InsnType, InsnTypeChar, InsnTypeFloat, InsnTypeDouble REGS = [ # 8-bit general-purpose reg 'AL', 'BL', 'CL', 'DL', 'AH', 'BH', 'CH', 'DH', 'DIL', 'SIL', 'BPL', 'SPL', 'R8L', 'R9L', 'R10L', 'R11L', 'R12L', 'R13L', 'R14L', 'R15L', # 16-bit general-purpose reg 'AX', 'BX', 'CX', 'DX', 'DI', 'SI', 'BP', 'SP', 'R8W', 'R9W', 'R10W', 'R11W', 'R12W', 'R13W', 'R14W', 'R15W', # 32-bit general-purpose reg 'EAX', 'EBX', 'ECX', 'EDX', 'EDI', 'ESI', 'EBP', 'ESP', 'R8D', 'R9D', 'R10D', 'R11D', 'R12D', 'R13D', 'R14D', 'R15D', # 64-bit general-purpose reg 'RAX', 'RBX', 'RCX', 'RDX', 'RDI', 'RSI', 'RBP', 'RSP', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15', # Instruction Pointer Register 'RIP', # MMX and XMM Register 'MMX0', 'MMX1', 'MMX2', 'MMX3', 'MMX4', 'MMX5', 'MMX6', 'MMX7', 'XMM0', 'XMM1', 'XMM2', 'XMM3', 'XMM4', 'XMM5', 'XMM6', 'XMM7', 'MXCSR', ] """ # FPU Register 'ST0', 'ST1', 'ST2','ST3', 'ST4', 'ST5', 'ST6', 'ST7', # segment reg 'CS', 'DS', 'SS', 'ES', 'FS', 'GS', # control reg 'CR0', 'CR2', 'CR3', 'CR4', # debug reg 'DR0', 'DR1', 'DR2', 'DR3', 'DR6', 'DR7', """ BYTE_WIDTHS = ['', 'byte ptr', 'word ptr', 'dword ptr', 'qword ptr'] BYTE_WIDTHS_size = { '': -1, 'byte ptr': 1, 'word ptr': 2, 'dword ptr': 4, 'qword ptr': 8 } def parse_regs(op): register_list = re.findall( r'(%s)' % '|'.join(REGS), op.upper(), flags=re.IGNORECASE ) return register_list def parse_offset(op): """ :return: byte_width, base, offset """ result = re.findall( r'(%s)\s\[(%s).*?\s([+-]?\s[xa-f\d]+)\]' % ( '|'.join(BYTE_WIDTHS), '|'.join(REGS) ), op, re.IGNORECASE ) if result: return result[0][0], result[0][1], \ int(result[0][2].replace(' ', ''), 16) # e.g. "- 0x4" elif '[' in op: r = re.findall( r'(%s)\s\[(%s)\]' % ( '|'.join(BYTE_WIDTHS), '|'.join(REGS) ), op, re.IGNORECASE ) if r: return r[0][0], r[0][1], 0, else: return None, None, None else: return None, None, None def guess_basic_type(byte_width, fp_mode=False): if byte_width == 'byte ptr': return InsnTypeChar() elif byte_width == 'word ptr': return InsnTypeInt(size=2, label='short int') elif byte_width == 'dword ptr' and not fp_mode: return InsnTypeInt(size=4, label='int') elif byte_width == 'dword ptr' and fp_mode: return InsnTypeFloat(size=4, label='float') elif byte_width == 'qword ptr' and not fp_mode: return InsnTypeInt(size=8, label='long int') elif byte_width == 'qword ptr' and fp_mode: return InsnTypeDouble(size=8, label='double') elif byte_width == 'qword ptr' and pt_mode: return InsnTypeDouble(size=8, label='double') else: return InsnType(label='unknow') if __name__ == "__main__": print(parse_offset('dword ptr [rbp + rax*4 - 0x30]'))
Markdown
UTF-8
2,620
3.265625
3
[ "MIT" ]
permissive
# Delete objects {#concept_91924_zh .concept} This topic describes how to delete objects. **Warning:** Delete objects with caution because deleted objects cannot be recovered. For the complete code of deleting objects, see [GitHub](https://github.com/aliyun/aliyun-oss-csharp-sdk/blob/master/samples/Samples/DeleteObjectsSample.cs). ## Delete an object {#section_kbr_nm2_lfb .section} Run the following code to delete a single object: ``` using Aliyun.OSS; var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; var objectName = "<yourObjectName>"; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { /// Delete an object. client.DeleteObject(bucketName, objectName); Console.WriteLine("Delete object succeeded"); } catch (Exception ex) { Console.WriteLine("Delete object failed. {0}", ex.Message); } ``` ## Delete multiple objects { .section} You can delete a maximum of 1,000 objects simultaneously. Objects can be deleted in two modes: detail \(verbose\) and simple \(quiet\) modes. - verbose: returns the list of objects that you have deleted successfully. The default mode is verbose. - quiet: returns the list of objects that you failed to delete. Run the following code to delete multiple objects simultaneously: ``` using Aliyun.OSS; var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var keys = new List<string>(); var listResult = client.ListObjects(bucketName); foreach (var summary in listResult.ObjectSummaries) { keys.Add(summary.Key); } // If the quietMode is true, the quiet mode is used. If the quietMode is false, the verbose mode is used. The default mode is verbose. var quietMode = false; // The third parameter of the DeleteObjectsRequest specifies the return mode. var request = new DeleteObjectsRequest(bucketName, keys, quietMode); // Delete multiple objects. var result = client.DeleteObjects(request); if ((! quietMode) && (result.Keys ! = null)) { foreach (var obj in result.Keys) { Console.WriteLine("Delete successfully : {0} ", obj.Key); } } Console.WriteLine("Delete objects succeeded"); } catch (Exception ex) { Console.WriteLine("Delete objects failed. {0}", ex.Message); } ```
C
UTF-8
960
2.6875
3
[]
no_license
#include<stdio.h> void typeline(int n,char *f) { FILE *fp; int c=0,cnt=0; char str[80]; fp=fopen(f,"r"); if(n>0) { printf("The line are:\n"); while(fgets(str,80,fp)) { printf("%s\n",str); c++; if(c==n) break; } } else if(n<0) { while(fgets(str,80,fp)) { c++; } fclose(fp); fp=fopen(f,"r"); while(fgets(str,80,fp)) { cnt++; if(cnt==(c+n)) break; } printf("The lines are:\n"); while(fgets(str,80,fp)) { printf("%s\n",str); } } else if(n==0) { printf("All Lines are:\n"); while(fgets(str,80,fp)) { printf("%s\n",str); } } fclose(fp); } main() { char cmd[50],t1[20],t2[20],t3[20]; int d; while(1) { printf("\nMyshell$]"); gets(cmd); sscanf(cmd,"%s%s%s",t1,t2,t3); d=atoi(t2); if(strcmp(t1,"q")==0) exit(0); if(strcmp(t1,"typeline")==0) typeline(d,t3); else if(fork()) { execlp(t1,t1,t2,t3,NULL); perror(t1); } } }
PHP
UTF-8
564
2.671875
3
[]
no_license
<?php include 'archivo.class.php'; /** * */ class Imagen extends Archivo { public function imagenImprimir($ruta,$title,$tipos) { if($tipos==1) { $tipos='img-rounded'; } else if($tipos==2) { $tipos='img-circle'; } else if($tipos==3) { $tipos='img-thumbnail'; } $this->imagen_titulo = '<img style="width: auto; height:auto"'; $this->imagen_titulo .= 'src="'.$ruta.'" alt="'.$title.'" title="'.$title.'"'; $this->imagen_titulo .= ' class="'.$tipos.' img-responsive">'; echo $this->imagen_titulo; } } ?>
C++
UTF-8
9,019
2.546875
3
[]
no_license
//================================================================================================= // // Bx Engine // bxs3514 @ 2016 - 2018 // // All code licensed under the MIT license // //================================================================================================ #if BX_OPENGL #include "OpenGLTemplate.h" #include <random> using Math::Vector3; OpenGLTemplate::OpenGLTemplate( Setting* pSetting, const BOOL defaultScene) : m_pSetting(pSetting), m_context(pSetting) { if (defaultScene == TRUE) { createDefaultScene(); } } OpenGLTemplate::~OpenGLTemplate() { } void OpenGLTemplate::run() { m_context.run(); } void OpenGLTemplate::createDefaultScene() { std::default_random_engine generator; std::uniform_real_distribution<float> distribution(0.0, 1.0); m_context.initialize(); Scene* pScene = m_context.GetScene(); pScene->EnableDebug(); /*pScene->AddDirectionalLight(Vector3(0.0f, -1.0f, 0.0f), Vector3(0.5f, 0.5f, 0.5f));*/ pScene->AddDirectionalLight(Vector3(-1.0f, -1.0f, -1.0f), Vector3(0.5f, 0.5f, 0.5f)); /*pScene->AddDirectionalLight(Vector3( 1.0f, -1.0f, -1.0f), Vector3(0.5f, 0.5f, 0.5f));*/ /*pScene->AddSpotLight( Vector3(0.0f, 3.0f, 2.0f), Vector3(0.0f, -1.0f, 0.0f), Vector3(0.5f, 0.0f, 0.0f), 5.0f, Math::Radians(60.0f), Math::Radians(90.0f)); pScene->AddSpotLight( Vector3(2.0f, 3.0f, 0.0f), Vector3(0.0f, -1.0f, 0.0f), Vector3(0.0f, 0.5f, 0.0f), 5.0f, Math::Radians(60.0f), Math::Radians(90.0f)); pScene->AddSpotLight( Vector3(-2.0f, 3.0f, 0.0f), Vector3(0.0f, -1.0f, 0.0f), Vector3(0.0f, 0.0f, 0.5f), 5.0f, Math::Radians(60.0f), Math::Radians(90.0f));*/ // pScene->AddPointLight(Vector3(0.0f, -0.5f, 0.0f), Vector3(1.0f, 0.0f, 0.0f), 1.0f); /*pScene->AddPointLight(Vector3( 0.0f, 0.0f, 0.0f), Vector3(0.5f, 0.0f, 0.0f), 2.0f); pScene->AddPointLight(Vector3( 1.0f, 0.0f, 0.0f), Vector3(0.0f, 0.5f, 0.0f), 2.0f); pScene->AddPointLight(Vector3(-1.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, 0.5f), 2.0f);*/ for (int i = 0; i < 64; ++i) { for (int j = 0; j < 63; ++j) { pScene->AddPointLight(Vector3(-100.0f + i * 2.0f, 0.0f, -100.0f + j * 2.0f), Vector3(distribution(generator), distribution(generator), distribution(generator)), 5.0f); } } /*for (int i = 0; i < 2040; ++i) { pScene->AddPointLight(Vector3(-70.0f + i * 0.1f, 0.0f, 0.5f), Vector3(distribution(generator), distribution(generator), distribution(generator)), 5.0f); }*/ /*pScene->AddDirectionalLight(Vector3( 1.0f, -1.0f, -1.0f), Vector3(0.5f, 0.0f, 0.0f)); pScene->AddDirectionalLight(Vector3(-1.0f, -1.0f, 1.0f), Vector3(0.0f, 0.5f, 0.0f)); pScene->AddDirectionalLight(Vector3( 1.0f, -1.0f, 1.0f), Vector3(0.0f, 0.0f, 0.5f));*/ const float invAspectRadio = static_cast<float>(m_pSetting->resolution.height) / static_cast<float>(m_pSetting->resolution.width); /*pScene->addProspectiveCamera(glm::vec3(0.0f, 2.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0, 0, 1.0f), 5.0f, aspectRadio, 0.1f, 1000.0f, 60.0f);*/ /*float halfWidth = static_cast<float>(m_pSetting->resolution.width * 2) * 0.002f; float halfHeight = static_cast<float>(m_pSetting->resolution.width * 2) * 0.002f;*/ //Vector3 lightDir = pScene->m_directionalLight.getDir(); //glm::vec3 glmLightDir = glm::vec3(lightDir.x, lightDir.y, lightDir.z); //float lightPosScale = 100.0f; /*pScene->addOrthographicCamera( -glmLightDir * lightPosScale, glmLightDir, glm::vec3(0, 1, 0), 5.0f, Rectangle(-halfWidth, halfWidth, -halfHeight, halfHeight), 0.1f, 1000.0f);*/ /*pScene->addProspectiveCamera(glm::vec3(0.0f, 15.0f, 10.0f), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), 5.0f, aspectRadio, 0.1f, 1000.0f);*/ /*pScene->addProspectiveCamera(glm::vec3(0.0f, 0.0f, 5.0f), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), 100.0f, invAspectRadio, 0.1f, 10000.0f, 90.0f);*/ //pScene->AddDirectionalLight(Vector3(-1.0f, -1.0f, -1.0f), Vector3(0.5f, 0.5f, 0.5f)); pScene->addProspectiveCamera(glm::vec3(-80.0f, 0.0f, 0.0f), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), 10.0f, invAspectRadio, 0.1f, 1000.0f, 70.0f); /*pScene->addProspectiveCamera(glm::vec3(0.0f, 5.0f, 0.1f), glm::vec3(0, 4, 0), glm::vec3(0, 1, 0), 5.0f, aspectRadio, 0.1f, 1000.0f, 70.0f);*/ //m_pLightCamera = new ProspectiveCamera( // /*lightPos, lightPos + glmLightDir,*/ // glm::vec3(0.0f, 10.0f, 0.1f), glm::vec3(0, 4, 0), // glm::vec3(0.0f, 1.0f, 0.0f), 0.0f, aspectRadio, 0.1f, 1000.0f); #if _DEBUG //Load model and texture(Hardcode here) pScene->addModel("../resources/models/box/box.obj", "../resources/models/box/box.mtl", new Trans(glm::vec3(-70.0f, 0.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); #else /*pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3(0.0f, -0.5f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f)));*/ //Model* pModel = pScene->GetModelPtr(0); /*pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3( 3.0f, 0.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/box/box.obj", "../resources/models/box/box.mtl", new Trans(glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/plane/plane.obj", "../resources/models/plane/plane.mtl", new Trans(glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f)));*/ /*pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3( 0.0f, 0.0f, 3.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3( 3.0f, 0.0f, 3.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3( 3.0f, 0.0f, -3.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3(-3.0f, 0.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3(-3.0f, 0.0f, 3.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3( 0.0f, 0.0f, -3.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel("../resources/models/sphere/sphere.obj", "../resources/models/sphere/sphere.mtl", new Trans(glm::vec3(-3.0f, 0.0f, -3.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f)));*/ pScene->addModel("../resources/models/sponza/sponza_big.obj", "../resources/models/sponza/sponza_big.mtl", new Trans(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel( "../resources/models/buddha/buddha.obj", "../resources/models/buddha/buddha.mtl", new Trans(glm::vec3(10.0f, -30.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); pScene->addModel( "../resources/models/dragon/dragon.obj", "../resources/models/dragon/dragon.mtl", new Trans(glm::vec3(0.0f, -30.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f))); #endif /*pScene->addModel( "../resources/models/cornellbox/CornellBox-Sphere.obj", "../resources/models/cornellbox/CornellBox-Sphere.mtl", new Trans(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(), glm::vec3(0.0f, 1.0f, 0.0f)));*/ //pScene->GetModelPtr(0)->m_pTrans->SetScale(glm::vec3(5.0f, 5.0f, 5.0f)); //Create texture and set sampler pScene->addTexture("../resources/textures/teaport/wall.jpg", GL_TEXTURE_2D, GL_RGBA, GL_UNSIGNED_BYTE, GL_REPEAT, GL_TRUE); pScene->addSkyboxImage( "../resources/textures/skybox/SunSet/SunSetLeft2048.png", "../resources/textures/skybox/SunSet/SunSetRight2048.png", "../resources/textures/skybox/SunSet/SunSetUp2048.png", "../resources/textures/skybox/SunSet/SunSetDown2048.png", "../resources/textures/skybox/SunSet/SunSetFront2048.png", "../resources/textures/skybox/SunSet/SunSetBack2048.png"); pScene->disableSceneLocalMaterial(); } #endif
JavaScript
UTF-8
855
3.046875
3
[]
no_license
var Box = Newton.createClass({ getInitialState: function(){ return {visible: true}; }, render: function(){ return $('div', {className: 'box'}); } }); var Circle = Newton.createClass({ getInitialState: function(){ return {visible: true}; }, render: function(){ return $('div', {className: 'box'}); } }); var box = new Box(); var circle = new Circle(); console.log(box); console.log(box instanceof Box); //true console.log(box instanceof Newton.Component); // true console.log(circle); console.log(box.getUID()); console.log(circle.getUID()); console.log(box instanceof Box); //true console.log(box instanceof Newton.Component); // true console.log(box.state);// box.state; // {visible: true} box.setState({ visible: false }); box.setState({ visiblex: false }); console.log(box.state); console.log(box.render());
Java
UTF-8
419
2.828125
3
[]
no_license
package entities; public class StateModel { private double reward = 0.000; private boolean isWall = false; public StateModel(double reward) { this.reward = reward; } public double getReward() { return reward; } public void setReward(double reward) { this.reward = reward; } public boolean getIsWall() { return isWall; } public void setIsWall(boolean isWall) { this.isWall = isWall; } }
JavaScript
UTF-8
796
2.953125
3
[]
no_license
const WORLD = { /* largura escolhida para ser bem maior que a tela */ width: 2400, height: 506, backgroundColor: "#0a79f1", gravity : Vector2D(0, .005), xOffSet: 0, yOffSet: 0, inside: [], }; WORLD.update = function() { for (let element of this.inside) { OPERATIONS.update[element.type].call(element); } }; WORLD.render = function render() { CTX.fillStyle = this.backgroundColor; CTX.fillRect(this.xOffSet, this.yOffSet, this.width, this.height); for (let element of this.inside) { /* O próprio WORLD object é o contexto */ OPERATIONS.render[element.type] .call(element, Object.assign({}, this)); } }; WORLD.changeOffSet = function changeOffSet(x, y) { this.xOffSet = x; this.yOffSet = y; };
C#
UTF-8
1,553
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace Kapsch.Core.Caching { public class MemoryCache<T> : ICache<T> where T : class { private string _name; public MemoryCache(string name) { this._name = name; } public T Get(string key, bool remove = false) { return Cache[GetCompositeKey(key)] as T; } public void Set(string key, T data, long cacheTimeMinutes = 1440) { var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.UtcNow + TimeSpan.FromMinutes(cacheTimeMinutes) }; Cache.Add(new CacheItem(GetCompositeKey(key), data), policy); } public bool IsSet(string key) { return (Cache[GetCompositeKey(key)] != null); } public void Remove(string key) { Cache.Remove(GetCompositeKey(key)); } public void Clear() { var allKeys = Cache.Select(f => f.Key).Where(f => f.StartsWith(_name)).ToList(); Parallel.ForEach(allKeys, key => Cache.Remove(key)); } private string GetCompositeKey(string key) { return string.Format("{0}_{1}", _name, key); } private static ObjectCache Cache { get { return System.Runtime.Caching.MemoryCache.Default; } } } }
C#
UTF-8
1,512
2.890625
3
[ "MIT" ]
permissive
using ExchangeRateResolver.Models; using System; using System.Collections.Generic; using System.Text; namespace ExchangeRateResolver.Parsers { public class PriceUpdaterParser : IParser { private PriceUpdate _data; public PriceUpdaterParser() { } public object GetLastResult() { return _data; } public object Parse(string command) { var tokens = command?.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (tokens?.Length == 6) { _data = new PriceUpdate(); _data.OriginalCommand = command; DateTime timeStamp; if (DateTime.TryParse(tokens[0], out timeStamp)) { _data.TimeStamp = timeStamp; } _data.Exchange = tokens[1].ToUpper(); _data.SourceCurrency = tokens[2].ToUpper(); _data.DestinationCurrency = tokens[3].ToUpper(); float forwardFactor; if (float.TryParse(tokens[4], out forwardFactor)) { _data.ForwardFactor = forwardFactor; } float backwardFactor; if (float.TryParse(tokens[5], out backwardFactor)) { _data.BackwardFactor = backwardFactor; } } return _data; } } }
C#
UTF-8
929
3.46875
3
[]
no_license
using System; using System.Linq; namespace AdventLibrary.Day2 { public class DifferenceGridChecksumCalculator { public int CalculateFor(string input) { var accumulated = 0; var lines = input.Split(new []{'\n','\r'}, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { var values = line.Split(new []{'\t',' '}, StringSplitOptions.RemoveEmptyEntries) .Select(a => Convert.ToInt32(a)); var min = 100000; var max = 0; foreach (var value in values) { if (value < min) min = value; if (value > max) max = value; } accumulated += max - min; } return accumulated; } } }
SQL
UTF-8
1,313
2.96875
3
[]
no_license
CREATE TABLE ITEM ( ID VARCHAR(3) PRIMARY KEY, NAME VARCHAR(40) NOT NULL, PRICE DECIMAL(8,2) NOT NULL, DESCRIPTION VARCHAR(255), IMAGE VARCHAR(40) ); CREATE TABLE T_USER ( ID VARCHAR(50) PRIMARY KEY, PASSWORD VARCHAR(255) NOT NULL ); CREATE TABLE ADDRESS ( ID VARCHAR(50) PRIMARY KEY, NAME VARCHAR(50), LINE1 VARCHAR(50), LINE2 VARCHAR(50), POSTCODE VARCHAR(10), CITY VARCHAR(30) ); insert into ITEM values ('app','Apple Pie', 8.5, 'a delicious apple pie with fresh apples','applepie.jpg'); insert into ITEM values ('ecc','Eclair au chocolat', 6.5, 'a French chocolate treat','eclair.jpg'); insert into ITEM values ('mac','Macarons', 9.5, 'so delicate !','macarons.jpg'); insert into ITEM values ('str', 'Strudel', 6.0, 'a German apple pie','strudel.jpg'); insert into ITEM values ('cro','Croissant', 1.5,'the famous French pastry','croissant.jpg'); insert into ITEM values ('pro','Profiteroles', 9.0,'Ice cream and melting chocolate : the perfect match','profiteroles.jpg'); INSERT INTO T_USER VALUES ('stb@cnam.fr', '$2a$10$Wp6BYM99hA4B1ufrJBtAzeqgG8qlhbtl94YYn0rcUubpqsaAw/vjm'); INSERT INTO ADDRESS VALUES ('stb@cnam.fr','Stéphane Bruyère','210, R du Fg St Martin','','CP75010', 'PARIS');
JavaScript
UTF-8
858
3.546875
4
[]
no_license
function removeDuplicates(arr) { var len = arr.length var unique = [], position = [], str = [] // Finding the position of duplicates in the array for(var i = 0; i < len; i++){ str[i] = arr[i] for(var j = i + 1; j < len; j++){ if(str[i] == arr[j]){ position.push(j) } } } // Adding only unique elemets to another array for(var i = 0; i < len; i++){ var count = 0 for(var j = 0; j < position.length; j++){ if(i == position[j]){ count++ } } if(count == 0){ unique.push(arr[i]) } } return unique } console.log(removeDuplicates([1, 2, 3, 2, 5, 4, 1, 9, 1, 45, 23, 9, 45, 99, 99])) console.log(removeDuplicates(['a', 'b', 'c', 'e', 'gth', 'xyz', 'gth', 'b', 'e', 'iu']))
C#
UTF-8
704
2.609375
3
[ "MIT" ]
permissive
 namespace PopFree.Pop3 { /// <summary> /// Possible responses received from the server when performing an Authentication /// </summary> public enum AuthenticationResponse { /// <summary> /// Authentication succeeded /// </summary> Success = 0, /// <summary> /// Login doesn't exist on the Pop3 server /// </summary> InvalidUser = 1, /// <summary> /// Password is invalid for the give login /// </summary> InvalidPassword = 2, /// <summary> /// Invalid login and/or password /// </summary> InvalidUserOrPassword = 3 } }
Markdown
UTF-8
628
2.75
3
[]
no_license
The project consists of three files: my-cat.c, my-sed.c, and my-uniq.c. All files function indepently. my.cat reads a file as specified by the user and prints its contents. ex. ./my-cat filename my.sed will only be used to find and replace it with the exact given string. It will find the first instance of a string in a line and substitute it with another. It will print the output to standard output. Instances following the first instance remain as is. ex. ./my-sed foo bar baz.txt qux.txt my-uniq finds out unique lines by only comparing them only with their adjacent lines, and prints them. ex. ./my-sed foo "" bar.txt
Python
UTF-8
1,384
2.796875
3
[]
no_license
from urllib.request import urlopen from bs4 import BeautifulSoup import csv import json def crawl(url): html = urlopen(url) soup = BeautifulSoup(html, "html.parser") body = soup.select('#bodyContent') return(body[0].text) crawl('https://en.wikipedia.org/wiki/Norberto_Alonso') if __name__ == '__main__': dev_file = open("gap-development.tsv", 'r', encoding='utf-8') dev_read_file = csv.reader(dev_file, delimiter="\t") dev_set = [] for line in dev_read_file: dev_set.append(line) dev_set = dev_set[1:] test_file = open("gap-test.tsv", 'r', encoding='utf-8') test_read_file = csv.reader(test_file, delimiter="\t") test_set = [] for line in test_read_file: test_set.append(line) test_set = test_set[1:] dev_url = {} for line in dev_set: tid = line[0] url = line[10] try: dev_url[tid] = crawl(url) except: print (tid, url) test_url = {} for line in test_set: tid = line[0] url = line[10] try: test_url[tid] = crawl(url) except: print (tid, url) with open('dev_url.json', 'w') as dev_file: json.dump(dev_url, dev_file, ensure_ascii=False) with open('test_url.json', 'w') as test_file: json.dump(test_url, test_file, ensure_ascii=False)
Python
UTF-8
4,011
3.15625
3
[]
no_license
import random import time run = 32 def merge(arr, l, m, r): # print (l, " ",m," " ,r) n1 = m - l + 1 n2 = r - m # create temp arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0 , n1): L[i] = arr[l + i] for j in range(0 , n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2 : if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = R[j] j += 1 k += 1 def insertionSort(arr, left, right): for i in range(left + 1, right + 1): temp = arr[i]; j = i - 1; while j >= left and temp < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = temp; """ for ( i = left + 1, i <= right, i=i+1): int temp = arr[i]; int j = i - 1; while (arr[j] > temp && j >= left): arr[j+1] = arr[j]; j--; arr[j+1] = temp; """ def insertionSort1(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # print(key) # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i - 1 # print(arr[j]) while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def timSort(arr, n): <<<<<<< HEAD # j=run j = run i = 0; l = 0; ======= j = run i = 0; l=0; >>>>>>> branch 'master' of https://github.com/lovedeepSangha/algorithms.git for i in range(0, n - 1, run): insertionSort(arr, i, min((i + 31), (n - 1))) <<<<<<< HEAD for j in range(run, n - 1, j=(2 * j)): for j in range(run, n - 1, 2 * j): for l in range(0, n - 1, l + (2 * j)): mid = l + j - 1; r = min((l + 2 * j - 1), (n - 1)) merge(arr, l, mid, r) ======= for j in range(run, n - 1, 2 * j): for l in range(0, n - 1, l + (2 * j)): mid = l + j - 1; r = min((l + 2 * j - 1), (n - 1)) merge(arr, l, mid, r) >>>>>>> branch 'master' of https://github.com/lovedeepSangha/algorithms.git <<<<<<< HEAD arr = random.sample(range(1, 100000), 120) ======= arr = random.sample(range(1, 100000), 800) >>>>>>> branch 'master' of https://github.com/lovedeepSangha/algorithms.git timSort(arr, len(arr)) for i in range(len(arr)): print (arr[i]) """// Sort individual subarrays of size RUN for (int i = 0; i < n; i+=RUN) insertionSort(arr, i, min((i+31), (n-1))); // start merging from size RUN (or 32). It will merge // to form size 64, then 128, 256 and so on .... for (int size = RUN; size < n; size = 2*size) { // pick starting point of left sub array. We // are going to merge arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we increase left by 2*size for (int left = 0; left < n; left += 2*size) { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; int right = min((left + 2*size - 1), (n-1)); // merge sub array arr[left.....mid] & // arr[mid+1....right] merge(arr, left, mid, right); } } } """
JavaScript
UTF-8
550
4.59375
5
[]
no_license
/* Given two numbers, say x and y, write a program that determines if the numbers are either between the range of 0-20 or 80-100 , which includes the edges of the limit: 0, 20, 80, and 100. withinLimits(10, 99) // => true withinLimits(21, 81) // => false */ let withinLimits = (a, b) => { let r1 = 0, r2 = 20; let r3 = 80, r4 = 100; let isBetweenRanges = false if ((a >= r1 && a <= r2) && (b >= r3 && b <= r4)) { isBetweenRanges = true } console.log(isBetweenRanges) } withinLimits(10, 99) //true withinLimits(21, 81) //false
C++
UTF-8
4,331
3.09375
3
[]
no_license
#include "Add.hpp" #include "Cpu.hpp" #include "MemoryController.hpp" unsigned short PerformAdd8(Cpu* cpu, unsigned char lh, unsigned char rh, bool addCarry) { unsigned short result = lh + rh; if (addCarry) { if (cpu->TestFlag(cpu::Flag::Carry)) { result++; } } if ((rh & 0xF) + (lh & 0xF) > 0xF) { cpu->SetFlag(cpu::Flag::HalfCarry); } else { cpu->ClearFlag(cpu::Flag::HalfCarry); } if (result > 0xFF) { cpu->SetFlag(cpu::Flag::Carry); } else { cpu->ClearFlag(cpu::Flag::Carry); } if (result == 0) { cpu->SetFlag(cpu::Flag::Zero); } else { cpu->ClearFlag(cpu::Flag::Zero); } cpu->ClearFlag(cpu::Flag::SubOp); return result; } //add the value in target to src (store in src) void Instructions::Add8(Cpu* cpu, Register8 src, Register8 target) { unsigned char target_value = cpu->GetRegister(target); unsigned char src_value = cpu->GetRegister(src); /* unsigned short result = src_value + target_value; if ((target_value & 0xF) + (src_value & 0xF) > 0xF) { cpu->SetFlag(cpu::Flag::HalfCarry); } else { cpu->ClearFlag(cpu::Flag::HalfCarry); } if (result > 0xFF) { cpu->SetFlag(cpu::Flag::Carry); } else { cpu->ClearFlag(cpu::Flag::Carry); } if (result == 0) { cpu->SetFlag(cpu::Flag::Zero); } else { cpu->ClearFlag(cpu::Flag::Zero); } cpu->ClearFlag(cpu::Flag::SubOp);*/ unsigned short result = PerformAdd8(cpu, src_value, target_value, false); cpu->SetRegister(src, static_cast<unsigned char>(result)); } void Instructions::Add16(Cpu* cpu, Register16 src, Register16 target) { unsigned short src_value = cpu->GetRegister(src); unsigned short target_value = cpu->GetRegister(target); unsigned int result = src_value + target_value; if (result > 0x800) { cpu->SetFlag(cpu::Flag::HalfCarry); } else { cpu->ClearFlag(cpu::Flag::HalfCarry); } if (result > 0xFF) { cpu->SetFlag(cpu::Flag::Carry); } else { cpu->ClearFlag(cpu::Flag::Carry); } cpu->SetRegister(src, static_cast<unsigned short>(result)); } void Instructions::Add16_SignedImmediate(Cpu * cpu, Register16 src) { unsigned short src_value = cpu->GetRegister(src); signed short immediate = static_cast<signed short>(cpu->ReadByteOffset(1)); int result = src_value + immediate; if (result > 0x800) { cpu->SetFlag(cpu::Flag::HalfCarry); } else { cpu->ClearFlag(cpu::Flag::HalfCarry); } if (result > 0xFF) { cpu->SetFlag(cpu::Flag::Carry); } else { cpu->ClearFlag(cpu::Flag::Carry); } cpu->SetRegister(src, static_cast<unsigned short>(result)); } void Instructions::Add8_Immediate(Cpu* cpu, Register8 target) { auto immediate = cpu->ReadByteOffset(1); auto targetValue = cpu->GetRegister(target); auto result = PerformAdd8(cpu, targetValue, immediate, false); cpu->SetRegister(target, static_cast<unsigned char>(result)); } void Instructions::AddCarry8_Immediate(Cpu * cpu, Register8 target) { auto immediate = cpu->ReadByteOffset(1); auto targetValue = cpu->GetRegister(target); auto result = PerformAdd8(cpu, targetValue, immediate, true); cpu->SetRegister(target, static_cast<unsigned char>(result)); } void Instructions::AddCarry8(Cpu* cpu, Register8 src, Register8 target) { unsigned char target_value = cpu->GetRegister(target); unsigned char src_value = cpu->GetRegister(src); unsigned short result = PerformAdd8(cpu, src_value, target_value, true); cpu->SetRegister(src, static_cast<unsigned char>(result)); } void Instructions::AddFromAddr8(Cpu* cpu, Register8 target, Register16 addressSrc) { unsigned char target_value = cpu->GetRegister(target); unsigned short address = cpu->GetRegister(addressSrc); unsigned char val = cpu->GetMemoryController()->ReadByte(address); unsigned short result = PerformAdd8(cpu, val, target_value, false); cpu->SetRegister(target, static_cast<unsigned char>(result)); } void Instructions::AddCarryFromAddr8(Cpu* cpu, Register8 target, Register16 addressSrc) { unsigned char target_value = cpu->GetRegister(target); unsigned short address = cpu->GetRegister(addressSrc); unsigned char val = cpu->GetMemoryController()->ReadByte(address); unsigned short result = PerformAdd8(cpu, val, target_value, true); cpu->SetRegister(target, static_cast<unsigned char>(result)); }
JavaScript
UTF-8
3,903
2.578125
3
[ "MIT" ]
permissive
App.Views.Punkt = Backbone.View.extend({ initialize: function(){ //this.model.on("change", this.render, this); }, tagName: 'li', render: function(){ this.$el.html( this.model.get('rejimRab')+ '<br>'+ this.model.get('phone')+ '<br>' + this.model.get('addr')+ '<br>'+this.model.get('name')); return this; } }); /* App.Views.Contact = Backbone.View.extend({ initialize: function(){ this.model.on("destroy", this.unrender, this); this.model.on("change", this.render, this); }, tagName: 'tr', events: { "click a.delete":"delContact", "click a.edit":"editContact", }, template: App.template("singleContact"), render: function(){ this.$el.html( this.template( this.model.toJSON() ) ); this.el.bgColor = "white"; return this; }, unrender: function(){ this.$el.remove(); $("#editContact").hide(); $("#addContact").show(); }, delContact: function(){ this.model.destroy(); }, editContact: function(){ $("#addContact").hide(); $("#editContact").show(); $("#editContact #name").val(this.model.get('name')); $("#editContact #surname").val(this.model.get('surname')); $("#editContact #email").val(this.model.get('email')); $("#editContact #phone").val(this.model.get('phone')); $("#editContact #description").val(this.model.get('description')); $("#editContact #id").val(this.model.get('id')); this.el.bgColor = "LightCyan"; } }); App.Views.App = Backbone.View.extend({ initialize: function(){ var addContact = new App.Views.addContact({collection: App.contacts}); var editContact = new App.Views.editContact({collection: App.contacts}); var contList = new App.Views.contactsList({ collection: App.contacts }); contList.render(); //if(contList.el.childElementCount == 0) // $("body").append("<center><h3>Список пока пуст, заполните его</h3></center>"); $("#allContactsTable").append(contList.el); } }); App.Views.addContact = Backbone.View.extend({ el: "#formAddContact", events: { 'submit' : 'addContact' }, addContact: function(e){ e.preventDefault(); //alert("Добавление контакта"); this.collection.create({ name: this.$("#name").val(), surname: this.$("#surname").val(), email: this.$("#email").val(), phone: this.$("#phone").val(), description: this.$("#description").val(), }, { success: function(response){ inp = $('#delContact').html(); console.log(response.id); } }); this.clearInputs(); }, clearInputs: function(){ $("#name").val(''); $("#surname").val(''); $("#phone").val(''); $("#email").val(''); $("#description").val(''); } }); App.Views.editContact = Backbone.View.extend({ el: "#formEditContact", events: { 'submit' : 'editContact' }, editContact: function(e){ e.preventDefault(); //alert("Добавление контакта"); contact_id = $("#editContact #id").val(); contact = this.collection.get(contact_id); contact.set({ name : $("#editContact #name").val(), surname : $("#editContact #surname").val(), email : $("#editContact #email").val(), phone : $("#editContact #phone").val(), description : $("#editContact #description").val() }); contact.save(); this.clearInputs(); $("#editContact").hide(); $("#addContact").show(); }, clearInputs: function(){ $("#name").val(''); $("#surname").val(''); $("#phone").val(''); $("#email").val(''); $("#description").val(''); } }); App.Views.contactsList = Backbone.View.extend({ initialize: function(){ console.log('privet_mir'); this.collection.on("add", this.addOne, this); }, tagName: 'tbody', render: function(){ this.collection.each(this.addOne, this); return this; }, addOne: function(contact){ if(email = contact.get('email') == '') alert('Ошибка') else{ Contact = new App.Views.Contact({model: contact}); this.$el.a */
Python
UTF-8
3,147
2.5625
3
[]
no_license
# -*- coding: UTF-8 -*- import gtk import os from widgets import ComboFunciones, MatrizLeds class Window: FRECUENCIA = 0.3 ON_OFF_BTN_ON = 'Parar' ON_OFF_BTN_OFF = 'Continuar' def __init__(self, mods_horizontales, mods_verticales): self.build_glade_ui() self.init_matriz_leds(int(mods_horizontales), int(mods_verticales)) self.window.show() def on_window_delete_event(self, widget, data=None): self.matriz_leds.clear() return False def build_glade_ui(self): builder = gtk.Builder() builder.add_from_file(os.path.abspath('funcion.glade')) builder.connect_signals(self) self.fetch_widgets_from_xml(builder) self.init_frecuencia(builder.get_object('frecuencia')) self.init_func_radios(builder) def fetch_widgets_from_xml(self, gtk_builder): self.window = gtk_builder.get_object('window') self.container = gtk_builder.get_object('container') self.on_off_btn = gtk_builder.get_object('on_off_btn') self.txt = gtk_builder.get_object('txt') def init_frecuencia(self, frecuencia): frecuencia.set_value(self.FRECUENCIA) self.frecuencia = frecuencia def init_func_radios(self, gtk_builder): for rbutton in ['bhorizontal', 'bvertical', 'demo', 'texto']: radio_button = gtk_builder.get_object(rbutton) radio_button.connect("toggled", self.on_func_radio_toggled, rbutton) def init_matriz_leds(self, mods_horizontales, mods_verticales): self.matriz_leds = MatrizLeds(mods_horizontales, mods_verticales, self.get_frecuencia()) self.container.pack_start(self.matriz_leds) self.container.reorder_child(self.matriz_leds, 0) self.matriz_leds.show_all() def on_encender_clicked(self, widget): self.on_off_btn.set_label(self.ON_OFF_BTN_OFF) self.matriz_leds.set() def on_limpiar_clicked(self, widget): self.on_off_btn.set_label(self.ON_OFF_BTN_OFF) self.matriz_leds.clear() def on_off_btn_clicked_cb(self, widget): if widget.get_label() == self.ON_OFF_BTN_ON: self.matriz_leds.clear() widget.set_label(self.ON_OFF_BTN_OFF) else: self.matriz_leds.restart() widget.set_label(self.ON_OFF_BTN_ON) def on_frecuencia_value_changed(self, frecuencia): if hasattr(self, 'matriz_leds'): self.matriz_leds.restart(frecuencia=frecuencia.get_value()) def on_func_radio_toggled(self, radio_button, data=None): d = None if data == 'texto': d = self.get_text() if radio_button.get_active(): self.txt.show() else: self.txt.hide() if radio_button.get_active(): self.matriz_leds.set_func(radio_button.get_label(), d) def on_txt_changed(self, widget): if(widget.get_visible()): self.matriz_leds.restart(data=self.get_text()) def get_frecuencia(self): return self.frecuencia.get_value() def get_text(self): return self.txt.get_text() or ' '
Java
UTF-8
1,555
2.984375
3
[]
no_license
package com.homeWork; public class Phone { String name; String model; int year; String os; void security() { System.out.println(name + " " + model + " have more security."); } void lesssecurity() { System.out.println(name + " " + model + " have less security."); } void camera() { System.out.println(name + " " + model + " Can take a picture."); } void ring() { System.out.println(name + " " + model + " Can ring."); } void message() { System.out.println(name + " " + model + " Can send and recieve text and multi media."); } void music() { System.out.println(name + " " + model + " Can play audio and video files."); } public static void main(String[] args) { Phone iPhone = new Phone(); iPhone.name = "iPhone"; iPhone.model = "12"; iPhone.year = 2020; iPhone.os = "IOS 14.1"; iPhone.security(); iPhone.camera(); iPhone.ring(); iPhone.message(); iPhone.music(); System.out.println("******************************************"); Phone android = new Phone(); android.name = "Samsung"; android.model = "S10"; android.year = 2020; android.os = "Android 9.0"; android.camera(); android.ring(); android.message(); android.music(); android.lesssecurity(); System.out.println("******************************************"); Phone nokia = new Phone(); nokia.name = "Nokia 9"; nokia.model = "PureView"; nokia.year = 2019; nokia.os = "Android 9.0"; nokia.camera(); nokia.ring(); nokia.message(); nokia.music(); nokia.lesssecurity(); } }
Markdown
UTF-8
825
3.71875
4
[]
no_license
#List of problems: - Problem 1 - Problem 2 - Problem 4 #Problem 1 Complexity rotate() function: - Line {3} use Array.prototype.reverse, that will take O(n) complexity - Line {2} has a loop with O(n-1) complexity - Line {1} also has a loop with O(n-1) complexity - Line {4} is a recursion considered as an interation with O(m) complexity (m = k % 4) So the complexity: O(m*n^3) The possible values of m If (k % 4) === 0 the complexity is O(1); If (k % 4) === 1 the complexity is O(n^3) If (k % 4) >= 2 the complexity is O(m*n^3) but the m is an interger and always within [0, 3] so the final complexity should be O(n^3) How to run all the test suites with jest Run npm run test Problem 2 How to run: npm run prob2 Problem 4 How to run: npm run prob4
Java
UTF-8
1,425
3.359375
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class P07_PhoneNumber { public static void main(String[] args) throws IOException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); LinkedHashMap<String, String> phoneBook = new LinkedHashMap<>(); Pattern pattern = Pattern.compile("([A-Z][a-zA-Z]*)(?:[^a-zA-Z+]*?)(\\+?\\d[\\d()./\\- ]*\\d)"); StringBuilder text = new StringBuilder(); String input; while (!"END".equals(input = reader.readLine())) text.append(input); Matcher matcher = pattern.matcher(text); while (matcher.find()) { String name = matcher.group(1); String number = matcher.group(2).replaceAll("[^+\\d]", ""); phoneBook.put(name, number); } if (phoneBook.isEmpty()) { System.out.println("<p>No matches!</p>"); return; } StringBuilder output = new StringBuilder("<ol>"); for (String name : phoneBook.keySet()) { String number = phoneBook.get(name); output.append(String.format("<li><b>%s:</b> %s</li>", name, number)); } output.append("</ol>"); System.out.println(output); } }
Java
UTF-8
737
1.703125
2
[]
no_license
package com.google.android.gms.internal.measurement; import android.os.RemoteException; /* renamed from: com.google.android.gms.internal.measurement.e reason: case insensitive filesystem */ final class C0349e extends a { /* renamed from: e reason: collision with root package name */ private final /* synthetic */ String f5164e; /* renamed from: f reason: collision with root package name */ private final /* synthetic */ Cf f5165f; C0349e(Cf cf, String str) { this.f5165f = cf; this.f5164e = str; super(cf); } /* access modifiers changed from: 0000 */ public final void a() throws RemoteException { this.f5165f.p.endAdUnitExposure(this.f5164e, this.f4896b); } }
JavaScript
UTF-8
609
2.515625
3
[]
no_license
import React, { Component } from 'react'; import './App.css'; class OptionSelecter extends Component { render() { const { options } = this.props.options; const optionsList = options.map(option => { return ( <option value={option.value}>{option.txt}</option> ) }) return ( <div> <select name={this.props.name} value={this.props.value} onChange={this.props.onChangeFunction}> {optionsList} </select> </div> ) } } export default OptionSelecter;
Java
UTF-8
3,211
2.3125
2
[]
no_license
package com.micro.android316.housekeeping.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.micro.android316.housekeeping.CustomControls.RatingBar; import com.micro.android316.housekeeping.R; import com.micro.android316.housekeeping.model.ElderlyDate; import com.micro.android316.housekeeping.utils.LoadImage; import java.util.List; /** * Created by Administrator on 2016/12/10. */ public class ElderAdapter extends BaseAdapter{ private Context context; private List list; private LayoutInflater inflater; public ElderAdapter(Context context,List list){ inflater=LayoutInflater.from(context); this.list=list; this.context=context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView==null){ convertView=inflater.inflate(R.layout.elderly_item,null); holder=new ViewHolder(); holder.name= (TextView) convertView.findViewById(R.id.name); holder.age= (TextView) convertView.findViewById(R.id.age); holder.wk_time= (TextView) convertView.findViewById(R.id.wk_time); holder.wk_space= (TextView) convertView.findViewById(R.id.wk_space); holder.js= (TextView) convertView.findViewById(R.id.js); holder.gz= (TextView) convertView.findViewById(R.id.gz); holder.pl= (TextView) convertView.findViewById(R.id.pl); holder.head= (ImageView) convertView.findViewById(R.id.head); holder.ratingBar= (RatingBar) convertView.findViewById(R.id.rating_bar); convertView.setTag(holder); }else{ holder= (ViewHolder) convertView.getTag(); } ElderlyDate date= (ElderlyDate) list.get(position); if(date.getName()!=null) holder.name.setText(date.getName()); if(date.getAge()!=null) holder.age.setText(date.getAge()+"岁"); if(date.getExperience()!=null) holder.wk_time.setText("从业时间:"+date.getExperience()); if(date.getWorkSpace()!=null) holder.wk_space.setText("工作范围: "+date.getWorkSpace()); if(date.getBriefIntroduction()!=null) holder.js.setText(date.getBriefIntroduction()); if(date.getGuanZhu_count()!=null) holder.gz.setText(date.getGuanZhu_count()); //holder.pl.setText(date.getPingLun_count()); if(date.getHeadURL()!=null) LoadImage.Load(holder.head,date.getHeadURL(),context); holder.ratingBar.setRating(date.getStars()); return convertView; } class ViewHolder{ ImageView head; TextView name ,age,wk_time,wk_space,js,gz,pl; RatingBar ratingBar; } }
C++
WINDOWS-1258
1,425
3.859375
4
[]
no_license
/*Given an index k, return the kth row of the Pascals triangle. Pascals triangle : To generate A[C] in row R, sum up A[C] and A[C-1] from previous row R - 1. NOTE : k is 0 based. k = 0, corresponds to the row [1]. Note:Could you optimize your algorithm to use only O(k) extra space? Example: Input : k = 3 Ans: [1,3,3,1]*/ #include <iostream> #include<bits/stdc++.h> using namespace std; vector<int>getRow(int A) { int i,j; vector<int> ans; ans.push_back(1); if(A==0) return ans; ans.push_back(1); if(A==1) return ans; for(i=2;i<=A;i++) { vector<int> previous; for(j=0;j<ans.size();j++) previous.push_back(ans[j]); ans.clear(); for(j=0;j<=i;j++) { if(j==0 || j==i) ans.push_back(1); else ans.push_back(previous[j-1]+previous[j]); } } return ans; } int main() { int n; string a; cout<<"Enter the row number for Pascal Triangle value to print :-"; cin>>n; switch(n){ case 1: a="st"; break; case 2: a = "nd"; break; case 3: a = "rd"; break; default: a = "th"; } vector<int> pascal_row_value; pascal_row_value = getRow(n); cout<<n<<a<<" row value of pascal triangle is :- "; for(int i=0;i<pascal_row_value.size();i++) cout<<pascal_row_value[i]<<" "; return 0; }
Java
UTF-8
4,547
2.125
2
[ "Apache-2.0" ]
permissive
package org.noear.water.dso; import org.noear.snack.ONode; import org.noear.water.WW; import org.noear.water.WaterAddress; import org.noear.water.WaterClient; import org.noear.water.WaterSetting; import org.noear.water.log.Level; import org.noear.water.log.LogEvent; import org.noear.water.utils.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 日志服务接口 * * @author noear * @since 2.0 * */ public class LogApi { protected final ApiCaller apiCaller; public LogApi() { apiCaller = new ApiCaller(WaterAddress.getLogApiUrl()); } /** * 添加日志 */ public void append(String logger, Level level, Map<String, Object> map) { append(logger, level, (String) map.get("tag"), (String) map.get("tag1"), (String) map.get("tag2"), (String) map.get("tag3"), (String) map.get("summary"), map.get("content")); } /** * 添加日志 */ public void append(String logger, Level level, String summary, Object content) { append(logger, level, null, null, null, null, summary, content, true); } /** * 添加日志 */ public void append(String logger, Level level, String tag, String summary, Object content) { append(logger, level, tag, null, null, null, summary, content, true); } /** * 添加日志 */ public void append(String logger, Level level, String tag, String tag1, String summary, Object content) { append(logger, level, tag, tag1, null, null, summary, content, true); } /** * 添加日志 */ public void append(String logger, Level level, String tag, String tag1, String tag2, String summary, Object content) { append(logger, level, tag, tag1, tag2, null, summary, content, true); } /** * 添加日志 */ public void append(String logger, Level level, String tag, String tag1, String tag2, String tag3, String summary, Object content) { append(logger, level, tag, tag1, tag2, tag3, summary, content, true); } /** * 添加日志 * * @param logger 日志接收器 * @param level 等级 * @param tag 标签 * @param tag1 标签1 * @param tag2 标签2 * @param tag3 标签3 * @param summary 简介 * @param content 内容 * @param async 是否异步提交 */ public void append(String logger, Level level, String tag, String tag1, String tag2, String tag3, String summary, Object content, boolean async) { String trace_id = WaterClient.waterTraceId(); appendDo(logger, trace_id, level, tag, tag1, tag2, tag3, summary, content); } private void appendDo(String logger, String trace_id, Level level, String tag, String tag1, String tag2, String tag3, String summary, Object content) { if (TextUtils.isEmpty(logger)) { return; } if (logger.indexOf(".") > 0) { return; } Datetime datetime = Datetime.Now(); LogEvent log = new LogEvent(); log.logger = logger; log.level = level.code; log.tag = tag; log.tag1 = tag1; log.tag2 = tag2; log.tag3 = tag3; log.summary = summary; log.content = LogHelper.contentAsString(content); log.trace_id = trace_id; log.from = WaterClient.localServiceHost(); log.thread_name = Thread.currentThread().getName(); log.log_date = datetime.getDate(); log.log_fulltime = datetime.getFulltime(); LogPipeline.singleton().add(log); } public void appendAll(List<LogEvent> list, boolean async) { if (async) { WaterSetting.pools.submit(() -> { appendAllDo(list); }); } else { appendAllDo(list); } } private void appendAllDo(List<LogEvent> list) { if (list == null || list.size() == 0) { return; } String json = ONode.serialize(list); try { if (WaterSetting.water_logger_gzip()) { apiCaller.postBody("/log/add2/", GzipUtils.gZip(json), WW.mime_glog); } else { Map<String, String> map = new HashMap<>(); map.put("list", json); apiCaller.post("/log/add2/", map); } } catch (Exception ex) { ex.printStackTrace(); } } }
Markdown
UTF-8
4,452
2.765625
3
[ "DOC" ]
permissive
# Maya Reference Edit Router Documentation The Maya USD plugin supports hosting a Maya reference inside the USD scene. This Maya reference can be edited as Maya data and then cached as USD prims. The caching process supports customization of its behaviour, even a full replacement of its logic through an `edit router`. This document outlines the API of this `edit router` and what the default implementation does. ## Edit Router Generalities The edit router is a callback that receives information in a USD `VtDictionary` and fills another `VtDictionary` with information about what work it did. The interface to declare and register an `edit router` is found in the file `lib\mayaUsd\utils\editRouter.h`. It declares the `EditRouter` class itself and functions to register and retrieve an `edit router`. The `edit router` is registered and retrieved by name. ## Maya Reference Edit Router The Maya Reference `edit router` is named "mayaReferencePush". The default implementation found in the file `lib\mayaUsd\utils\editRouter.cpp` as the function named `cacheMayaReference` does the following: - Extract all necessary inputs from the input `VtDictionary`. - Validate the path of the Maya Reference that was edited. - Validate the destination layer and destination prim. - Determine the file format of the USD cache. - Export the edited Maya data into a USD layer, the USD cache. - Copy the transform of the root of the Maya data into the Maya Reference. - Refer to the USD cache either as a reference or payload, optionally in a variant. - Fill the output `VtDictionary` with information about the layer and prim. We will go into more details about these steps in the following sections. ### Maya Reference Edit Router Inputs The input information received by the Maya Reference `edit router` are: - "prim" (std::string): the `SdfPath` of the USD Maya Reference that was edited. - "defaultUSDFormat" (std::string): the USD file format used to create the cache. - "rn_layer" (std::string): the absolute file path to the cache. A layer will be created there. - "rn_relativePath" (int): if the file path should be converted to be relative to the layer containing the reference. 0 or 1. - "rn_primName" (std::string): the name of the root prim of the cache. - "rn_listEditType" (std::string): how the reference is added: "Append" or "Prepend". - "rn_payloadOrReference" (std::string): type of ref: "Reference" or "Payload". - "rn_defineInVariant" (int): if the cache is in a variant. 0 or 1. - "rn_variantSetName" (std::string): name of the variant set if in a variant. - "rn_variantName" (std::string): name of the variant in the set, if in a variant. - "src_stage" (UsdStageRefPtr): the source `UsdStage` to copy the transform. - "src_layer" (SdfLayerRefPtr): the source `SdfLayer` to copy the transform. - "src_path" (SdfPath): the source `SdfPath` to copy the transform. - "dst_stage" (UsdStageRefPtr): the destination `UsdStage` to copy the transform. - "dst_layer" (SdfLayerRefPtr): the destination `SdfLayer` to copy the transform. - "dst_path" (SdfPath): the destination `SdfPath` to copy the transform. The last six inputs correspond to the parameters received by the Maya Reference updater `pushCopySpecs` function. That is the function that is calling the `edit router`. ### Validation and Export The Maya Reference default `edit router` validates various inputs to verify that the Maya Reference exists and was edited. It then exports the Maya scene nodes of the Maya Reference file to a USD layer file. That layer file will be used as the USD cache representing the contents of the Maya Reference. ### Copy the Transform To support that the user might have moved the root of the Maya Reference when editing as Maya data, the transform of this root is copied to the USD Maya Reference. This preserve the position of the data. ### Create the Cache Prim The USD cache must be referenced in the USD stage. The `edit router` creates a reference or payload, possibly in a variant, inside a USD prim. Remember that the path to that prim was given in "rn_primName". ### Fill the Output VtDictionary The output `VtDictionary` is filled with the following information: - "layer" (std::string): the identifier of the cache layer, will be equal to "rn_layer". - "save_layer" (std::string): "yes" if the layer should be saved. (Calling `Save` on it.) - "path" (std::string): the `SdfPath` to the prim that contains the cache.
C++
UTF-8
445
3.171875
3
[]
no_license
/* 题目:尾部的零 容易 题目大意: 给定一个n,求n!的尾部的0有多少个 解题思路: 直接算 遇到的问题: 老问题,没有问题 */ class Solution { public: // param n : description of n // return: description of return long long trailingZeros(long long n) { long long ans = 0; while (n > 0) { n /= 5; ans += n; } return ans; } };
PHP
UTF-8
4,084
2.84375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Ice * Date: 06.03.2017 * Time: 3:20. */ namespace App\Model; use App\Engine\Model; /** * Class Comment. */ class Comment extends Model { /** * @param array $posts * * @return array */ public function getComments(array $posts) { $result = []; foreach ($posts as $post) { $post_id = (int) $post['id']; $result[$post_id] = $this->getCommentsByPost($post_id); } return $result; } /** * @param $post_id * * @return array */ public function getCommentsByPost($post_id) { $result = []; $sql = 'SELECT `c`.`id`' . ' FROM `comments` c' . ' WHERE `c`.`post_id` = ' . (int) $post_id . ' ORDER BY `created_at` ASC'; $query = $this->db->query($sql); if($query->num_rows){ foreach ($query->rows as $row) { $result[] = $this->getComment($row['id']); } } return $this->getTreeViewComments($result); } /** * sort comments for tree-view. * * @param array $comments */ protected function getTreeViewComments(array $comments) { $result = []; //sort by parent foreach ($comments as $comment) { $result[$comment['parent_id']][] = $comment; } //final sort return $this->getCommentChildren(0, $result); } /** * Recursive set tree for comments. * * @param $parent_id * @param array $comments * * @return array */ protected function getCommentChildren($parent_id, array $comments) { $result = []; if(true === array_key_exists($parent_id, $comments)){ foreach ($comments[$parent_id] as $comment) { $result[] = $comment; if(true === array_key_exists($comment['id'], $comments)){ $childrens = $this->getCommentChildren($comment['id'], $comments); if(0 !== count($childrens)){ $result = array_merge($result, $childrens); } } } } return $result; } /** * @param $id * * @return array */ public function getComment($id) { $result = []; $sql = 'SELECT `c`.`id`, `c`.`body`, `c`.`user_id`, `c`.`post_id`, `c`.`parent_id`, `c`.`level`, `u`.`name` as username,' . ' DATE_FORMAT(`c`.`created_at`, "%d.%m.%Y %H:%i") as created_at,' . ' DATE_FORMAT(`c`.`updated_at`, "%d.%m.%Y %H:%i") as updated_at' . ' FROM `comments` c' . ' LEFT JOIN `users` u ON `c`.`user_id`=`u`.`id`' . ' WHERE `c`.`id`= ' . (int) $id; $query = $this->db->query($sql); if($query->num_rows){ $result = $query->row; } return $result; } /** * @param array $data */ public function addComment(array $data) { $sql = 'INSERT INTO `comments`' . ' SET' . ' `body` ="' . $this->db->escape($data['body']) . '",' . ' `post_id` ="' . (int) $data['post_id'] . '",' . ' `parent_id` ="' . (int) $data['parent_id'] . '",' . ' `level` ="' . (int) $data['level'] . '",' . ' `user_id` ="' . (int) $data['user_id'] . '"'; $this->db->query($sql); return $this->db->getLastId(); } /** * @param array $data */ public function editComment($id, array $data) { $sql = 'UPDATE `comments`' . ' SET' . ' `body` ="' . $this->db->escape($data['body']) . '"' . ' WHERE `id` ="' . (int) $id . '"'; return $this->db->query($sql); } /** * @param $id * * @return mixed */ public function deleteComment($id) { $sql = 'DELETE FROM `comments` WHERE `id`="' . (int) $id . '"'; return $this->db->query($sql); } }
Java
UTF-8
5,181
2.078125
2
[]
no_license
/* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 Untied States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ /******************************************* * PRODUCT OF PT INOVACAO - EST DEPARTMENT * *******************************************/ package android.gov.nist.javax.sip.parser.ims; import android.gov.nist.core.Token; import android.gov.nist.javax.sip.header.SIPHeader; import android.gov.nist.javax.sip.header.ims.PVisitedNetworkID; import android.gov.nist.javax.sip.header.ims.PVisitedNetworkIDList; import android.gov.nist.javax.sip.parser.Lexer; import android.gov.nist.javax.sip.parser.ParametersParser; import android.gov.nist.javax.sip.parser.TokenTypes; import java.text.ParseException; /** * P-Visited-Network-ID header parser. * * <pre> * P-Visited-Network-ID = "P-Visited-Network-ID" HCOLON * vnetwork-spec * *(COMMA vnetwork-spec) * vnetwork-spec = (token / quoted-string) * *(SEMI vnetwork-param) * vnetwork-param = generic-param * </pre> * * @author ALEXANDRE MIGUEL SILVA SANTOS */ /* */ public class PVisitedNetworkIDParser extends ParametersParser implements TokenTypes { /** * Constructor */ public PVisitedNetworkIDParser(String networkID) { super(networkID); } protected PVisitedNetworkIDParser(Lexer lexer) { super(lexer); } public SIPHeader parse() throws ParseException { PVisitedNetworkIDList visitedNetworkIDList = new PVisitedNetworkIDList(); if (debug) dbg_enter("VisitedNetworkIDParser.parse"); try { this.lexer.match(TokenTypes.P_VISITED_NETWORK_ID); this.lexer.SPorHT(); this.lexer.match(':'); this.lexer.SPorHT(); while (true) { PVisitedNetworkID visitedNetworkID = new PVisitedNetworkID(); if (this.lexer.lookAhead(0) == '\"') parseQuotedString(visitedNetworkID); else parseToken(visitedNetworkID); visitedNetworkIDList.add(visitedNetworkID); this.lexer.SPorHT(); char la = lexer.lookAhead(0); if (la == ',') { this.lexer.match(','); this.lexer.SPorHT(); } else if (la == '\n') break; else throw createParseException("unexpected char = " + la); } return visitedNetworkIDList; } finally { if (debug) dbg_leave("VisitedNetworkIDParser.parse"); } } protected void parseQuotedString(PVisitedNetworkID visitedNetworkID) throws ParseException { if (debug) dbg_enter("parseQuotedString"); try { StringBuilder retval = new StringBuilder(); if (this.lexer.lookAhead(0) != '\"') throw createParseException("unexpected char"); this.lexer.consume(1); while (true) { char next = this.lexer.getNextChar(); if (next == '\"') { // Got to the terminating quote. break; } else if (next == '\0') { throw new ParseException("unexpected EOL", 1); } else if (next == '\\') { retval.append(next); next = this.lexer.getNextChar(); retval.append(next); } else { retval.append(next); } } visitedNetworkID.setVisitedNetworkID(retval.toString()); super.parse(visitedNetworkID); }finally { if (debug) dbg_leave("parseQuotedString.parse"); } } protected void parseToken(PVisitedNetworkID visitedNetworkID) throws ParseException { // issued by Miguel Freitas lexer.match(TokenTypes.ID); Token token = lexer.getNextToken(); //String value = token.getTokenValue(); visitedNetworkID.setVisitedNetworkID(token); super.parse(visitedNetworkID); } }
Markdown
UTF-8
2,748
3.71875
4
[ "MIT" ]
permissive
### [Maximum Score from Performing Multiplication Operations](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations) <p>You are given two <strong>0-indexed</strong> integer arrays <code>nums</code> and <code>multipliers</code><strong> </strong>of size <code>n</code> and <code>m</code> respectively, where <code>n &gt;= m</code>.</p> <p>You begin with a score of <code>0</code>. You want to perform <strong>exactly</strong> <code>m</code> operations. On the <code>i<sup>th</sup></code> operation (<strong>0-indexed</strong>) you will:</p> <ul> <li>Choose one integer <code>x</code> from <strong>either the start or the end </strong>of the array <code>nums</code>.</li> <li>Add <code>multipliers[i] * x</code> to your score. <ul> <li>Note that <code>multipliers[0]</code> corresponds to the first operation, <code>multipliers[1]</code> to the second operation, and so on.</li> </ul> </li> <li>Remove <code>x</code> from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> score after performing </em><code>m</code> <em>operations.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], multipliers = [3,2,1] <strong>Output:</strong> 14 <strong>Explanation:</strong>&nbsp;An optimal solution is as follows: - Choose from the end, [1,2,<strong><u>3</u></strong>], adding 3 * 3 = 9 to the score. - Choose from the end, [1,<strong><u>2</u></strong>], adding 2 * 2 = 4 to the score. - Choose from the end, [<strong><u>1</u></strong>], adding 1 * 1 = 1 to the score. The total score is 9 + 4 + 1 = 14.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6] <strong>Output:</strong> 102 <strong>Explanation: </strong>An optimal solution is as follows: - Choose from the start, [<u><strong>-5</strong></u>,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score. - Choose from the start, [<strong><u>-3</u></strong>,-3,-2,7,1], adding -3 * -5 = 15 to the score. - Choose from the start, [<strong><u>-3</u></strong>,-2,7,1], adding -3 * 3 = -9 to the score. - Choose from the end, [-2,7,<strong><u>1</u></strong>], adding 1 * 4 = 4 to the score. - Choose from the end, [-2,<strong><u>7</u></strong>], adding 7 * 6 = 42 to the score. The total score is 50 + 15 - 9 + 4 + 42 = 102. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == multipliers.length</code></li> <li><code>1 &lt;= m &lt;= 300</code></li> <li><code>m &lt;= n &lt;= 10<sup>5</sup></code><code> </code></li> <li><code>-1000 &lt;= nums[i], multipliers[i] &lt;= 1000</code></li> </ul>
C++
UTF-8
7,233
3.515625
4
[]
no_license
#include "matrix.h" /**< ****************************************************/ /**< C-tors & D-tors */ Matrix::Matrix(const Matrix& matr) { *this = matr; } Matrix::Matrix(size_t rows, size_t cols) { //ctor this->matr = std::vector<std::vector<double>>(rows, std::vector<double>(cols)); } Matrix::Matrix(double** matr, size_t rows, size_t cols) { //here you can assign a matrix from matr this->matr = std::vector<std::vector<double>>(rows, std::vector<double>(cols)); for (size_t i = 0; i < this->rows(); ++i) for (size_t j = 0; j < this->cols(); ++j) this->matr[i][j] = matr[i][j]; } Matrix::Matrix(const std::vector<std::vector<double>>& matr) { this->matr = matr; } Matrix::~Matrix(){} /**< Getters for special info about matrix */ size_t Matrix::rows() const { return this->matr.size(); } size_t Matrix::cols() const { return this->matr.front().size(); } /**< Operators */ std::vector<double>& Matrix::operator [](const int index) { return this->matr[index]; } std::vector<double> Matrix::operator [](const int index) const { return this->matr[index]; } bool operator ==(const Matrix& left, const Matrix& right) { if (left.rows() != right.rows() || left.cols() != right.cols()) return false; for (size_t i = 0; i < left.rows(); ++i) if (left[i] != right[i]) return false; return true; } Matrix& Matrix::operator =(const Matrix& right) { if (this == &right) return *this; this->matr = right.matr; return *this; } Matrix& Matrix::operator =(const std::vector<std::vector<double>> &right) { this->matr = right; return *this; } Matrix operator +(const Matrix& left, const Matrix& right) { if (left.rows() != right.rows() || left.cols() != right.cols()) throw IncorrectMatrixAdditionException(); Matrix r(left.rows(), left.cols()); for (size_t i = 0; i < left.rows(); ++i) for (size_t j = 0; j < left.cols(); ++j) r[i][j] = left.matr[i][j] + right.matr[i][j]; Matrix::_correct_negative_zeros(r); return r; } Matrix& Matrix::operator +=(const Matrix& right) { *this = *this + right; return *this; } Matrix operator -(const Matrix& left, const Matrix& right) { return left + (-1*right); } Matrix& Matrix::operator-=(const Matrix& right) { *this = *this - right; return *this; } Matrix operator *(const double& left, const Matrix &right) { Matrix r(right.rows(), right.cols()); for (size_t i = 0; i < right.rows(); ++i) for (size_t j = 0; j < right.cols(); ++j) r[i][j] = right.matr[i][j] * left; Matrix::_correct_negative_zeros(r); return r; } Matrix operator *(const Matrix &left, const int& right) { Matrix r(left.rows(), left.cols()); r = right * left; return r; } Matrix& Matrix::operator *=(const int& right) { *this = *this * right; return *this; } Matrix operator *(const Matrix& left, const Matrix &right) { if (left.cols() != right.rows()) throw IncorrectMatrixMultiplicationException(); Matrix r(left.rows(), right.cols()); for (size_t i = 0; i < left.rows(); ++i) for (size_t j = 0; j < right.cols(); ++j) for (size_t k = 0; k < left.cols(); ++k) r[i][j] += left.matr[i][k] * right.matr[k][j]; Matrix::_correct_negative_zeros(r); return r; } Matrix& Matrix::operator *= (const Matrix& right) { *this = *this * right; return *this; } //advance this operator with printing width (printf) std::ostream& operator <<(std::ostream& os, const Matrix& matrix) { for (size_t i = 0; i < matrix.rows(); ++i) { for (size_t j = 0; j < matrix.cols(); ++j) os << matrix[i][j] << " "; os << "\n"; } return os; } /**< Operations */ double Matrix::det() { if (this->rows() != this->cols()) throw NotSquareMatrixException(); return _det(*this); } double Matrix::_det(Matrix m) { if (m.cols() == 1) return m[0][0]; if (m.cols() == 2) return m[0][0] * m[1][1] - m[0][1] * m[1][0]; double r(0); for (size_t i = 0; i < m.cols(); ++i) { Matrix temp(m.rows() - 1, m.cols() - 1); for (size_t j = 1; j < m.rows(); ++j) { bool x = 0; for (size_t k = 0; k < m.cols(); ++k) { if (k == i) { x = 1; continue; } temp[j - 1][k - x] = m[j][k]; } } r += (((i + 1) % 2) ? double(1) : double(-1)) * m[0][i] * _det(temp); } return r; } void Matrix::_correct_negative_zeros(Matrix &m) { for (size_t i = 0; i < m.rows(); ++i) for (size_t j = 0; j < m.cols(); ++j) if (m[i][j] == 0) m[i][j] = 0; } Matrix Matrix::transpose() { std::vector<std::vector<double>> ans(this->cols(), std::vector<double>(this->rows())); for (size_t i = 0; i < this->rows(); ++i) for (size_t j = 0; j < this->cols(); ++j) ans[i][j] = matr[j][i]; return Matrix(ans); } double Matrix::minor(size_t row, size_t col) { if (this->rows() != this->cols()) throw NotSquareMatrixException(); Matrix temp(this->rows() - 1, this->cols() - 1); bool passed_row = false; for (size_t i = 0; i < temp.rows(); ++i) { passed_row |= (i == row); bool passed_col = false; for (size_t j = 0; j < temp.cols(); ++j) { passed_col |= (j == col); temp[i][j] = this->matr[i + passed_row][j + passed_col]; } } return temp.det(); } Matrix Matrix::minor_matrix() { Matrix ans(this->rows(), this->cols()); for (size_t i = 0; i < this->rows(); ++i) for (size_t j = 0; j < this->cols(); ++j) ans[i][j] = this->minor(i, j); return ans; } double Matrix::cofactor(size_t row, size_t col) { return (((row + col + 2) % 2 == 0) ? (this->minor(row, col)) : (-this->minor(row, col))); } Matrix Matrix::cofactor_matrix() { Matrix ans(this->rows(), this->cols()); for (size_t i = 0; i < this->rows(); ++i) for (size_t j = 0; j < this->cols(); ++j) ans[i][j] = this->cofactor(i, j); return ans; } Matrix Matrix::inverse() { double det = this->det(); if (det == 0) throw NullDeterminantException(); return (1.0 / det) * this->cofactor_matrix().transpose(); } Matrix Matrix::E(size_t size) { Matrix ans(size, size); for (size_t i = 0; i < size; ++i) ans[i][i] = 1; return ans; } /* EXCEPTION CLASSES MESSAGES ***************/ const char* NotSquareMatrixException::what() const throw() { return "The operation cannot be applied to not-square matrix."; } const char* NullDeterminantException::what() const throw() { return "The operation cannot be applied to matrix because it's determinant equals zero."; } const char* IncorrectMatrixMultiplicationException::what() const throw() { return "Matrices sizes doesn't match: impossible to multiply."; } const char* IncorrectMatrixAdditionException::what() const throw() { return "Matrices sizes doesn't match: impossible to add."; }
JavaScript
UTF-8
1,209
3.359375
3
[]
no_license
//songs array var songs = []; songs[songs.length] = "Legs > by Z*ZTop on the album Eliminator"; songs[songs.length] = "The Logical Song > by Supertr@amp on the album Breakfast in America"; songs[songs.length] = "Another Brick in the Wall > by Pink Floyd on the album The Wall"; songs[songs.length] = "Welco(me to the Jungle > by Guns & Roses on the album Appetite for Destruction"; songs[songs.length] = "Ironi!c > by Alanis Moris*ette on the album Jagged Little Pill"; //add one song to beginning and end songs.unshift("Frances the Mute > by The Mars Volta on the album Frances the Mute"); songs.push("Cloud Zero > by Porcupine Tree on the album Up the Downstair"); // Loop over the array and remove any words or characters that obviously don't belong. // Students must find and replace the > character in each item with a - character. //Must add each string to the DOM in index.html in the main content area. var songsList = document.getElementById("songs"); for (var i = 0; i < songs.length; i++) { var song = songs[i]; song = song.replace(/[@\*\(\!]/g, ""); song = song.replace(/>/g, "-"); var newH3 = document.createElement("h3"); newH3.innerHTML = song; songsList.appendChild(newH3); }
Python
UTF-8
647
3.0625
3
[]
no_license
## ## FractalImaging.py ## Apply fractal to image ## Michael Menz ## from numpy import array, sin, cos, zeros, absolute, amax, isnan, pi from scipy.misc import imread, imsave from PIL import Image im_path = '/Users/menz/Desktop/Screenshots/waldos.png' image_array = imread(im_path, 1) real = sin(image_array/255 * pi - pi/2) imag = cos(image_array/255 * pi) complex_array = real + imag*complex(0,1) expand_array = zeros(complex_array.shape) for x in range(100): complex_array = complex_array**2 + complex(0, 0.1) ask_array = isnan(complex_array) expand_array += ask_array im = Image.fromarray(expand_array) im.save('test.gif')
Shell
UTF-8
5,323
4.15625
4
[]
no_license
#!/usr/bin/env bash set -eu -o pipefail : <<DESC Validate the format of a commit message DESC : <<HELP One can specify the git config value ${c_value}hooks.format.long-line-regex${c_reset} to provide a regex for lines to be omitted from the message body line-length check. HELP # Get our useful functions (be sure to provide lib path as source argument) # shellcheck source=included/lib/core.sh . "$(dirname "${BASH_SOURCE[@]}")/../../lib/core.sh" "$(dirname "${BASH_SOURCE[@]}")/../../lib" commit_msg="$1" # Lets just send all output to stderr exec >&2 if [[ -f $(git rev-parse --git-dir)/MERGE_HEAD ]]; then # This is a merge commit, don't enforce rules exit fi if [[ "$(sed -e '/^#.*/d' -e '/^$/d' "$commit_msg" | wc -l)" -eq 0 ]]; then # Allow git commit to abort normally on an empty commit message exit fi # Save the msg in case our commit fails and we want to preload it next time # in a prepare-commit-msg hook.. cat "$commit_msg" >"$(get_cached_commit_message_filename)" # Sentinel value set to false if any checks fail. This allows us to get output # from multiple failed checks. success=true # Remove comments and leading newlines sed -i.bckp -e 's/^#.*//' -e '/./,$!d' "$commit_msg"; rm -f "${commit_msg}.bckp" # Remove duplicate newlines # TODO: this actually removes all duplicate lines which is possibly dangerous # shellcheck disable=SC2094 { rm "$commit_msg"; uniq >"$commit_msg"; } <"$commit_msg" subject=$(head -n 1 "$commit_msg") # Check that subject message exists case "$subject" in "") printf "${c_error}%s${c_reset}\\n" "Must provide commit message subject" printf "${c_error}%s${c_reset}\\n" "========================================================================" printf "${c_error}%s${c_reset}\\n" "$subject" printf "${c_error}%s${c_reset}\\n\\n" "========================================================================" success=false ;; *) # Check subject line capitalization case "${subject:0:1}" in [[:upper:]]) ;; *) printf "${c_error}%s${c_reset}\\n" "Commit message subject must begin with a capitalized letter" printf "${c_error}%s${c_reset}\\n" "========================================================================" printf "${c_error}%s${c_reset}%s\\n" "${subject:0:1}" "${subject:1:${#subject}}" printf "${c_error}%s${c_reset}\\n\\n" "========================================================================" success=false ;; esac # Check subject line length subject_len=80 if [[ "${#subject}" -gt "${subject_len}" ]]; then printf "${c_error}%s${c_reset}\\n" "Commit message subject must be no longer than ${subject_len} characters" printf "${c_error}%s${c_reset}\\n" "========================================================================" printf "%s${c_error}%s${c_reset}\\n" "${subject:0:${subject_len}}" "${subject:${subject_len}:${#subject}}" printf "${c_error}%s${c_reset}\\n\\n" "========================================================================" success=false fi # Check subject line for trailing period case ${subject: -1} in \.) printf "${c_error}%s${c_reset}\\n" "Commit message subject must not end with a period" printf "${c_error}%s${c_reset}\\n" "========================================================================" printf "%s${c_error}%s${c_reset}\\n" "${subject:0:-1}" "${subject: -1}" printf "${c_error}%s${c_reset}\\n\\n" "========================================================================" success=false ;; esac # Check for blank line after subject if [[ "$(wc -l <"$commit_msg")" -gt 1 ]] && [[ -n "$(head -n +2 "$commit_msg" | tail -n 1)" ]]; then printf "${c_error}%s${c_reset}\\n" "Commit message must have a blank line after the subject" printf "${c_error}%s${c_reset}\\n" "========================================================================" printf "${c_reset}%s${c_reset}\\n" "$subject" printf "${c_error}%s${c_reset}\\n" "$(head -n +2 "$commit_msg" | tail -n 1)" printf "${c_error}%s${c_reset}\\n\\n" "========================================================================" success=false fi ;; esac # Check message body line length message_line_len=100 long_line_regex="$(git config --get hooks.format.long-line-regex)" ||: if [[ $(grep -vE "${long_line_regex:-^\$}" "$commit_msg" | awk '{print length}' | sort -nr | head -n 1) -gt "$message_line_len" ]]; then printf "${c_error}%s${c_reset}\\n" "Commit message contains lines longer than $message_line_len characters" printf "${c_error}%s${c_reset}\\n" "========================================================================" while read -r line; do printf "%s${c_error}%s${c_reset}\\n" "${line:0:${message_line_len}}" "${line:${message_line_len}:${#line}}" done < "$commit_msg" printf "${c_error}%s${c_reset}\\n\\n" "========================================================================" success=false fi $success
Swift
UTF-8
1,858
2.546875
3
[]
no_license
// // PageVC.swift // OverPowered // // Created by Bright Future on 22/07/2017. // Copyright © 2017 Bright Future. All rights reserved. // import UIKit class PageVC: UIPageViewController, UIPageViewControllerDataSource { var viewModel: ConversationViewModel! lazy var viewControllersToAdd: [UIViewController] = { let storyboard = UIStoryboard(name: "Main", bundle: nil) let conversationVC = storyboard.instantiateViewController(withIdentifier: "ConversationVC") let resultVC = storyboard.instantiateViewController(withIdentifier: "ResultVC") let helpVC = storyboard.instantiateViewController(withIdentifier: "HelpVC") return [conversationVC, resultVC, helpVC] }() override func viewDidLoad() { super.viewDidLoad() dataSource = self setViewControllers([viewControllersToAdd[0]], direction: .forward, animated: false, completion: nil) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let currentIndex = viewControllersToAdd.index(of: viewController) let previousIndex = currentIndex! - 1 if previousIndex >= 0 { return viewControllersToAdd[previousIndex] } else { return nil } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = viewControllersToAdd.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 if nextIndex <= 2 { return viewControllersToAdd[nextIndex] } else { return nil } } }
Python
UTF-8
2,184
3.390625
3
[]
no_license
# Package: model.game # Description: structure of board # Artificial Intelligence, II Semester 2018 # Project: Connect 4 # Author : Jonathan Martinez C. # E-mail: jonathan.gerad@hotmail.com # Version: 0.0.0 # IMPORT SECTION import argparse from model.game.agent import Agent from model.game.human import Human from model.game.player import Player from model.game.game import Game class Game_Controller(): def __init__(self): self.player_1 = Player() self.player_2 = Player() # Methods------------------------- # @Method: CONFIG_PLAYERS # @Description: def config_players(self): parser = argparse.ArgumentParser(description='Configuración del ' + 'Juego.') parser.add_argument("-gt", "--game-type", type=int, help="Define el tipo de juego. ") parser.add_argument("-a1c", "--agent1c",type=str, help="Características del agente 1") parser.add_argument("-a2c", "--agent2c",type=str, help="Características del agente 2") parser.add_argument("-p1c", "--agentec", type=str, help="Características del agente") args = parser.parse_args() # 0 -> H vs A, 1 -> A vs A # player 2 symbol = 2, and oponent = 1 self.player_2 = Agent(2,1) if(args.game_type == 0): self.player_2.set_strategies(eval(args.agentec)) self.player_1 = Human() else: self.player_2.set_strategies(eval(args.agent1c)) self.player_1 = Agent(1,2) self.player_1.set_strategies(eval(args.agent2c)) # Methods------------------------- # @Method: GET_CONFIG_PLAYERS # @Description: Return the players, and the game type def get_config_players(self): if(isinstance(self.player_1, Human)): return [self.player_1, self.player_2, 0] else: return [self.player_1, self.player_2, 1] def play_game(self): players = self.get_config_players() self.game = Game(players[0],players[1]) self.game.play_game()
Markdown
UTF-8
282
2.9375
3
[]
no_license
#### PYTHON EXERCISES #### - [Coma Code](lists/comma_code.py): given a list, returns a string with all items separated by ', ' and ' and ' before the last item. > Example: 'me, myself, irene' returns 'me, myself and irene' - [Tic-Tac-Toe](dict/tic-tactoe.py): Tic-Tac-Toe game
Java
UTF-8
144
1.6875
2
[]
no_license
package aqa.core.lesson10.lpylypenko; public class InvalidAgeException extends RuntimeException { public InvalidAgeException () { } }
Python
UTF-8
793
2.921875
3
[]
no_license
from typing import Dict from pydantic import BaseModel class UsuarioInDB(BaseModel): nombre: str # usuarioInDB.nombre = "diego" mejorpuntaje: int ultimopuntaje: int database_usuarios = Dict[str, UsuarioInDB] # {"nombre": "diego", } database_usuarios = {"Diego": UsuarioInDB(**{"nombre":"Diego", "mejorpuntaje":1000, "ultimopuntaje":10}), "Felix": UsuarioInDB(**{"nombre":"Felix", "mejorpuntaje":30, "ultimopuntaje":30})} def get_usuario(nombre: str): if nombre in database_usuarios.keys(): return database_usuarios[nombre] else: return None def update_usuario(usuario_in_db: UsuarioInDB): database_usuarios[usuario_in_db.nombre] = usuario_in_db return usuario_in_db
C++
UTF-8
737
2.96875
3
[]
no_license
// Source: https://leetcode.com/problems/find-and-replace-in-string/ // Author: Miao Zhang // Date: 2021-03-16 class Solution { public: string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) { vector<pair<int, int>> idx; for (int i = 0; i < indexes.size(); i++) { idx.emplace_back(indexes[i], i); } sort(idx.rbegin(), idx.rend()); for (auto id: idx) { int i = id.first; string s = sources[id.second]; string t = targets[id.second]; if (S.substr(i, s.size()) == s) { S = S.substr(0, i) + t + S.substr(i + s.size()); } } return S; } };
Java
UTF-8
3,247
2.890625
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 shoppinginthesupermarket; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import shoppinginthesupermarket.specialofferprocessors.SpecialOfferProcessor; import shoppinginthesupermarket.specialoffers.SpecialOffer; /** * * @author oracle */ public class Checkout { private List<SpecialOffer> specialOffers; private List<Item> specialOffersInTrolley; private CheckoutPrinter printer; public Checkout() { this.printer = new CheckoutPrinter(); this.specialOffersInTrolley = new ArrayList<>(); } void setSpecialOffers(List<SpecialOffer> specialOffers) { this.specialOffers = specialOffers; } public List<SpecialOffer> getSpecialOffers() { return specialOffers; } Receipt processTrolley(Trolley trolley) { BigDecimal totalWithoutDiscounts; BigDecimal totalDiscounts; printer.addWelcome(); totalWithoutDiscounts = prepareTotalWithoutDiscountsAndKeepApartSpecialOffers(trolley); totalDiscounts = prepareTotalDiscounts(); BigDecimal total = totalWithoutDiscounts.subtract(totalDiscounts); prepareTotal(total); return printer.getReceipt(); } protected BigDecimal prepareTotalWithoutDiscountsAndKeepApartSpecialOffers(Trolley trolley) { BigDecimal total = new BigDecimal("0"); if (!trolley.getItemsToBuy().isEmpty()) { for (Item item : trolley.getItemsToBuy()) { if (item.hasSpecialOffer()) { specialOffersInTrolley.add(item); } printer.addItemLine(item.getId(), item.getPrice()); total = total.add(item.getPrice()); } } printer.addTotalWithoutDiscounts(total); return total; } protected BigDecimal prepareTotalDiscounts() { BigDecimal totalDiscounts = new BigDecimal("0"); if (specialOffers!=null) { //Apply all the offers from the supermarket in the list for (SpecialOffer supermarketSpecialOffer : specialOffers) { List<Item> listWithSameOffers = new ArrayList<>(); for (Item item : specialOffersInTrolley) { SpecialOffer itemSpecialOfferFromTrolley = item.getSpecialOffer(); if (itemSpecialOfferFromTrolley.isSameTypeOfOfferAs(supermarketSpecialOffer)) { listWithSameOffers.add(item); } } if (!listWithSameOffers.isEmpty()) { SpecialOfferProcessor sop = supermarketSpecialOffer.getSpecialOfferProcessor(); sop.setSpecialOfferList(listWithSameOffers); totalDiscounts = totalDiscounts.add(sop.getTotalDiscount()); } } } printer.addDiscounts(totalDiscounts); return totalDiscounts; } private void prepareTotal(BigDecimal total) { printer.addTotalWithDiscounts(total); } }