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
SQL
UTF-8
1,215
3.015625
3
[]
no_license
-- 用意されているコマンドに関しては大文字を使う INSERT INTO gs_bm_table(company,brandname,items,comment,datetime)VALUES('サツドラ','wellnessnavi',ビタアルト,'低価格で高品質',sysdate()) INSERT INTO gs_bm_table(company,brandname,items,comment,datetime)VALUES('イオン','TOPVALUE',ヨーグルト,'安いけどおいしくない',sysdate()) INSERT INTO gs_bm_table(company,brandname,items,comment,datetime)VALUES('西友','みなさまのお墨付き',牛乳,'新鮮',sysdate()) INSERT INTO gs_bm_table(company,brandname,items,comment,datetime)VALUES('サツドラ','クレアーレ',トイレットペーパー,'コスパ最強&使いやすさ抜群でリピート確定',sysdate()) -- データ取得 SELECT * FROM gs_bm_table SELECT name,brandname FROM gs_bm_table SELECT * FROM gs_bm_table WHERE id=1 SELECT * FROM gs_bm_table WHERE company='サツドラ' SELECT * FROM gs_bm_table WHERE items='ヨーグルト' SELECT * FROM gs_bm_table WHERE id=1 OR id=2 OR id=10 SELECT * FROM gs_bm_table WHERE name LIKE SELECT * FROM gs_bm_table ORDER BY id DESC; --DESC=昇順,ASC=昇順 SELECT * FROM gs_bm_table ORDER BY id DESC LIMIT 3; --上から3
JavaScript
UTF-8
3,879
2.90625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
const geometry = require('../geometry'); describe('geometry', () => { describe('extendPointOnLine', () => { it('returns a point distance away from the end point', () => { const p1 = {x: 0, y: 0}; const p2 = {x: 8, y: 6}; expect(geometry.extendPointOnLine(p1, p2, 5)).toEqual({x: 12, y: 9}); }); it('works with negative distances', () => { const p1 = {x: 0, y: 0}; const p2 = {x: 8, y: 6}; expect(geometry.extendPointOnLine(p1, p2, -5)).toEqual({x: 4, y: 3}); }); it('works when p2 is before p1 in the line', () => { const p1 = {x: 12, y: 9}; const p2 = {x: 8, y: 6}; expect(geometry.extendPointOnLine(p1, p2, 10)).toEqual({x: 0, y: 0}); }); it('works with vertical lines', () => { const p1 = {x: 2, y: 4}; const p2 = {x: 2, y: 6}; expect(geometry.extendPointOnLine(p1, p2, 7)).toEqual({x: 2, y: 13}); }); it('works with vertical lines where p2 is above p1', () => { const p1 = {x: 2, y: 6}; const p2 = {x: 2, y: 4}; expect(geometry.extendPointOnLine(p1, p2, 7)).toEqual({x: 2, y: -3}); }); }); describe('frechetDist', () => { it('is 0 if the curves are the same', () => { const curve1 = [{x: 0, y: 0}, {x: 4, y: 4}]; const curve2 = [{x: 0, y: 0}, {x: 4, y: 4}]; expect(geometry.frechetDist(curve1, curve2)).toBe(0); expect(geometry.frechetDist(curve2, curve1)).toBe(0); }); it('less than then max length of any segment if curves are identical', () => { const { subdivideCurve, frechetDist } = geometry; const curve1 = [{x: 0, y: 0}, {x: 2, y: 2}, {x: 4, y: 4}]; const curve2 = [{x: 0, y: 0}, {x: 4, y: 4}]; expect(frechetDist(subdivideCurve(curve1, 0.5), subdivideCurve(curve2, 0.5))).toBeLessThan(0.5); expect(frechetDist(subdivideCurve(curve1, 0.1), subdivideCurve(curve2, 0.1))).toBeLessThan(0.1); expect(frechetDist(subdivideCurve(curve1, 0.01), subdivideCurve(curve2, 0.01))).toBeLessThan(0.01); }); it('will be the dist of the starting points if those are the only difference', () => { const curve1 = [{x: 1, y: 0}, {x: 4, y: 4}]; const curve2 = [{x: 0, y: 0}, {x: 4, y: 4}]; expect(geometry.frechetDist(curve1, curve2)).toBe(1); expect(geometry.frechetDist(curve2, curve1)).toBe(1); }); }); describe('subdivideCurve', () => { it('leave the curve the same if segment lengths are less than maxLen apart', () => { const curve = [{x: 0, y: 0}, {x: 4, y: 4}]; expect(geometry.subdivideCurve(curve, 10)).toEqual([{x: 0, y: 0}, {x: 4, y: 4}]); }); it('breaks up segments so that each segment is less than maxLen length', () => { const curve = [{x: 0, y: 0}, {x: 4, y: 4}, {x: 0, y: 8}]; expect(geometry.subdivideCurve(curve, Math.sqrt(2))).toEqual([ {x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2}, {x: 3, y: 3}, {x: 4, y: 4}, {x: 3, y: 5}, {x: 2, y: 6}, {x: 1, y: 7}, {x: 0, y: 8}, ]); }); }); describe('filterParallelPoints', () => { it('removes internal points that are on the line connecting the points on either side', () => { const points = [ {x: 0, y: 0}, {x: 5, y: 0}, {x: 6, y: 0}, {x: 7, y: 1}, {x: 8, y: 2}, {x: 9, y: 3}, {x: 10, y: 3}, {x: 11, y: 3}, ]; expect(geometry.filterParallelPoints(points)).toEqual([ {x: 0, y: 0}, {x: 6, y: 0}, {x: 9, y: 3}, {x: 11, y: 3}, ]); }); it('returns the original points if there are no parallel points', () => { const points = [ {x: 0, y: 0}, {x: 6, y: 0}, {x: 9, y: 3}, {x: 11, y: 3}, ]; expect(geometry.filterParallelPoints(points)).toEqual(points); }); }); });
C++
UTF-8
1,816
3.375
3
[]
no_license
/* * File: CrazyRandomSword.cpp * Author: Vivian Nguyen <vsn17@my.fsu.edu> * * Created on January 29, 2019, 10:15 PM */ #include "CrazyRandomSword.h" #include <cstdlib> #include <ctime> #include <iostream> using namespace std; CrazyRandomSword::CrazyRandomSword() : Weapon("Crazy Random Sword", 0.0) { srand( time(0) ); hitPoints = rand() % 94 + 7; // Initializing hitPoints with a random integer from 7 to 100. } double CrazyRandomSword::hit(double armor) { double origHitPoints = hitPoints; // Making a copy of the original hitPoints value (used in this function) hitPoints = rand() % 94 + 7; // Changing the value of hitPoints for when this function is called again next time if (armor < 6) // Note that armor must be at least 6 because CRS ignores a random { // integer from 2 to armor/3. So, this range assumes armor is at least 9 (in order to have return origHitPoints; // (...) a range from at least 2-3. These two if-statements are checks to } // (...) include what happens if armor < 9. if (armor >= 6 && armor <= 8) return (origHitPoints - (armor-2)); // Why this if statement? See definition of variables armorMax and damageIgnored in below lines. // In damageIgnored's definition, it uses rand() % armorMax, so armorMax cannot be 0 or else // get an error. So, if armor is 6,7,or 8, it results in armorMax being 0. // This if-statement avoids that happening. int armorMax = armor/3 - 2; // Subtract 2 because we will add 2 when using rand() to get range beginning at 2. int damageIgnored = rand() % armorMax + 2; double damage = origHitPoints - (armor - damageIgnored); if (damage < 0) return 0; return damage; }
Ruby
UTF-8
188
3.03125
3
[]
no_license
N = gets.to_i count = 0 (1..N).each do |num| if num.odd? ds = [] (1..num).each do |i| ds << i if num % i == 0 end count += 1 if ds.length == 8 end end puts count
JavaScript
UTF-8
1,164
2.640625
3
[]
no_license
const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ejs = require("ejs"); const app = express(); app.use( bodyParser.urlencoded({extended : true})); app.set('view engine','ejs'); app.use(express.static("public")); app.get("/",function(req,res){ res.render("home"); }); app.post("/",function(req,res){ const cityname = req.body.cityName ; const url = "https://api.openweathermap.org/data/2.5/weather?appid=20bfd35ac5ff82780167e76421e14105&units=imperial&q="+ cityname; https.get(url,function(response){ response.on("data",function(data){ const weatherData = JSON.parse(data); const temp = ((5/9)*(weatherData.main.temp-32)).toFixed(2); const s = (weatherData.weather[0].description); const weatherInfo= s[0].toUpperCase() + s.slice(1); const icon = weatherData.weather[0].icon; const iconurl = "http://openweathermap.org/img/wn/"+ icon +"@2x.png"; res.render("city",{temperature:temp,icon :iconurl,climate:weatherInfo}); }); }) }); app.listen(3000,function(){ console.log("Server is running"); });
Java
IBM852
535
3.859375
4
[]
no_license
import java.util.Scanner; public class P04_LaMultiplication { public static void main(String[] args) { // ferme le lecteur Scanner in = new Scanner(System.in); // lit les nombres. System.out.printf("Enter first number: "); int num1 = in.nextInt(); System.out.printf("Enter second number: "); int num2 = in.nextInt(); // a fait le calcul int result = num1 * num2; // affiche le resultat System.out.println("result is = " + result); // ferme le lecteur in.close(); } }
Java
UTF-8
825
2.03125
2
[]
no_license
package taskmodels; import com.example.nicol.joynus.RegisterActivity; import dtomodels.userDTO.RegisterFormDTO; public class RegisterUserPackage { private RegisterFormDTO formToSend; private int responseCode; private RegisterActivity sender; public RegisterUserPackage() { } public RegisterFormDTO getFormToSend() { return formToSend; } public void setFormToSend(RegisterFormDTO formToSend) { this.formToSend = formToSend; } public int getResponseCode() { return responseCode; } public void setResponseCode(int responseCode) { this.responseCode = responseCode; } public RegisterActivity getSender() { return sender; } public void setSender(RegisterActivity sender) { this.sender = sender; } }
C++
UTF-8
1,357
3.40625
3
[]
no_license
#include <iostream> #include <list> #include <vector> using namespace std; class Solution { public: int searchInsert(vector<int>& nums, int target) { int index = 0, begin = 0, end = nums.size(); index = (begin + end) / 2; while (end > begin+1) { if (target > nums[end-1]) { return end; } else if (target < nums[begin]) { return begin; } else { if (target < nums[index]) { end = index; } else if (target == nums[index]) { return index; } else { begin = index; } index = (begin + end) / 2; } } if (begin != end) { if (target > nums[begin]) index = begin+1; else if (target == nums[begin]) index = begin; else index = begin; } return index; } }; int main() { Solution s; vector<int> v1; int i = 0; int t1 = 5, t2 = 2, t3 = 7,t4 = 0; v1.push_back(1); v1.push_back(3); v1.push_back(5); v1.push_back(6); cout << "Input:["; for (i = 0; i < v1.size() - 1; i++) { cout << v1[i] << ","; } cout << v1[v1.size() - 1] << "]," << endl; cout << "Output:" << t1<<"->"<< s.searchInsert (v1, t1)<< endl; cout << "Output:" << t2 << "->" << s.searchInsert(v1, t2) << endl; cout << "Output:" << t3 << "->" << s.searchInsert(v1, t3) << endl; cout << "Output:" << t4 << "->" << s.searchInsert(v1, t4) << endl; system("pause"); }
PHP
UTF-8
21,956
2.640625
3
[]
no_license
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Allow to access/update/delete job's informations from database * * @author Hermannovich <donfack.hermann@gmail.com> */ class Jobs_model extends CI_Model { public function __construct() { parent::__construct(); } public function create( $data ){ if ($this->db->insert('jobs', $data)){ return $this->db->insert_id(); } return null; } public function link_to_skills( $job_id, $skills ) { if( !empty($skills) && is_array($skills) ) { foreach ($skills as $key => $value) { $this->db->insert('job_skills',array( 'job_id' => $job_id, 'skill_name' => $value )); } } } public function get_type( $job_id ){ $this->db ->select('job_type') ->from('jobs') ->where('jobs.id', $job_id); $query = $this->db->get(); return $query->row(); } public function load_offer($job_id, $bid_id){ $fields = array( 'jobs.*', 'jobs.user_id as client_id', 'job_bids.*', 'job_bids.status as bid_status', 'jobs.job_duration as jobduration', 'job_bids.id as bid_id', 'job_bids.created as bid_created' ); $query = $this->db->select($fields) ->join('job_bids', 'jobs.id=job_bids.job_id', 'inner') ->where('job_bids.id', $bid_id) ->where('job_bids.job_id', $job_id) // ->where('job_bids.hired', '1') // ->where('job_bids.job_progres_status','2') ->where('job_bids.status', 0) ->get('jobs'); return $query->row(); } public function load_job_status($sender_id, $user_id, $job_id, $with_country = false) { $this->db->select('*, job_bids.created AS bid_created, job_bids.id as bid_id, jobs.status AS job_status,jobs.job_duration AS jobduration,jobs.created AS job_created, webuser.cropped_image, job_bids.status as bid_status'); $this->db->from('job_accepted'); $this->db->join('job_bids', 'job_bids.id=job_accepted.bid_id', 'inner'); if($sender_id !== null){ $this->db->join('webuser', 'webuser.webuser_id=job_accepted.fuser_id', 'inner'); }else{ $this->db->join('webuser', 'webuser.webuser_id=job_accepted.buser_id', 'inner'); } $this->db->join('webuser_basic_profile', 'webuser_basic_profile.webuser_id=webuser.webuser_id', 'inner'); $this->db->join('jobs', 'jobs.id=job_bids.job_id', 'inner'); if($with_country) $this->db->join('country', 'country.country_id=webuser.webuser_country', 'inner'); if($sender_id !== null){ $this->db->where('job_accepted.buser_id', $sender_id); $this->db->where('job_accepted.fuser_id', $user_id); }else{ $this->db->where('job_accepted.fuser_id', $user_id); } $this->db->where('job_accepted.job_id', $job_id); $query = $this->db->get(); return $query->row(); } /** * Count the number of hired freelance by an employer. * * @return int $nb_hired */ public function number_freelancer_hired($employer_id){ if(empty($employer_id) || !is_numeric($employer_id)) return null; $this->db->select('COUNT(*) as nb_freelancer_hired'); $this->db->from('job_accepted'); $this->db->join('webuser', 'webuser.webuser_id=job_accepted.fuser_id', 'inner'); $this->db->join('job_bids', 'job_bids.id=job_accepted.bid_id', 'inner'); $this->db->join('jobs', 'jobs.id=job_bids.job_id', 'inner'); $this->db->join('country', 'country.country_id=webuser.webuser_country', 'inner'); $this->db->where('job_accepted.buser_id', $employer_id); $this->db->where('job_bids.hired', '0'); $this->db->where('job_bids.jobstatus', '0'); $query = $this->db->get(); $result = $query->result(); if( ! empty( $result ) ) return $result[0]->nb_freelancer_hired; return 0; } public function load_all_jobs_freelancer_hired( $employer_id ){ if(empty($employer_id) || !is_numeric($employer_id)) return null; $this->db->select('*, job_bids.status as bid_status'); $this->db->from('job_accepted'); $this->db->join('webuser', 'webuser.webuser_id=job_accepted.fuser_id', 'inner'); $this->db->join('job_bids', 'job_bids.id=job_accepted.bid_id', 'inner'); $this->db->join('jobs', 'jobs.id=job_bids.job_id', 'inner'); $this->db->join('country', 'country.country_id=webuser.webuser_country', 'inner'); $this->db->where('job_accepted.buser_id', $employer_id); $this->db->where('job_bids.hired', '0'); $this->db->where('job_bids.jobstatus', '0'); $this->db->order_by("jobs.job_type", "desc"); $this->db->order_by("job_accepted.created", "desc"); $query = $this->db->get(); $result = $query->result(); return $result; } public function number_offer( $employer_id ){ if(empty($employer_id) || !is_numeric($employer_id)) return null; $this->db->select('COUNT(*) as number_offer'); $this->db->from('job_bids'); $this->db->join('jobs', 'jobs.id=job_bids.job_id', 'inner'); $this->db->where('job_bids.status', 0); $this->db->where('jobs.user_id', $employer_id); $this->db->where('job_bids.hired', 1); //$this->db->group_by('job_bids.bid_id'); $query = $this->db->get(); $result = $query->result(); if( ! empty( $result )) return $result[0]->number_offer; return 0; } public function number_past_hired($employer_id){ if(empty($employer_id) || !is_numeric($employer_id)) return null; $this->db->select('COUNT(*) as nb_pas_hired'); $this->db->from('job_accepted'); $this->db->join('job_bids', 'job_bids.id=job_accepted.bid_id', 'inner'); $this->db->where('job_accepted.buser_id', $employer_id); $this->db->where('job_bids.hired', '0'); $this->db->where('job_bids.jobstatus', '1'); $query = $this->db->get(); $result = $query->result(); if( ! empty( $result )) return $result[0]->nb_pas_hired; return 0; } public function get_all_freelancer_total_hour( $job_ids, $this_week_start = null, $today = null){ if(empty($job_ids)) return array(); $this->db ->select('fuser_id, jobid, SUM(total_hour) as total_hour') ->from('job_workdairy') ->where_in('jobid', $job_ids); if( $this_week_start != null ) $this->db->where('working_date >=', $this_week_start); if( $today != null ) $this->db->where('working_date <=', $today); $this->db->group_by(array('fuser_id', 'jobid')); $query = $this->db->get(); $job_done = $query->result(); $result = array(); if($job_done != null){ foreach($job_done as $job){ $result[$job->jobid][$job->fuser_id] = (int) $job->total_hour; } } return $result; } public function get_final_paid_infos($job_id, $user_id){ $infos = $this->get_each_work_total_hour(array($job_id), $user_id, null, null, true); if(isset($infos[$job_id]) && isset($infos[$job_id][$user_id])) return $infos[$job_id][$user_id]; return array( 'total_hour' => 0, 'amount_by_hour' => null, 'amount' => 0.00 ); } /* Hui added for total hour */ public function get_freelancer_total_hour( $job_id, $user_id ,$this_week_start = null, $today = null){ if(empty($job_id) || empty($user_id)) return array(); $this->db ->select('fuser_id, jobid, SUM(total_hour) as total_hour') ->from('job_workdairy') ->where('jobid =', $job_id) ->where('fuser_id =', $user_id); if( $this_week_start != null ) $this->db->where('working_date >=', $this_week_start); if( $today != null ) $this->db->where('working_date <=', $today); $this->db->group_by(array('fuser_id', 'jobid')); $query = $this->db->get(); $job_done = $query->result(); $result = array(); if($job_done != null){ foreach($job_done as $job){ $result[$job->jobid][$job->fuser_id] = (int) $job->total_hour; } } return $result; } /* end */ public function get_work_total_hour($job_id, $user_id, $begin = null, $end = null){ $result = $this->get_each_work_total_hour(array($job_id), $user_id, $begin, $end); if(isset($result[$job_id]) && isset($result[$job_id][$user_id])) return $result[$job_id][$user_id]; return 0; } public function get_each_work_total_hour( $job_ids, $user_id, $begin = null, $end = null, $with_amount = false ){ $result = array(); if(empty($job_ids)) return $result; $this->db ->select('job_bids.offer_bid_amount, job_bids.bid_amount, job_bids.user_id, job_bids.job_id, SUM(job_workdairy.total_hour) as total_hour') ->from('job_bids') ->join('job_workdairy', 'job_workdairy.jobid=job_bids.job_id', 'inner') ->where('user_id', $user_id) ->where_in('job_id', $job_ids); if( $begin != null ) $this->db->where('working_date >=', $begin); if( $end != null ) $this->db->where('working_date <=', $end); $this->db->group_by(array('job_bids.user_id', 'job_bids.job_id')); $query = $this->db->get(); $job_done = $query->result(); if($job_done != null){ if($with_amount === false){ foreach($job_done as $job){ $result[$job->job_id][$job->user_id] = (int) $job->total_hour; } }else{ foreach($job_done as $job){ $total_hour = (int) $job->total_hour; $amount_by_hour = !empty($job->offer_bid_amount) ? $job->offer_bid_amount : $job->bid_amount; $amount = $total_hour * $amount_by_hour; $result[$job->job_id][$job->user_id] = array( 'total_hour' => $total_hour, 'amount_by_hour' => $amount_by_hour, 'amount' => $amount ); } } } return $result; } public function update_bid_state($bid_id, $state ){ $this->db->where('id', $bid_id); return $this->db->update('job_bids', array( 'status' => $state )); } public function load_bid( $bid_id, $hired = false ){ $this->db ->select('*') ->from('job_bids') ->where('id', $bid_id ); if($hired) $this->db->where('hired', 1); $query = $this->db->get(); return $query->row(); } public function set_feedback_saw( $job_id, $user_id ){ $this->db->where('feedback_userid', $user_id) ->where('feedback_job_id', $job_id) ->where('sender_id !=', $user_id) ->where('haveseen', 1) ->update('job_feedback', array( 'haveseen' => 0 )); } public function get_total_paid( $bid_id, $job_amount = 0.0 ){ $this->db ->select('SUM( fixedpay_amount ) as amount') ->from('job_hire_end') ->where('bid_id', $bid_id); $query = $this->db->get(); $result = $query->result(); if( !empty($result) ) return round( ( $result[0]->amount + $job_amount ), 2); return 0.0; } public function get_feedbacks($job_id, $sender_id, $receiver_id){ $this->db ->select('feedback_score, feedback_comment') ->from('job_feedback') ->where('job_feedback.feedback_job_id', $job_id) ->where('job_feedback.feedback_userid', $receiver_id) ->where('job_feedback.sender_id', $sender_id) ->order_by('job_feedback.feedback_id', "desc") ->limit(1, 0); $query = $this->db->get(); $feedback = $query->row(); if(!empty($feedback)){ $rating = ($feedback->feedback_score/5)*100; $score = $feedback->feedback_score; $comment = $feedback->feedback_comment; return array( 'rating' => $rating, 'score' => $score, 'comment' => $comment ); } return null; } public function update_job($job_id, $data){ return $this->db ->where('id', $job_id) ->update('jobs', $data); } public function load_client_infos( $post_id ) { $query = $this->db->select('webuser.*,jobs.*,jobs.created created') ->join('webuser', 'webuser.webuser_id=jobs.user_id', 'left') ->order_by("jobs.id", "desc") ->get_where('jobs', array('id' => $post_id)); return $query->row(); } public function get_category( $category_id ) { $query = $this->db ->from('job_subcategories') ->where('subcat_id', $category_id) ->get(); $result = $query->row(); $category_name = ''; if( ! empty( $result ) ) $category_name = $result->subcategory_name; return $category_name; } public function get_skills( $job_id ) { $query = $this->db ->select("skill_name") ->from("job_skills") ->where("job_id = ", $job_id ) ->get(); return $query->result_array(); } public function num_sent_by( $client_id ) { $query = $this->db->select('COUNT(*) as num') ->from('jobs') ->where('user_id', $client_id) ->get(); $result = $query->row(); if( ! empty( $result ) ) return $result->num; return 0; } public function load_informations( $job_id ) { $query = $this->db->select('*') ->from('jobs') ->where('jobs.id', $job_id) ->get(); return $query->row(); } public function load_jobs($keyword, $sql, $limit, $offset, $id){ $keywords = ""; if (isset($keyword)) { $keywords = $keyword; } if (isset($sql) && $sql != "" && strlen($sql) >= 1) { if ($this->session->userdata('type') == '2') { $val = array( '1' => '1', 'status' => 1 ); if (strlen($keywords) > 0) { $jobCatPage = true; $this->db->like("jobs.title", $keywords); } else { $this->db->where_in('jobs.category', $sql, FALSE); } $this->db->order_by("jobs.id", "DESC"); $query = $this->db->get_where('jobs', $val, $limit, $offset); } else if ($this->session->userdata('type') == '1') { $val = array( 'user_id' => $id, 'status' => 1 ); $this->db->order_by("jobs.id", "DESC"); $query = $this->db->get_where('jobs', $val, $limit, $offset); } } else { $query = ""; } return $query; } function jobs_by_category($val, $limit, $offset){ $this->db ->join('webuser', 'webuser.webuser_id=jobs.user_id', 'left') ->order_by("jobs.id", "desc"); return $this->db->get_where('jobs', $val, $limit, $offset); } function filter_jobs($jobType, $jobDuration, $jobHours, $category, $sql, $keywords, $limit, $offset, $sort = FALSE){ $val = array( '1' => '1', 'status' => 1 ); if (!empty($jobType)) { $jobType = explode(",", $jobType); foreach ($jobType as $type) { $this->db->where('jobs.job_type', $type); } } if (!empty($jobDuration)) { $jobDuration = explode(",", $jobDuration); foreach ($jobDuration as $duretion) { $this->db->where('jobs.job_duration', $duretion); } } if (!empty($jobHours)) { $jobHours = explode(",", $jobHours); foreach ($jobHours as $hour) { $this->db->where('jobs.hours_per_week', $hour); } } if (empty($category)) { if ($sql != "" && strlen($sql) >= 1) { $this->db->where_in('jobs.category', $sql, FALSE); if (strlen($keywords) > 0) { $this->db->where("jobs.title", $keywords); $this->db->or_like("jobs.job_description", $keywords); } } }else{ if ($sql != "" && strlen($sql) >= 1) { $this->db->where_in('jobs.category', $sql); if (strlen($keywords) > 0) { $this->db->where("jobs.title", $keywords); $this->db->or_like("jobs.job_description", $keywords); } } } if($sort != FALSE){ if($sort == 0){ $this->db->order_by('jobs.job_created', 'ASC'); }else{ $this->db->order_by('jobs.job_created', 'DESC'); } } return $this->db->get_where('jobs', $val, $limit, $offset); } function generate_random_jobs($keywords, $sql, $limit, $offset){ if (isset($sql) && $sql != "" && strlen($sql) >= 1) { $val = array( '1' => '1', 'status' => 1 ); $this->db->select('r.*'); if (strlen($keywords) > 0) { $this->db->like("r.title", $keywords); } else { $this->db->where('(SELECT COUNT(*) FROM jobs r1 WHERE r.category = r1.category AND r.id < r1.id ) <= 1'); $this->db->where_in('r.category', $sql, FALSE); } $this->db->order_by('r.category ASC, RAND()'); return $this->db->get_where('jobs r', $val, $limit, $offset); } } function filter_random_jobs($jobType, $jobDuration, $jobHours, $category, $sql, $keywords, $limit, $offset, $sort = FALSE){ $val = array( '1' => '1', 'status' => 1 ); $this->db->select('r.*'); if (!empty($jobType)) { $jobType = explode(",", $jobType); foreach ($jobType as $type) { $this->db->where('r.job_type', $type); } } if (!empty($jobDuration)) { $jobDuration = explode(",", $jobDuration); foreach ($jobDuration as $duretion) { $this->db->where('r.job_duration', $duretion); } } if (!empty($jobHours)) { $jobHours = explode(",", $jobHours); foreach ($jobHours as $hour) { $this->db->where('r.hours_per_week', $hour); } } if (empty($category)) { if ($sql != "" && strlen($sql) >= 1) { $this->db->where_in('r.category', $sql, FALSE); if (strlen($keywords) > 0) { $this->db->like("r.title", $keywords); $this->db->or_like("r.job_description", $keywords); } } }else{ if ($sql != "" && strlen($sql) >= 1) { $this->db->where_in('r.category', $sql); if (strlen($keywords) > 0) { $this->db->like("r.title", $keywords); $this->db->or_like("r.job_description", $keywords); } } } if($sort != FALSE){ if($sort == 0){ $this->db->order_by('r.job_created', 'ASC'); }else{ $this->db->order_by('r.job_created', 'DESC'); } } $this->db->where('r.status', 1); $this->db->where('(SELECT COUNT(*) FROM jobs r1 WHERE r.category = r1.category AND r.id < r1.id ) <= 1'); return $this->db->get_where('jobs r', $val, $limit, $offset); } }
Java
UTF-8
4,435
2.53125
3
[]
no_license
package it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.controller; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.connection.ConnectionManager; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.connection.FinishGame; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.model.BlackSheep; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.model.Dice; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.model.GameTable; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.model.Road; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.model.Sheep; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.shared.DebugLogger; import it.polimi.deib.provaFinale2014.francesco1.corsini_gabriele.carassale.shared.TypeAnimal; import java.util.logging.Logger; /** * Questa classe rappresenta il turno di un giocatore * * @author Carassale Gabriele */ public class Turn { private boolean forceLastRound; private final GameTable game; private final Dice dice; private final ConnectionManager connectionManager; /** * Costruttore solo per eseguire i Test(non ha il connectionManager) * * @param isLastTurn * @param gameTable */ public Turn(boolean isLastTurn, GameTable gameTable) { connectionManager = null; forceLastRound = isLastTurn; dice = new Dice(); game = gameTable; } /** * Costruttore * * @param isLastTurn true se è un turno dell'ultimo giro * @param gameTable gioco su cui si sta giocando * @param connectionManager dove sono tutte le connessioni */ public Turn(boolean isLastTurn, GameTable gameTable, ConnectionManager connectionManager) { this.connectionManager = connectionManager; forceLastRound = isLastTurn; dice = new Dice(); game = gameTable; } /** * Avvia il turno * * @return True se i cancelli sono finiti e il round che ha avviato il turno * deve diventare l'ultimo round * @throws FinishGame */ public boolean playTurn() throws FinishGame { moveBlackSheep(); //questo controllo serve per poter utilizzare i test senza connessioni(nel caso di Test non esistono i Client connessi) if (connectionManager != null) { connectionManager.startAction(); } //Alla fine delle azioni del player crescono gli animali growUpLambs(); if (game.getFenceNumber() <= 0) { forceLastRound = true; } return forceLastRound; } /** * gestisce il movimento pecora nera. È protected e non private poichè lo * devo chiamare per far fare il test su di lui * * @return true se la BlackSheep è stata mossa */ protected boolean moveBlackSheep() { BlackSheep blackSheep = game.getBlacksheep(); int diceNumber = dice.getRandom(); try { Road road = blackSheep.hasToMove(diceNumber); blackSheep.move(road); if (connectionManager != null) { connectionManager.refreshMoveAnimal(-1, blackSheep.getPosition().getID()); } return true; } catch (WrongDiceNumberException ex) { Logger.getLogger(DebugLogger.class.getName()).log(DebugLogger.getLevel(), ex.getMessage(), ex); return false; } } /** * Method che fa crescere tutti gli agnelli di 1 turno e se ne trova uno * abbastanza grande lo fa diventare pecora o montone */ protected void growUpLambs() { //è protected per poterlo testare for (Sheep ele : game.getSheeps()) { //se è un lamb lo faccio crescere if (ele.isLamb()) { ele.growUpOneTurn(); //se non è più lamb allora è cresciuto if (!ele.isLamb()) { String kind; if (ele.isRam()) { kind = TypeAnimal.RAM.toString(); } else { kind = TypeAnimal.WHITE_SHEEP.toString(); } connectionManager.refreshTransformAnimal(ele.getId(), kind); } } } } }
JavaScript
UTF-8
4,056
3.765625
4
[]
no_license
/** * Bài 1 * Khối 1: Input * wage: lương theo ngày * days: số ngày làm việc * * Khối 2: Các bước xử lý * B1: tạo và gán giá trị cho lương theo ngày * B2: tạo biến số ngày làm việc cho người dùng nhập vào * B3: xây dựng công thức * salary = wage*days * b4: xuất giá trị salary * Khối 3: Output * salary: tiền lương nhân viên * */ document.getElementById("btnLuong").onclick = function(){ var wage = 100000; console.log("Lương/ngày: " + wage); var days = document.getElementById("inputLuong").value; console.log("Số ngày làm việc: " + days); var salary = wage * days; console.log("Tiền lương phải trả: " + salary); document.getElementById("txtLuong").innerHTML = "Tiền lương phải trả: " + salary; } /** * Bài 2 * Khối 1: input * num1 - num5 * kiểu dữ liệu number(float) * * Khối 2: * B1: tạo và gán giá trị cho các biến num1 -> num5 và avg * B2: xây dựng công thức * average = (num1 + num2 + num3 + num4 + num5)/5 * B3: xuất giá trị average * * Khối 3: output * */ document.getElementById("btnAvg").onclick = function(){ var num1 = parseFloat(document.getElementById("num1").value); var num2 = parseFloat(document.getElementById("num2").value); var num3 = parseFloat(document.getElementById("num3").value); var num4 = parseFloat(document.getElementById("num4").value); var num5 = parseFloat(document.getElementById("num5").value); var avg = (num1 + num2 + num3 + num4 + num5)/5; console.log("Average: "+avg); document.getElementById("txtAvg").innerHTML = avg; } /** * Bài 3 * Khối 1: input * 1usd = 23500vnd * * Khối 2: * b1: tạo biến số tiền cần quy đổi là usd, * số tiền quy đổi là vnd, * rate = 23500 * b2 xây dựng côgn thức * vnd = usd * rate * B3: xuất giá trị * * B3 output * */ document.getElementById("btnCur").onclick = function(){ var rate = 23500; var usd = parseFloat(document.getElementById("inputCur").value); console.log("Số tiền cần đổi: "+usd+"usd"); var vnd = usd*rate; console.log("Số tiền quy đổi: "+vnd+"vnd"); document.getElementById("txtCur").innerHTML = vnd } /** * Bài 4 * Khối 1: input * chiều dài * chiều rộng * * Khối 2: * B1: tạo biến chiều dài "d" * chiều rộng "r" * diện tích "s" * chu vi "p" * B2: xấy dựng công thức * s = d*r * p = (d+r)*2 * b3: xuất giá trị * * Khối 3: ouput * s,p * */ document.getElementById("btnHcn").onclick = function(){ var d = parseFloat(document.getElementById("d").value); var r = parseFloat(document.getElementById("r").value); var s = d*r; console.log("Diện tích: "+s); document.getElementById("txtS").innerHTML = s var p = (d + r)*2; document.getElementById("txtP").innerHTML = p console.log("Chu vi: "+p); } /** * Bài 5 * Khối 1: input * số có 2 chữ số * * Khối 2: * B1: khai báo biến số nhập vào "num", * số hàng đơn vị "unit", * số hàng chục "dozen", * B2: xây dựng công thức * tách số hàng đơn vị: * unit = num%10 * tách số hàng chục: * dozen = Math.floor(num/10) * tính tổng unit và dozen * B3: xuất kết quả * * Khối 3: output * tổng cần tìm "sum" */ document.getElementById("btnNum").onclick = function(){ var num = parseFloat(document.getElementById("inputNum").value); console.log("Số có 2 chữ số: "+num); var unit = num%10 console.log("Số đơn vị: "+unit); var dozen = Math.floor(num/10); console.log("Số hàng chục: "+dozen); var sum = unit+dozen; console.log("Tổng cần tìm: "+sum); if(dozen < 10){ document.getElementById("txtNum").innerHTML = "Tổng 2 ký số là: "+ sum; }else{ document.getElementById("txtNum").innerHTML = "Vui lòng nhập số có 2 chữ số"; } }
Ruby
UTF-8
446
2.78125
3
[]
no_license
require 'active_support/all' require_relative 'formatted_value' class FormattedNumeric < FormattedValue def initialize(value, format) val = Float(value || 0) format.color = format.positive_color if val > 0 && format.positive_color format.color = format.negative_color if val < 0 && format.negative_color val = val.to_formatted_s(format.format.to_s.to_sym, precision: format.precision.to_i) super(val, format) end end
JavaScript
UTF-8
849
2.546875
3
[]
no_license
class DDl extends React.Component { desert = [ { value:1, text :"Gulab Jamun" }, { value:2, text :"Basundi" }, { value:3, text :"Jalebi" }, { value:4, text :"Ras Malai" }, ] render() { return ( <div> <h1>DROPDOWN LIST USING REACT</h1> <select> <option>--Select An Option --</option> { this.desert.map(displaydesert => <option title={displaydesert.value}>{displaydesert.text}</option>) } </select> </div> ) } } React.render(<DDl />, document.getElementById("list"));
C
UTF-8
4,963
3.203125
3
[ "BSD-3-Clause", "LicenseRef-scancode-mit-nagy", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "MIT", "GPL-1.0-or-later", "OpenSSL", "Apache-2.0" ]
permissive
#include <limits.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "test.h" static char buffer[100]; static void checkStrftime(const char* format, const struct tm* tm, const char* expected) { size_t resultLength = strftime(buffer, sizeof(buffer), format, tm); if (resultLength != 0 && strcmp(buffer, expected) != 0) { t_error("\"%s\": expected \"%s\", got \"%s\"\n", format, expected, buffer); } else if (resultLength == 0 && strlen(expected) != 0) { t_error("\"%s\": expected \"%s\", got nothing\n", format, expected); } } static struct tm tm1 = { .tm_sec = 45, .tm_min = 23, .tm_hour = 13, .tm_mday = 3, .tm_mon = 0, .tm_year = 2016 - 1900, .tm_wday = 0, .tm_yday = 2, .tm_isdst = 0 }; static struct tm tm2 = { .tm_sec = 53, .tm_min = 17, .tm_hour = 5, .tm_mday = 5, .tm_mon = 0, .tm_year = 10009 - 1900, .tm_wday = 1, .tm_yday = 4, .tm_isdst = 0 }; static struct tm tm3 = { .tm_sec = 0, .tm_min = 0, .tm_hour = 12, .tm_mday = 23, .tm_mon = 1, .tm_year = 0 - 1900, .tm_wday = 3, .tm_yday = 53, .tm_isdst = 0 }; static struct tm tm4 = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = -123 - 1900, .tm_wday = 1, .tm_yday = 0, .tm_isdst = 0 }; static struct tm tm5 = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = INT_MAX, .tm_wday = 3, .tm_yday = 0, .tm_isdst = 0 }; int main() { setenv("TZ", "UTC0", 1); checkStrftime("%c", &tm1, "Sun Jan 3 13:23:45 2016"); checkStrftime("%c", &tm2, "Mon Jan 5 05:17:53 +10009"); checkStrftime("%c", &tm3, "Wed Feb 23 12:00:00 0000"); // The POSIX.1-2008 standard does not specify the padding character for // "%C". The C standard requires that the number is padded by '0'. // See also http://austingroupbugs.net/view.php?id=1184 checkStrftime("%C", &tm1, "20"); checkStrftime("%03C", &tm1, "020"); checkStrftime("%+3C", &tm1, "+20"); checkStrftime("%C", &tm2, "100"); checkStrftime("%C", &tm3, "00"); checkStrftime("%01C", &tm3, "0"); checkStrftime("%F", &tm1, "2016-01-03"); checkStrftime("%012F", &tm1, "002016-01-03"); checkStrftime("%+10F", &tm1, "2016-01-03"); checkStrftime("%+11F", &tm1, "+2016-01-03"); checkStrftime("%F", &tm2, "+10009-01-05"); checkStrftime("%011F", &tm2, "10009-01-05"); checkStrftime("%F", &tm3, "0000-02-23"); checkStrftime("%01F", &tm3, "0-02-23"); checkStrftime("%06F", &tm3, "0-02-23"); checkStrftime("%010F", &tm3, "0000-02-23"); checkStrftime("%F", &tm4, "-123-01-01"); checkStrftime("%011F", &tm4, "-0123-01-01"); checkStrftime("%g", &tm1, "15"); checkStrftime("%g", &tm2, "09"); checkStrftime("%G", &tm1, "2015"); checkStrftime("%+5G", &tm1, "+2015"); checkStrftime("%04G", &tm2, "10009"); checkStrftime("%r", &tm1, "01:23:45 PM"); checkStrftime("%r", &tm2, "05:17:53 AM"); checkStrftime("%r", &tm3, "12:00:00 PM"); checkStrftime("%r", &tm4, "12:00:00 AM"); // The "%s" specifier was accepted by the Austin Group for the next POSIX.1 // revision. See http://austingroupbugs.net/view.php?id=169 checkStrftime("%s", &tm1, "1451827425"); if (sizeof(time_t) * CHAR_BIT >= 64) { checkStrftime("%s", &tm2, "253686748673"); } checkStrftime("%T", &tm1, "13:23:45"); checkStrftime("%T", &tm2, "05:17:53"); checkStrftime("%T", &tm3, "12:00:00"); checkStrftime("%T", &tm4, "00:00:00"); checkStrftime("%U", &tm1, "01"); checkStrftime("%U", &tm2, "01"); checkStrftime("%U", &tm3, "08"); checkStrftime("%V", &tm1, "53"); checkStrftime("%V", &tm2, "02"); checkStrftime("%V", &tm3, "08"); checkStrftime("%W", &tm1, "00"); checkStrftime("%W", &tm2, "01"); checkStrftime("%W", &tm3, "08"); checkStrftime("%x", &tm1, "01/03/16"); checkStrftime("%X", &tm1, "13:23:45"); checkStrftime("%y", &tm1, "16"); // There is no standard that explicitly specifies the exact format of "%Y". // The C standard says that "%F" is equivalent to "%Y-%m-%d". The // POSIX.1-2008 standard says that "%F" is equivalent to "%+4Y-%m-%d". // This implies that to conform to both standards "%Y" needs to be // equivalent to "%+4Y". // See also http://austingroupbugs.net/view.php?id=739 checkStrftime("%Y", &tm1, "2016"); checkStrftime("%05Y", &tm1, "02016"); checkStrftime("%+4Y", &tm1, "2016"); checkStrftime("%+5Y", &tm1, "+2016"); checkStrftime("%Y", &tm2, "+10009"); checkStrftime("%05Y", &tm2, "10009"); checkStrftime("%Y", &tm3, "0000"); checkStrftime("%02Y", &tm3, "00"); checkStrftime("%+5Y", &tm3, "+0000"); checkStrftime("%Y", &tm4, "-123"); checkStrftime("%+4Y", &tm4, "-123"); checkStrftime("%+5Y", &tm4, "-0123"); if (INT_MAX == 0x7FFFFFFF) { // The standard does not specify any range for tm_year, so INT_MAX // should be valid. checkStrftime("%y", &tm5, "47"); checkStrftime("%Y", &tm5, "+2147485547"); checkStrftime("%011Y", &tm5, "02147485547"); if (sizeof(time_t) * CHAR_BIT >= 64) { checkStrftime("%s", &tm5, "67768036160140800"); } } return t_status; }
Java
UTF-8
2,357
2.65625
3
[]
no_license
package interpretator.component.impl.expressionresolver; import interpretator.component.ExpressionResolver; import interpretator.exception.SyntaxInterpretatorException; import interpretator.model.Expression; import interpretator.model.expression.ArrayWithValuesDeclarationExpression; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static interpretator.Config.expressionResolver; public class ArrayWithValuesDeclarationExpressionResolver implements ExpressionResolver { @Override public boolean isSupport(String... tokens) { return tokens.length > 0 && "{".equals(tokens[0]); } @Override public Expression resolve(String... tokens) { validateSyntax(tokens); List<String[]> tokenGroup = groupByComma(Arrays.copyOfRange(tokens, 1, tokens.length-1)); List<Expression> expressions = tokenGroup.stream() .map(t -> expressionResolver.resolve(t)) .collect(Collectors.toList()); /*List<Expression> expressions = new ArrayList<>(); for (String [] token : tokenGroup) { expressions.add(expressionResolver.resolve(token)); }*/ return new ArrayWithValuesDeclarationExpression(expressions); } private List<String[]> groupByComma(String[] tokens) { if(tokens.length == 0) { return Collections.emptyList(); } List<String[]> result = new ArrayList<>(); List<String> tokenBuilder = new ArrayList<>(); for (String token : tokens) { if(",".equals(token)) { addTokenToResult(result, tokenBuilder); } else { tokenBuilder.add(token); } } addTokenToResult(result, tokenBuilder); return result; } private void addTokenToResult(List<String[]> result, List<String> tokenBuilder) { if(tokenBuilder.isEmpty()) { throw new SyntaxInterpretatorException("Missing array element"); } result.add(tokenBuilder.toArray(new String[0])); tokenBuilder.clear();; } private void validateSyntax(String[] tokens) { if(!"}".equals(tokens[tokens.length - 1])) { throw new SyntaxInterpretatorException("Missing }"); } } }
Python
UTF-8
992
3.375
3
[]
no_license
from sys import stdin def solution(N): counter = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] S, E = 1, N unit = 1 def count_chiper(num, unit): while num: counter[num%10] += unit num //= 10 while True: # move start and end while S%10 != 0 and S <= E: count_chiper(S, unit) S += 1 if S > E: break while E%10 != 9 and S <= E: count_chiper(E, unit) E -= 1 if S > E: break S //= 10 E //= 10 count = E - S + 1 for i in range(10): counter[i] += count*unit unit *= 10 return counter N = int(stdin.readline()) print(' '.join([str(i) for i in solution(N)])) # def dum_solution(N): # counter = [0,0,0,0,0,0,0,0,0,0] # for i in range(1, N+1): # for c in str(i): # counter[int(c)] += 1 # return counter # # print(' '.join([str(i) for i in dum_solution(N)]))
Python
UTF-8
786
2.84375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import base64 from Crypto.Cipher import AES def find_iv(): begin = data.find(b'\xFF\xC0') iv_len = 16 # skip marker and length end = begin + 4 + iv_len SOF0 = data[begin+4:end] return SOF0 def find_key(): begin = data.find(b'\xFF\xDA') key_len = 32 # skip marker end = begin + 2 + key_len SOS = data[begin+2:end] return SOS a = 'b3BlbnNzbCBlbmMgLWQgLWFlcy0yNTYtY2JjIC1pdiBTT0YwIC1LIFNPUyAtaW4gZmxhZy5lbmMg' b = 'LW91dCBmbGFnIC1iYXNlNjQKCml2IGRvZXMgbm90IGluY2x1ZGUgdGhlIG1hcmtlciBvciBsZW5n' c = 'dGggb2YgU09GMAoKa2V5IGRvZXMgbm90IGluY2x1ZGUgdGhlIFMwUyBtYXJrZXIKCg==' d = b'mmtaSHhAsK9pLMepyFDl37UTXQT0CMltZk7+4Kaa1svo5vqb6JuczUqQGFJYiycY.' hint = base64.b64decode(a+b+c) print('hint', hint) cipher = base64.b64decode(d) print('cipher', cipher) data = open('The-Keymaker.jpg', 'rb').read() key = find_key() print('key', key.hex(), len(key)) iv = find_iv() print('iv', iv.hex(), len(iv)) aes = AES.new(key, mode=AES.MODE_CBC, IV=iv) dec = aes.decrypt(cipher) print('flag', dec)
PHP
UTF-8
2,256
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; class ConfigAppRepository { /** * ConfigApp string representation. * * @var string */ protected $configApp; /** * ConfigApp path. * * @var string */ protected $configAppPath; /** * Items. * * @var array */ protected $items = [ 'name' => [ 'name', "/('name' => ')(.+)(')/" ], 'locale' => [ 'locale', "/('locale' => ')(.+)(')/" ], 'timezone' => [ 'timezone', "/('timezone' => ')(.+)(')/" ], 'backcommentsnestedlevel' => [ 'commentsNestedLevel', "/('commentsNestedLevel' =>\s)(.+)(,)/", ], 'backcommentsparent' => [ 'numberParentComments', "/('numberParentComments' =>\s)(.+)(,)/", ], 'frontposts' => [ 'nbrPages.front.posts', "/('front' => \[\n\s*'posts' =>\s)(.+)(,)/", ], 'backposts' => [ 'nbrPages.back.posts', "/('back' => \[\n\s*'posts' =>\s)(.+)(,)/", ], 'backusers' => [ 'nbrPages.back.users', "/('posts' =>\s.+\n\s*'users' =>\s)(.+)(,)/", ], 'backcomments' => [ 'nbrPages.back.comments', "/('users' =>.+\n\s*'comments' =>\s)(.+)(,)/", ], 'backcontacts' => [ 'nbrPages.back.contacts', "/('comments' =>.+\n\s*'contacts' =>\s)(.+)(,)/", ], ]; /** * Create a new ConfigAppRepository. * */ public function __construct() { $this->configAppPath = config_path ('app.php'); $this->configApp = file_get_contents($this->configAppPath); } /** * Update app config. * * @param array $inputs */ public function update($inputs) { foreach ($inputs as $key => $value) { if (config('app.' . $this->items[$key][0]) != $value) { $this->configApp = preg_replace ($this->items[$key][1], '${1}' . $value . '$3', $this->configApp); } } file_put_contents($this->configAppPath, $this->configApp); } }
TypeScript
UTF-8
603
2.796875
3
[]
no_license
class jQuery { constructor(selector: string) { const nodes = document.querySelectorAll(selector); const result: any = {}; for (let i in nodes) { if (nodes.hasOwnProperty(i)) { this[i] = nodes[i]; } } this['length'] = nodes.length; } length: number; [key: number]: Element; html(html: string) { for (let i in this) { this[i].innerHTML = html; } } } function $(selector: string) { return new jQuery(selector); } (window as any).$ = $; export default $;
Markdown
UTF-8
2,168
2.90625
3
[]
no_license
# Algorithms And Data Structures ## Help #### C++ To compile code use ```g++ -pipe -O2 -std=c++11 ./path/to/source.cpp -o ./path/to/dest.out``` #### Racket Run with REPL ```racket <filename.rkt>``` ## Contents | Issue | Solution examples | Description | | ----------- | ----------- | ----------- | | Stress testing | [c/c++](https://github.com/VladVes/algorithmsAndDataStructures/tree/master/c01-programming_challenges) | | Fibonacci sequence | [c/c++](https://github.com/VladVes/algorithms-and-data-structures/tree/master/c02-algorithmic_warmup/cpp) \| [racket](https://github.com/VladVes/algorithms-and-data-structures/tree/master/c02-algorithmic_warmup/rkt) | [wikipedia](https://ru.wikipedia.org/wiki/%D0%A7%D0%B8%D1%81%D0%BB%D0%B0_%D0%A4%D0%B8%D0%B1%D0%BE%D0%BD%D0%B0%D1%87%D1%87%D0%B8) | | Euclid GCD | [c/c++](https://github.com/VladVes/algorithmsAndDataStructures/tree/master/c02-algorithmic_warmup) | [wikipedia](https://ru.wikipedia.org/wiki/%D0%90%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC_%D0%95%D0%B2%D0%BA%D0%BB%D0%B8%D0%B4%D0%B0) | | Last common multiple | [c/c++](https://github.com/VladVes/algorithmsAndDataStructures/tree/master/c02-algorithmic_warmup) | [wikipedia](https://en.wikipedia.org/wiki/Least_common_multiple) | | Mony change | [c/c++ (greedy)](https://github.com/VladVes/algorithmsAndDataStructures/blob/master/c03-greedy_algorithms/change.cpp) | [wikipedia](https://en.wikipedia.org/wiki/Greedy_algorithm) | | Fractional knapsack | [c/c++ (greedy)](https://github.com/VladVes/algorithmsAndDataStructures/blob/master/c03-greedy_algorithms/fractional_knapsack.cpp) | [wikipedia](https://en.wikipedia.org/wiki/Continuous_knapsack_problem) | | Car fueling | [c/c++ (greedy)](https://github.com/VladVes/algorithmsAndDataStructures/blob/master/c03-greedy_algorithms/car_fueling.cpp) | [coursera](https://www.coursera.org/lecture/algorithmic-toolbox/car-fueling-implementation-and-analysis-shwg1) | ### Notes - Three of the most common algorithmic design techniques - Greedy algorithms - make a greedy choise - prove that it is a safe move - reduce to a subproblem and solve it - Divide and conquer - Dinamic programming
Java
UTF-8
3,595
2.875
3
[]
no_license
package view; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.layout.Pane; import java.io.IOException; import controller.Main; /** * An utility class to load and store the .fxml nodes of the view. * * The caching mechanism is useful when switching between views it prevents to reload the nodes and all the values * stored in their components (textboxes content, sliders position, ecc...). * * It is also possible to force the reloading of the nodes for heavy .fxml files instead of keeping them cached. */ public final class ScreenLoader { private final ObservableMap<FXMLScreens, Node> cache; private static ScreenLoader singleton; private ScreenLoader() { this.cache = FXCollections.observableHashMap(); } /** * Singleton class that return the {@link ScreenLoader}. * * @return the {@link ScreenLoader} */ public static ScreenLoader getScreenLoader() { synchronized (ScreenLoader.class) { if (singleton == null) { singleton = new ScreenLoader(); } } return singleton; } /** * Sets the loaded {@link Node} as main screen in the {@link Pane}. * * @param screen * {@link FXMLScreens} to be loaded * @param mainPane * the {@link Pane} * @throws IOException * if the resource is not found */ public void loadScreen(final FXMLScreens screen, final Pane mainPane) throws IOException { mainPane.getChildren().setAll(this.getLoadedNode(screen)); } /** * Return the loaded {@link Node}. * * @param screen * the {@link FXMLScreens} * @return the {@link Node} * @throws IllegalStateException * the {@link IllegalStateException}n */ public Node getLoadedNode(final FXMLScreens screen) throws IllegalStateException { if (!this.cache.containsKey(screen)) { throw new IllegalStateException(); } else { return this.cache.get(screen); } } /** * Seeks for the required {@link FXMLScreens} in the cache If not present it is loaded then returned. * * @param screen * {@link FXMLScreens} to be loaded * @param controller * the Object controller * @return the {@link Node} rendered * @throws IOException * if the resource is not found */ public Node loadFXMLInCache(final FXMLScreens screen, final Object controller) throws IOException { if (this.cache.containsKey(screen)) { return this.cache.get(screen); } else { final Node loadedNode = this.loadFXML(screen, controller); this.cache.put(screen, loadedNode); return loadedNode; } } /** * Bypass the cache and loads directly the {@link FXMLScreens}. * * @param screen * {@link FXMLScreens} to be loaded * @param controller * the Object controller * @return the {@link Node} loaded * @throws IOException * if the resource is not found */ public Node loadFXML(final FXMLScreens screen, final Object controller) throws IOException { final FXMLLoader loader = new FXMLLoader(); loader.setController(controller); loader.setLocation(Main.class.getResource(screen.getPath())); return loader.load(); } }
TypeScript
UTF-8
2,565
3.375
3
[]
no_license
export interface NaturalPerson { name: string; firstLastName: string; secondLastName: string; day: number; month: number; year: number; } export function calculate(person: NaturalPerson): string { return new NameCode(person).toString() + new BirthdayCode(person).toString(); } // matches any ocurrence of the special particles as a word: '^foo | foo | foo$'' const specialParticlesRegex: RegExp = new RegExp('(?:' + ["DE", "LA", "LAS", "MC", "VON", "DEL", "LOS", "Y", "MAC", "VAN", "MI"] .map((p) => `^${p} | ${p} | ${p}$`) .join('|') + ')', 'g'); class NameCode { private filteredPersonName: string; constructor(private person: NaturalPerson) { this.filteredPersonName = this.getFilteredPersonName(); } toString(): string { if (this.isFirstLastNameIsTooShort()) { return this.normalize(this.person.firstLastName).charAt(0) + this.normalize(this.person.secondLastName).charAt(0) + this.filteredPersonName.substring(0, 2); } else { return this.normalize(this.person.firstLastName).charAt(0) + this.firstVowelExcludingFirstCharacterOf(this.normalize(this.person.firstLastName)) + this.normalize(this.person.secondLastName).charAt(0) + this.filteredPersonName.charAt(0); } } // filter out common names (if more than one is provided) private getFilteredPersonName(): string { const normalized = this.normalize(this.person.name); if (this.person.name.split(' ').length > 1) { return normalized.replace(/(?:^JOSE |^MARIA |^MA |^MA\. ?)/gi, ''); } return normalized; } private normalize(s: string): string { return this.removeAccents(s.toUpperCase()) .replace(/\s+/g, ' ') // double space to allow multiple special-particles matching .replace(specialParticlesRegex, '') .replace(/\s+/g, ' ') // reset space .trim(); } private firstVowelExcludingFirstCharacterOf(s: string): string { return /[aeiou]/i.exec(s.slice(1))[0]; } private isFirstLastNameIsTooShort(): boolean { return this.normalize(this.person.firstLastName).length <= 2; } private removeAccents(input: string): string { return input.normalize('NFD') .replace(/[\u0300-\u036f]/g, ""); } } class BirthdayCode { constructor(private person: NaturalPerson) { } toString(): string { return this.person.year.toString().slice(-2) + this.zeroPadded(this.person.month) + this.zeroPadded(this.person.day); } private zeroPadded(n: number): string { return ('00' + n).slice(-2); } }
C#
UTF-8
758
2.546875
3
[]
no_license
using System.ComponentModel.DataAnnotations; namespace TestingService.Models.AccountModels { public class RegisterModel { [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Некорректный адрес")] [Required] public string Email { get; set; } [StringLength(20, MinimumLength = 6, ErrorMessage = "Длина пароля должна быть от 6 до 20 символов")] [Required] public string Password { get; set; } [Required] public string Name { get; set; } [Required] public string Surname { get; set; } public string Patronomic { get; set; } public string Role { get; set; } } }
Ruby
UTF-8
808
3.1875
3
[]
no_license
describe '#convert_between_temperature_units' do it 'is defined and functions for simple values' do expect(convert_between_temperature_units(0, 'C', 'K')).to be_within(0.0001).of(273.15) expect(convert_between_temperature_units(1, 'C', 'F')).to be_within(0.0001).of(33.8) end end describe '#melting_point_of_substance' do it 'knows the melting point of water' do expect(melting_point_of_substance('water', 'C')).to be_within(0.01).of(0) expect(melting_point_of_substance('water', 'K')).to be_within(0.01).of(273.15) end end describe '#boiling_point_of_substance' do it 'knows the boiling point of water' do expect(boiling_point_of_substance('water', 'C')).to be_within(0.01).of(100) expect(boiling_point_of_substance('water', 'K')).to be_within(0.01).of(373.15) end end
C++
UTF-8
117
2.671875
3
[]
no_license
#include <stdio.h> int main() { int c; float f; scanf("%d", &c); f = 9.0 / 5.0 * c + 32; printf("%.1f",f); }
C
UTF-8
274
2.671875
3
[]
no_license
#include "client.h" static int usage(void) { printf("usage: ./client [port]\n"); return (1); } int main(int argc, char **argv) { t_uint16 port; if (argc < 2) return (usage()); port = ft_atoi(argv[1]); if (connect_server(port) == -1) return (1); return (0); }
Java
UTF-8
873
2.3125
2
[]
permissive
package com.apptentive.android.sdk.partners.apptimize; /** * Data container class that mimics `ApptimizeTestInfo`. * https://sdk.apptimize.com/ios/appledocs/appledoc-3.0.1/Protocols/ApptimizeTestInfo.html */ public class ApptentiveApptimizeTestInfo { private final String testName; private final String enrolledVariantName; private final boolean participated; public ApptentiveApptimizeTestInfo(String testName, String enrolledVariantName, boolean participated) { this.testName = testName; this.enrolledVariantName = enrolledVariantName; this.participated = participated; } public String getTestName() { return this.testName; } public String getEnrolledVariantName() { return this.enrolledVariantName; } public boolean userHasParticipated() { return this.participated; } }
Markdown
UTF-8
5,054
2.671875
3
[]
no_license
--- description: "Recipe of Any-night-of-the-week Steak Salad" title: "Recipe of Any-night-of-the-week Steak Salad" slug: 457-recipe-of-any-night-of-the-week-steak-salad date: 2020-11-11T22:20:35.338Z image: https://img-global.cpcdn.com/recipes/3518ae412f60526d/751x532cq70/steak-salad-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/3518ae412f60526d/751x532cq70/steak-salad-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/3518ae412f60526d/751x532cq70/steak-salad-recipe-main-photo.jpg author: Hulda Wong ratingvalue: 4.9 reviewcount: 5 recipeingredient: - "2 lb beef sirloin steaks" - "12 cherry tomatoes" - "1 medium red onion thinly sliced" - "1 jar (7.5 oz) marinated artichoke hearts drained and sliced" - "1 cup sliced mushrooms" - "1/4 cup red wine vinegar" - "1/4 cup olive oil" - "1 tsp salt" - "1/2 tsp oregano" - "1/2 tsp dried rosemary" - "1/2 tsp pepper" - "1/2 tsp minced garlic" - "6 cups baby spinach" recipeinstructions: - "Grill steaks, covered, over medium heat until meat reaches desired doneness" - "Meanwhile, in a large bowl, combine tomatoes, onion, artichokes and mushrooms. In small bowl, whisk the vinegar, oil, sugar, salt, oregano, rosemary, pepper and garlic. Pour over vegetable mixture; toss to coat." - "Thinly slice steaks across the grain. Add beef and spinach to vegetable mixture; toss to coat." categories: - Recipe tags: - steak - salad katakunci: steak salad nutrition: 275 calories recipecuisine: American preptime: "PT25M" cooktime: "PT53M" recipeyield: "2" recipecategory: Dinner --- <br> Hey everyone, welcome to our recipe site, If you're looking for recipes idea to cook today, look no further! We provide you only the best Steak Salad recipe here. We also have wide variety of recipes to try. <br> ![Steak Salad](https://img-global.cpcdn.com/recipes/3518ae412f60526d/751x532cq70/steak-salad-recipe-main-photo.jpg) <i>Before you jump to Steak Salad recipe, you may want to read this short interesting healthy tips about <strong>Easy Ways to Get Healthy</strong>.</i> You already realize that, to achieve true health, your diet needs to be balanced and wholesome and you need to get a good amount of exercise. Sadly, there isn't often enough time or energy for us to really do the things we need to do. Working out at the gym isn't something people make time for when they get off from work. A hot, grease laden burger is usually our food of choice and not a leafy green salad (unless we are vegetarians). You should be thankful to learn that getting healthy doesn't always have to be super difficult. If you are conscientious you'll get all of the activity and healthy food you need. Here are some very simple ways to get healthful. Be wise when you do your food shopping. If you make smart decisions when you are purchasing your groceries, you will be eating better meals by default. At the conclusion of your day do you really want to deal with crowded grocery stores and long waits in the drive through line? You want to get home immediately and have something beneficial. Fill your pantry shelves with healthy foods. This way—even if you decide on something slightly greasy or not as good for you as it could be, you’re still picking foods that are better for you than you would get at the local diner or fast food drive through window. There are a good deal of things that factor into getting healthy. An costly gym membership and very restrictive diets are not the only way to do it. You can do small things each day to improve upon your health and lose weight. Make sensible choices every day is a great start. A good amount of physical activity each day is also critical. Remember: being healthy and balanced isn’t just about losing weight. It is more about making your body as powerful as it can be. <i>We hope you got insight from reading it, now let's go back to steak salad recipe. You can cook steak salad using <strong>13</strong> ingredients and <strong>3</strong> steps. Here is how you cook that. </i> ##### The ingredients needed to cook Steak Salad: 1. Take 2 lb beef sirloin steaks 1. Provide 12 cherry tomatoes 1. Get 1 medium red onion, thinly sliced 1. Take 1 jar (7.5 oz) marinated artichoke hearts, drained and sliced 1. Get 1 cup sliced mushrooms 1. Prepare 1/4 cup red wine vinegar 1. Provide 1/4 cup olive oil 1. Provide 1 tsp salt 1. You need 1/2 tsp oregano 1. Prepare 1/2 tsp dried rosemary 1. Use 1/2 tsp pepper 1. Use 1/2 tsp minced garlic 1. Provide 6 cups baby spinach ##### Steps to make Steak Salad: 1. Grill steaks, covered, over medium heat until meat reaches desired doneness 1. Meanwhile, in a large bowl, combine tomatoes, onion, artichokes and mushrooms. In small bowl, whisk the vinegar, oil, sugar, salt, oregano, rosemary, pepper and garlic. Pour over vegetable mixture; toss to coat. 1. Thinly slice steaks across the grain. Add beef and spinach to vegetable mixture; toss to coat. <i>If you find this Steak Salad recipe useful please share it to your friends or family, thank you and good luck.</i>
Python
UTF-8
216
3
3
[]
no_license
def classifica_idade(idade): if idade<12: print("crianca") else: if idade>=12 and x<18: print('adolescente') else: if idade>=18: print("adulto")
SQL
UTF-8
415
2.84375
3
[]
no_license
DROP TABLE IF EXISTS ACCOUNT; CREATE TABLE ACCOUNT ( ACCOUNT_NUMBER VARCHAR(100) PRIMARY KEY NOT NULL, PIN INT NOT NULL, OPEN_BALANCE INT NOT NULL, OVERDRAFT INT NOT NULL ); INSERT INTO ACCOUNT (ACCOUNT_NUMBER, PIN, OPEN_BALANCE, OVERDRAFT) VALUES (123456789, 1234, 800, 200), (987654321, 4321, 1230, 150);
Swift
UTF-8
838
3.28125
3
[]
no_license
// // MovieModel.swift // MovieRentalApp // // Created by Akaash Dev on 25/03/20. // Copyright © 2020 Sarath Chenthamarai. All rights reserved. // import Foundation struct MovieModel: Equatable { let id: Int let name: String let posterUrlString: String let ratings: Double let pricing: PricingModel var isOutOfStock: Bool = false static func ==(lhs: MovieModel, rhs: MovieModel) -> Bool { return lhs.id == rhs.id } func updateOutOfStock(value: Bool) -> MovieModel { var copy = self copy.isOutOfStock = value return copy } } struct PricingModel { let id: Int let name: String let initialCostString: String let additionalCostString: String var formattedPricing: String { return initialCostString + "\n" + additionalCostString } }
Java
UTF-8
1,701
3.359375
3
[]
no_license
package com.day5; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { BufferedReader reader; int maxID=0; ArrayList<Integer> seats = new ArrayList<>(); try { reader = new BufferedReader(new FileReader("input-day5.txt")); String seat = reader.readLine(); while(seat != null) { int minC = 0; int maxC = 127; int minR = 0; int maxR = 7; for(char letter : seat.toCharArray()) { if(letter == 'F') { maxC -= (maxC - minC + 1)/2; } if(letter == 'B') { minC += (maxC - minC + 1)/2; } if(letter == 'R') { minR += (maxR - minR +1)/2; } if(letter == 'L') { maxR -= (maxR - minR +1)/2; } } int ID = minC * 8 + maxR; seats.add(ID); if(ID > maxID) maxID = ID; seat = reader.readLine(); } } catch (IOException e) { e.printStackTrace(); } System.out.println(maxID + "\n"); Collections.sort(seats); for(int i = 0; i < seats.size()-1; i++) { if(seats.get(i+1)-seats.get(i) > 1) { System.out.println(seats.get(i)+1); } } } }
C++
UTF-8
1,426
2.75
3
[]
no_license
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc.hpp> #include<opencv2/opencv.hpp> #include<iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat image1; image1 = imread("C:/Lena_color.png", IMREAD_GRAYSCALE); if (image1.empty()) { cout << "Could not open or find the img" << std::endl; return -1; } //resize(image1, image1, Size(256, 256), 0, 0, INTER_LINEAR); Mat new_image = Mat::zeros(image1.size(), image1.type()); int masksize = 3; //Default int sum = 0; cout << "Enter the marsksize (Only odd)" << std::endl; cin >> masksize; for (int y = 0; y < image1.rows; y++) { for (int x = 0; x < image1.cols; x++) { sum = 0; int new_y, new_x; for (int i = -1 * masksize / 2; i <= masksize / 2; i++) { for (int j = -1 * masksize / 2; j <= masksize / 2; j++) { new_y = y + i; new_x = x + j; //Fill all border values with (0,0) if (new_y < 0) new_y = 0; else if (new_y > image1.rows - 1) new_y = 0; if (new_x < 0) new_x = 0; else if (new_x > image1.cols - 1) new_x = 0; sum += image1.at<uchar>(new_y, new_x) * 1; } } sum = sum/(masksize*masksize); if (sum > 255) sum = 255; if (sum < 0) sum = 0; new_image.at<uchar>(y, x) = sum; } } namedWindow("Display window", WINDOW_AUTOSIZE); imshow("Display window", new_image); waitKey(0); return 0; }
SQL
UTF-8
2,088
3.609375
4
[]
no_license
use lastmile_chwdb; drop view if exists view_chwPerformanceIndicatorQA; create view view_chwPerformanceIndicatorQA as select s1.chwID, s1.yearReported, s1.monthReported, if( s1.iCCMNutritionNumberInitialSickChildVisitsTotal is null, 0, s1.iCCMNutritionNumberInitialSickChildVisitsTotal ) as initialSickChildVisit, if( s1.iCCMNutritionReferredForDangerSignTotal is null, 0, s1.iCCMNutritionReferredForDangerSignTotal ) as referredForDangerSign, if( s1.professionalismSupervisionVisitAttemptedTotal is null, 0, s1.professionalismSupervisionVisitAttemptedTotal ) as supervisionVisitAttempted, if( s1.professionalismCHWAbsentForSupervisionTotal is null, 0, s1.professionalismCHWAbsentForSupervisionTotal ) as CHWAbsentForSupervision, if( s1.professionalismExcusedAbsenceTotal is null, 0, s1.professionalismExcusedAbsenceTotal ) as excusedAbsence, l.staffName, l.district, l.healthDistrict, l.healthFacility, l.county from staging_chwMonthlyServiceReportStep1 as s1 left outer join staging_chwMonthlyServiceReportStep1 as s2 on ( ( s1.chwID = s2.chwID ) and ( s1.yearReported = s2.yearReported ) and ( s1.monthReported = s2.monthReported ) and ( s1.chwMonthlyServiceReportStep1ID >= s2.chwMonthlyServiceReportStep1ID ) ) left outer join view_staffTypeLocation as l on ( s1.chwID = l.staffID ) and ( l.staffType like 'CHW' ) group by s1.chwID, s1.yearReported, s1.monthReported having count( * ) >= 1 order by cast( s1.chwID as unsigned ) asc, s1.yearReported desc, s1.monthReported desc ;
JavaScript
UTF-8
840
2.6875
3
[]
no_license
Components.Background = (function() { return React.createClass({ getDefaultProps: function() { return {} }, getInitialState: function() { return {} }, render: function () { var classes = "background"; if(this.props.type) { classes += " background--" + this.props.type; } if(this.props.border) { if(this.props.border.includes("T")) { classes += " background--border-top"} if(this.props.border.includes("B")) { classes += " background--border-bottom"} if(this.props.border.includes("L")) { classes += " background--border-left"} if(this.props.border.includes("R")) { classes += " background--border-right"} } return ( <div className={classes}> {this.props.children} </div> ); } }); })();
PHP
UTF-8
2,375
4.0625
4
[]
no_license
<?php /*_ EXERCICE 5 (1 PT) **_____ **Hand in: pool_php_d07/ex_05/Character.php **pool_php_d07/ex_05/Warrior.php **pool_php_d07/ex_05/Mage.php **pool_php_d07/ex_05/IMovable.php **Now our characters can talk, walk and attack in a customized way. Yet, they still cannot unsheathe their **weapon! Being able to attack is nice, but attacking while the weapon is still in its sheath is going to be diffi- **cult. . . **You will agree that, whether Warrior or Mage, the character will draw his weapon the same way. This is **why you will make sure that the class “Character” implements the method “unsheathe” so that **“Warrior” and “Mage” inherits from it. However, you will also make sure that the method “unsheathe” can- **not be overrided by “Warrior” and “Mage”. **This method will display the following text when it is called: “[NAME]: unsheathes his weapon.” */ include_once('IMovable.php'); class Character implements IMovable { protected $name; protected $life; protected $agility; protected $strength; protected $wit; const CLASSE = self::class; public function __CONSTRUCT($nom) { $this->name=$nom; $this->life=50; $this->agility=2; $this->strength=2; $this->wit=2; } public function getName() { return $this->name; } public function getLife() { return $this->life; } public function getAgility() { return $this->agility; } public function getStrength() { return $this->strength; } public function getWit() { return $this->wit; } public function getClasse() { return self::CLASSE; } final public function unsheathe() { echo $this->name, ": unsheathes his weapon.\n"; } public function moveRight() { echo $this->name,": moves right.\n"; } public function moveLeft() { echo $this->name,": moves left.\n"; } public function moveUp() { echo $this->name,": moves up.\n"; } public function moveDown() { echo $this->name,": moves down.\n"; } } /* $perso = new Character("Jean-Luc"); echo $perso ->getName()."\n"; echo $perso ->getLife()."\n"; echo $perso ->getAgility()."\n"; echo $perso ->getStrength()."\n"; echo $perso ->getWit()."\n"; echo $perso ->getClasse()."\n"; */
PHP
UTF-8
4,591
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Auth extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('MainModel', 'main'); $this->load->model('AuthModel', 'auth'); $this->form_validation->set_error_delimiters('<small class="form-text text-danger">* ', '</small>'); $this->form_validation->set_message('required', 'Kolom {field} harus diisi'); $this->form_validation->set_message('numeric', 'Isi kolom {field} dengan angka (0-9)'); $this->form_validation->set_message('min_length', 'Kolom {field} minimal {param} digit'); $this->form_validation->set_message('max_length', 'Kolom {field} maksimal {param} digit'); $this->form_validation->set_message('is_unique', '%s ini sudah ada'); $this->form_validation->set_message('matches', 'Kolom {field} harus sama dengan kolom {param}'); } private function template($page, $data = null) { $this->load->view('templates/auth/header', $data); $this->load->view($page); $this->load->view('templates/auth/footer'); } public function index() { // Cek Login if ($this->session->has_userdata('user')) { redirect('transaksi'); } $data['judul'] = "Login - Catatan Keuangan"; $this->form_validation->set_rules('username', 'Username', 'required|trim'); $this->form_validation->set_rules('pin', 'PIN', 'required|trim|numeric|min_length[4]|max_length[6]'); if ($this->form_validation->run() == false) { $this->template('auth/login', $data); } else { $input = $this->input->post(null, true); $cekUsername = $this->auth->cekUsername($input['username']); $pin = $cekUsername['pin']; if (count($cekUsername) > 0) { if (password_verify($input['pin'], $pin)) { $user = [ 'id_user' => $cekUsername['id_user'], 'username' => $cekUsername['username'], 'logged_in_at' => time() ]; $this->session->set_userdata('user', $user); redirect('transaksi'); } else { alert('danger', 'Password salah.'); redirect('login'); } } else { alert('danger', 'Username tidak terdaftar.'); redirect('login'); } } } private function getNewId($tgl_lahir, $char) { $table = "U"; $field = 'id_user'; $tgl = date('ymd', strtotime($tgl_lahir)); $prefix = $char . $tgl; $lastId = $this->auth->getMaxId($table, $field, $prefix); $noUrut = (int) substr($lastId, -4, 4); $noUrut += 1; $newId = $char . $tgl . sprintf('%04s', $noUrut); return $newId; } public function register() { $data['judul'] = "Daftar Akun - Catatan Keungan"; $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[user.username]'); $this->form_validation->set_rules('tgl_lahir', 'Tanggal Lahir', 'required|trim'); $this->form_validation->set_rules('pin', 'PIN', 'required|trim|numeric|min_length[4]|max_length[6]'); $this->form_validation->set_rules('confirm_pin', 'Konfirmasi PIN', 'required|trim|matches[pin]'); if ($this->form_validation->run() == false) { $this->template('auth/register', $data); } else { $input = $this->input->post(null, true); $userId = $this->getNewId($input['tgl_lahir'], 'U'); $userData = [ 'id_user' => $userId, 'username' => $input['username'], 'tgl_lahir' => $input['tgl_lahir'], 'pin' => password_hash($input['pin'], PASSWORD_DEFAULT) ]; // Insert data user $insert = $this->main->insert('user', $userData); if ($insert) { alert('success', 'Anda berhasil mendaftar, silahkan login.'); } else { $this->session->set_flashdata('pesan', "<div class='alert alert-danger'><strong>ERROR!</strong> Gagal menyimpan data anda</div>"); } redirect('login'); } } public function logout() { $this->session->unset_userdata('user'); $this->session->sess_destroy(); redirect('login'); } }
PHP
UTF-8
7,210
2.671875
3
[ "MIT" ]
permissive
<?php namespace Fenos\Notifynder\Builder; use Closure; use ArrayAccess; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Fenos\Notifynder\Helpers\TypeChecker; use Fenos\Notifynder\Models\NotificationCategory; use Fenos\Notifynder\Exceptions\UnvalidNotificationException; /** * Class Builder. */ class Builder implements ArrayAccess { /** * @var Notification */ protected $notification; /** * @var array */ protected $notifications = []; /** * Builder constructor. */ public function __construct() { $this->notification = new Notification(); } /** * Set the category for this notification. * * @param string|int|\Fenos\Notifynder\Models\NotificationCategory $category * @return $this */ public function category($category) { $categoryId = NotificationCategory::getIdByCategory($category); $this->setNotificationData('category_id', $categoryId); return $this; } /** * Set the sender for this notification. * * @return $this */ public function from() { $args = func_get_args(); $this->setEntityData($args, 'from'); return $this; } /** * Set the sender anonymous for this notification. * * @return $this */ public function anonymous() { $this->setNotificationData('from_type', null); $this->setNotificationData('from_id', null); return $this; } /** * Set the receiver for this notification. * * @return $this */ public function to() { $args = func_get_args(); $this->setEntityData($args, 'to'); return $this; } /** * Set the url for this notification. * * @param string $url * @return $this */ public function url($url) { TypeChecker::isString($url); $this->setNotificationData('url', $url); return $this; } /** * Set the expire date for this notification. * * @param Carbon|\DateTime $datetime * @return $this */ public function expire(Carbon $datetime) { TypeChecker::isDate($datetime); $carbon = new Carbon($datetime); $this->setNotificationData('expires_at', $carbon); return $this; } /** * Set the extra values for this notification. * You can extend the existing extras or override them - important for multiple calls of extra() on one notification. * * @param array $extra * @param bool $override * @return $this */ public function extra(array $extra = [], $override = true) { TypeChecker::isArray($extra); if (! $override) { $extra = array_merge($this->getNotificationData('extra', []), $extra); } $this->setNotificationData('extra', $extra); return $this; } /** * Set updated_at and created_at fields. */ public function setDates() { $date = Carbon::now(); $this->setNotificationData('updated_at', $date); $this->setNotificationData('created_at', $date); } /** * Set a single field value. * * @param string $key * @param mixed $value * @return $this */ public function setField($key, $value) { $additionalFields = notifynder_config()->getAdditionalFields(); if (in_array($key, $additionalFields)) { $this->setNotificationData($key, $value); } return $this; } /** * Set polymorphic model values. * * @param array $entity * @param string $property */ protected function setEntityData($entity, $property) { if (is_array($entity) && count($entity) == 2) { TypeChecker::isString($entity[0]); TypeChecker::isNumeric($entity[1]); $type = $entity[0]; $id = $entity[1]; } elseif ($entity[0] instanceof Model) { $type = $entity[0]->getMorphClass(); $id = $entity[0]->getKey(); } else { TypeChecker::isNumeric($entity[0]); $type = notifynder_config()->getNotifiedModel(); $id = $entity[0]; } $this->setNotificationData("{$property}_type", $type); $this->setNotificationData("{$property}_id", $id); } /** * Get a single value of this notification. * * @param string $key * @param null|mixed $default * @return mixed */ protected function getNotificationData($key, $default = null) { return $this->notification->get($key, $default); } /** * Set a single value of this notification. * * @param string $key * @param mixed $value */ protected function setNotificationData($key, $value) { $this->notification->set($key, $value); } /** * Get the current notification. * * @return Notification * @throws UnvalidNotificationException */ public function getNotification() { if (! $this->notification->isValid()) { throw new UnvalidNotificationException($this->notification); } $this->setDates(); return $this->notification; } /** * Add a notification to the notifications array. * * @param Notification $notification */ public function addNotification(Notification $notification) { $this->notifications[] = $notification; } /** * Get all notifications. * * @return array * @throws UnvalidNotificationException */ public function getNotifications() { if (count($this->notifications) == 0) { $this->addNotification($this->getNotification()); } return $this->notifications; } /** * Loop over data and call the callback with a new Builder instance and the key and value of the iterated data. * * @param array|\Traversable $data * @param Closure $callback * @return $this * @throws UnvalidNotificationException */ public function loop($data, Closure $callback) { TypeChecker::isIterable($data); foreach ($data as $key => $value) { $builder = new static(); $callback($builder, $value, $key); $this->addNotification($builder->getNotification()); } return $this; } /** * @param string $offset * @return bool */ public function offsetExists($offset) { return $this->notification->offsetExists($offset); } /** * @param string $offset * @return mixed */ public function offsetGet($offset) { return $this->notification->offsetGet($offset); } /** * @param string $offset * @param mixed $value */ public function offsetSet($offset, $value) { $this->notification->offsetSet($offset, $value); } /** * @param string $offset */ public function offsetUnset($offset) { $this->notification->offsetUnset($offset); } }
Markdown
UTF-8
749
2.96875
3
[ "Apache-2.0" ]
permissive
# Weatherworks Weatherworks is an online platform that aims at weather detection by classifying sky images. The multiclass application distinguishes the weather into rainy, cloudy, shiny and sunrise giving an opportunity of suitable precautions that could be undertaken by the user. From the perspective of agriculture, the applications helps to forecast the type of weather for the day which helps avoid unnecessary chaos. ## Steps to follow 1) Install the required packages mentioned in "requirement.txt". 2) Download the dataset from https://drive.google.com/file/d/1HF4kd3UV0ttnkItY-ORUEY53ej1gXp6t/view?usp=drivesdk. 3) Make sure that the training dataset "train" and test dataset "test" are inside the directory "Preprocessed_image".
Python
UTF-8
5,572
3.140625
3
[]
no_license
import pygame from const import TILE_SIZE from Item import Item class Block: """ Class qui initialise un block """ def __init__(self, world, chunk, name, x, y, image, hardness, have_hitbox): """ Constructor d'un block :param world: World.World --> monde auquel appartient le block :param chunk: Int --> position du block dans le monde dans un chunk (10xhauteur du monde) :param name: Str --> nom / id du block :param x: Int --> position x :param y: Int --> position y :param image: pygame.Surface --> image :param hardness: Int --> resistance du block (temps de minage) :param have_hitbox: Bool --> est ce que le block a une hitbox """ self.world = world self.chunk = chunk # print(chunk) self.name = name # change la taille de l'image => TILE_SIZE² (60x60) self.image = pygame.transform.scale(image, (TILE_SIZE, TILE_SIZE)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y # variable qui compte le temps ou la souris est appuyer sur le block self.timer = 0 # resistance du block (temps de cassage) -1 -> block incassable self.hardness = hardness # collision avec ce block ? self.have_hitbox = have_hitbox def set_image(self, image): """ Change la variable image """ self.image = pygame.transform.scale(image, (TILE_SIZE, TILE_SIZE)) def set_name(self, name): """ Change la variable name """ self.name = name def get_rect(self): """ Renvoie self.rect """ return self.rect def get_pos(self): """ Renvoie la position du block """ return self.rect.x, self.rect.y, self.get_chunk() def get_chunk(self): """ Renvoie le chunk dans leqeul le block est """ return self.chunk def destroy(self): """ Method qui permet de detruire les blocks (meilleur nom a trouve) """ # recuperation de la position de la souris pos = pygame.mouse.get_pos() # si la souris est sur le block if pygame.mouse.get_pressed(3)[0] == 1: # si le bouton gauche de la souris est appuyer et que le temps ou il est appuyer est < self.hardness # (temps de cassage) if pygame.rect.Rect(self.get_rect().x * TILE_SIZE + self.get_chunk() * 10 * TILE_SIZE + self.world.decalagex, self.get_rect().y * (-TILE_SIZE) + self.world.decalagey, self.get_rect().w, self.get_rect().h).collidepoint(pos) and \ self.timer < self.hardness: # le block est en train d'etre casse self.timer += 1 # si le temps ou il est maintenu est egal au temps de cassage (le block se casse) if self.timer == self.hardness: # recuperation de la cle du block key = str(self.get_pos()[0]) + "_" + str(self.get_pos()[1] - self.world.game.y + self.world.decalagey) + "_" + str(self.get_pos()[2]) # ajout dans l'inventaire self.drop() # recuperation de la cle du block en dessous block_below = str(self.get_pos()[0]) + "_" + str(self.get_pos()[1] - self.world.game.y + self.world.decalagey - 1) + "_" + str(self.get_pos()[2]) # s il existe un block en dessous de celui qui vient d etre casse if block_below in self.world.tile_list: # update du block si c'est de la terre self.update_grass(self.world.tile_list[block_below]) # suppression du block dans le monde del (self.world.tile_list[key]) # si le bouton gauche de la souris est relache ou # que la souris n'est plus sur le block => reinitialisation du compteur if pygame.mouse.get_pressed(3)[0] == 0 or not pygame.rect.Rect( self.get_rect().x * TILE_SIZE + self.get_chunk() * 10 * TILE_SIZE + self.world.decalagex, self.get_rect().y * (-TILE_SIZE) + self.world.decalagey, self.get_rect().w, self.get_rect().h).collidepoint(pos): self.timer = 0 def update_grass(self, tile): """ Method qui transforme de la dirt en grass s il n'y a pas de block au dessus """ # si c'est de la dirt if tile.name == "dirt": # transformation de la dirt en grass (nom et image changent) tile.set_name("grass") tile.set_image(self.world.grass_img) # sinon on ne fait rien else: return def drop(self): """ Ajoute un block a l'inventaire du joueur """ # recuperation du 1er slot vide dans l inventaire ou s il y a deja le meme block dans l inventaire for key, value in self.world.game.player.inventory.items(): if value.item is not None and value.item.name == self.name: self.world.game.player.inventory[key].count += 1 return for key, value in self.world.game.player.inventory.items(): if value.item is None: self.world.game.player.inventory[key].item = Item(self.world, self.name, self.world.blocks_img[self.name], self.have_hitbox) self.world.game.player.inventory[key].count = 1 return
JavaScript
UTF-8
4,154
3.0625
3
[]
no_license
$(function(){ // 封好请求1分页数据的接口 function getpostbypagination(currentPage,pageSize,category_id,status){ $.ajax({ type: "post", url: "/getPostsByPagination", data: { currentPage,pageSize,category_id,status },// 这里需要传递两个参数,一个是当前是第几页,每页显示多少条, success: function (res) { console.log(res); if(res.code == 1){ let html = template("tp",res.data); $('tbody').html(html); // 数据回来之后,才能生成分页按钮 initPagination(currentPage,res.pageMax); } } }); }; //一开始加载页面就把文字的列表显示出来 getpostbypagination(1,10,'all','all'); //封装好的生成分页按钮的结构的方法 function initPagination(currentPage,pageMax){ // 总共显示的按钮数 let buttonCount = 5; // 算出开始位置 let start = currentPage - Math.floor(buttonCount / 2); if(start <= 1){ start = 1; } // 算出结束的位置 ,不是根据当前算出的 let end = start + (buttonCount - 1); // 开始位置有最小,请问,结束位置是否有最大? 肯定有最大位置,但是这个最大位置,不是一定的,而是必须从服务端,计算回来的 if(end >= pageMax){ end = pageMax; // 此时有能会造成,前面的按钮个数不够 ,需要重新计算开始的页码 start = end - (buttonCount - 1); // 重新计算了开始位置之后,还是可能导致开始页码小于等于1,还是需要重新设定 if(start <=1){ start = 1; } } let html = ""; // 当当前页不是第一页,就有上一页 if(currentPage != 1){ html += `<li><a data-index="${currentPage-1}" href="javascript:void(0);">上一页</a></li>` } // 根据开头结尾生成结构 for(let i = start; i <= end; i++){ html += `<li><a data-index="${i}" href="javascript:void(0);">${i}</a></li>`; } // 当前页不是最后一页,就还有下一页 if(currentPage != pageMax){ html += `<li><a data-index="${currentPage+1}" href="javascript:void(0);">下一页</a></li>` } // 把累加好的结构,放到ul里面 $('.pagination').html(html); } // 也要使用委托的方式注册 $(".pagination").on('click','a',function(){ // 根据当前点击的按钮,得到对应要切换的页码 // 我们在生成结构的时候,使用了一个自定义属性 data-index 存储了这个a标签对应的页码数,只要得到这个a标签的自定义属性即可 let index= parseInt($(this).attr('data-index')); let category_id = $("#category_id").val(); let status = $("#status").val(); // 根据页码请求数据 getpostbypagination(index,10,category_id,status); }); /// 动态的加载所有的分类 $.ajax({ type: "post", url: "/getAllCategories", success: function (res) { console.log(res.data); if(res.code == 1){ // 把动态获取的分类,生成下拉框 let html = `<option value="all">所有分类</option>`; for(let i = 0; i < res.data.length; i++){ html += `<option value="${res.data[i].id}">${res.data[i].name}</option>` } $("#category_id").html(html); } } }); // 点击筛选按钮 $("#filter").on('click',function(){ // 根据已经选好的条件,把这些筛选的条件,发送到服务器,筛选出数据 let category_id = $("#category_id").val(); let status = $("#status").val(); console.log(category_id,status); // 获取了筛选的条件,把筛选的条件发送回服务端即可 getpostbypagination(1,10,category_id,status); }); })
Java
UTF-8
6,003
2.671875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Teamjava.Library; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author tyler */ public class CirculationTest { public CirculationTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSomeMethod() { // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setBookFileName method, of class Circulation. */ @Test public void testSetBookFileName() { System.out.println("setBookFileName"); String file = ""; Circulation instance = new Circulation(); instance.setBookFileName(file); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of checkOut method, of class Circulation. */ @Test public void testCheckOut() { System.out.println("checkOut"); String bTitle = ""; String pName = ""; Circulation instance = new Circulation(); instance.checkOut(bTitle, pName); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of checkIn method, of class Circulation. */ @Test public void testCheckIn() { System.out.println("checkIn"); String bTitle = ""; String pName = ""; Circulation instance = new Circulation(); instance.checkIn(bTitle, pName); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of listOverdueBooks method, of class Circulation. */ @Test public void testListOverdueBooks() { System.out.println("listOverdueBooks"); Circulation instance = new Circulation(); List expResult = null; List result = instance.listOverdueBooks(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of listCheckedOutByPatron method, of class Circulation. */ @Test public void testListCheckedOutByPatron() { System.out.println("listCheckedOutByPatron"); String pName = ""; Circulation instance = new Circulation(); List expResult = null; List result = instance.listCheckedOutByPatron(pName); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of listAllBooks method, of class Circulation. */ @Test public void testListAllBooks() { System.out.println("listAllBooks"); Circulation instance = new Circulation(); List expResult = null; List result = instance.listAllBooks(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of booksAvailableToPatron method, of class Circulation. */ @Test public void testBooksAvailableToPatron() { System.out.println("booksAvailableToPatron"); String pName = ""; Circulation instance = new Circulation(); List expResult = null; List result = instance.booksAvailableToPatron(pName); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of Exit method, of class Circulation. */ @Test public void testExit() { System.out.println("Exit"); Circulation instance = new Circulation(); instance.Exit(); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of printStatus method, of class Circulation. */ @Test public void testPrintStatus() { System.out.println("printStatus"); Circulation instance = new Circulation(); String expResult = ""; String result = instance.printStatus(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of printCurrentDate method, of class Circulation. */ @Test public void testPrintCurrentDate() { System.out.println("printCurrentDate"); Circulation instance = new Circulation(); String expResult = ""; String result = instance.printCurrentDate(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of advanceOneDay method, of class Circulation. */ @Test public void testAdvanceOneDay() { System.out.println("advanceOneDay"); Circulation instance = new Circulation(); instance.advanceOneDay(); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
Java
UTF-8
1,189
2.3125
2
[ "Apache-2.0" ]
permissive
package openfoodfacts.github.scrachx.openfood.models; import android.util.Log; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.ArrayList; import java.util.List; import openfoodfacts.github.scrachx.openfood.network.deserializers.IngredientsWrapperDeserializer; /** * JSON from URL https://ssl-api.openfoodfacts.org/data/taxonomies/ingredients.json * * @author dobriseb 2018-12-21 inspired by AllergensWrapper */ @JsonDeserialize(using = IngredientsWrapperDeserializer.class) public class IngredientsWrapper { private List<IngredientResponse> ingredients; /** * @return A list of Ingredient objects */ public List<Ingredient> map() { Log.i("INFO", "IngredientWrapper.map()"); List<Ingredient> entityIngredients = new ArrayList<>(); for (IngredientResponse ingredient : ingredients) { entityIngredients.add(ingredient.map()); } return entityIngredients; } public void setIngredients(List<IngredientResponse> ingredients) { this.ingredients = ingredients; } public List<IngredientResponse> getIngredients() { return ingredients; } }
TypeScript
UTF-8
324
2.515625
3
[]
no_license
import { hash } from 'bcrypt'; import { randomBytes } from 'crypto'; export const hashPassword = (password: string): Promise<string> => hash(password, 10); export const generateRandomToken = (): Promise<string> => new Promise((resolve) => randomBytes(64, (err, buffer) => resolve(buffer.toString('base64'))), );
Java
UTF-8
1,156
2.390625
2
[ "MIT" ]
permissive
package com.github.hisener.timetracker.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import java.time.Instant; @Document public class TimeLog { @Id private String id; @NotBlank private String description; private Instant dateTime; @Min(1) private Long timeSpent; public String getId() { return id; } public TimeLog setId(String id) { this.id = id; return this; } public String getDescription() { return description; } public TimeLog setDescription(String description) { this.description = description; return this; } public Instant getDateTime() { return dateTime; } public TimeLog setDateTime(Instant dateTime) { this.dateTime = dateTime; return this; } public Long getTimeSpent() { return timeSpent; } public TimeLog setTimeSpent(Long timeSpent) { this.timeSpent = timeSpent; return this; } }
Java
WINDOWS-1252
1,046
3.171875
3
[]
no_license
package ǰ; import java.util.*; public class Solution3 { public List<Integer> preorderTraversal(TreeNode root) { LinkedList<Integer> output = new LinkedList<>(); TreeNode node = root; while(node!=null) { if(node.left == null) { output.add(node.val); node = node.right; } else { TreeNode predcessor = node.left; while((predcessor.right!=null)&&(predcessor.right!=node)) { predcessor = predcessor.right; } if(predcessor.right==null) { output.add(node.val); predcessor.right = node; node = node.left; } else { predcessor.right = null; node = node.right; } } } return output; } }
Python
UTF-8
2,491
2.765625
3
[]
no_license
import imutils import cv2 from keras.models import load_model import numpy as np from imutils.video import VideoStream import time def get_labels(dataset_name): if dataset_name == 'fer2013': return {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy', 4: 'sad', 5: 'surprise', 6: 'neutral'} elif dataset_name == 'imdb': return {0: 'woman', 1: 'man'} elif dataset_name == 'KDEF': return {0: 'AN', 1: 'DI', 2: 'AF', 3: 'HA', 4: 'SA', 5: 'SU', 6: 'NE'} else: raise Exception('Invalid dataset name') def draw_text(coordinates, image_array, text, color, x_offset=0, y_offset=0, font_scale=2, thickness=2): x, y = coordinates[:2] cv2.putText(image_array, text, (x + x_offset, y + y_offset), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness, cv2.LINE_AA) def draw_bounding_box(face_coordinates, image_array, color): x, y, w, h = face_coordinates cv2.rectangle(image_array, (x, y), (x + w, y + h), color, 2) def apply_offsets(face_coordinates, offsets): x, y, width, height = face_coordinates x_off, y_off = offsets return (x - x_off, x + width + x_off, y - y_off, y + height + y_off) def load_detection_model(prototxt, weights): detection_model = cv2.dnn.readNetFromCaffe(prototxt, weights) return detection_model def detect_faces(detection_model, gray_image_array, conf): frame = gray_image_array # Grab frame dimention and convert to blob (h,w) = frame.shape[:2] # Preprocess input image: mean subtraction, normalization blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # Set read image as input to model detection_model.setInput(blob) # Run forward pass on model. Receive output of shape (1,1,no_of_predictions, 7) predictions = detection_model.forward() coord_list = [] for i in range(0, predictions.shape[2]): confidence = predictions[0,0,i,2] if confidence > conf: # Find box coordinates rescaled to original image box_coord = predictions[0,0,i,3:7] * np.array([w,h,w,h]) conf_text = '{:.2f}'.format(confidence) # Find output coordinates xmin, ymin, xmax, ymax = box_coord.astype('int') coord_list.append([xmin, ymin, (xmax-xmin), (ymax-ymin)]) print('Coordinate list:', coord_list) return coord_list
Markdown
UTF-8
14,666
2.609375
3
[]
no_license
<link href="../../css/style.css" rel="stylesheet" type="text/css" /> # 《张中丞传后叙》 <span class="r">唐 · 韩愈 <div class="p"> 元和二年四月十三日夜,愈与吴郡张籍阅家中旧书,得李翰所为《张巡传》。翰以文章自名,为此传颇详密。然尚恨有阙(quē)者:不为许远立传,又不载雷万春事首尾。 <span class="comment"> 张中丞:即张巡(—年),中丞,张巡驻守睢阳时朝廷所加的官衔。 元和二年:公元八〇七年元和,唐宪宗李纯的年号(—年)。 张籍(约—约年):字文昌,吴郡(治所在今江苏省苏州市)人,唐代著名诗人,韩愈学生。 李翰:字子羽,赵州赞皇(今河北省元氏县)人,官至翰林学士。 以文章自名:《旧唐书·文苑传》:翰“为文精密,用思苦涩”。自名,自许。 许远(—年):字令威,杭州盐官(今浙江省海宁县)人。 雷万春:张巡部下勇将。 </span> <div class="translation"> 元和二年四月十三日晚上,我和吴郡张籍翻阅家中的旧书,发现了李翰所写的《张巡传》。李翰因文章而自负,写这篇传记十分详密。但遗憾的是还有缺陷:没有为许远立传,又没有记载雷万春事迹的始末。 </div> 远虽材若不及巡者,开门纳巡,位本在巡上。授之柄而处其下,无所疑忌,竟与巡俱守死,成功名,城陷而虏,与巡死先后异耳。 两家子弟材智下,不能通知二父志,以为巡死而远就虏,疑畏死而辞服于贼。 远诚畏死,何苦守尺寸之地,食其所爱之肉,以与贼抗而不降乎?当其围守时,外无蚍(pí)蜉(fú)蚁子之援,所欲忠者,国与主耳,而贼语以国亡主灭。 远见救援不至,而贼来益众,必以其言为信;外无待而犹死守,人相食且尽,虽愚人亦能数日而知死所矣。远之不畏死亦明矣!乌有城坏其徒俱死,独蒙愧耻求活?虽至愚者不忍为,呜呼!而谓远之贤而为之邪? <span class="comment"> 开门纳巡:肃宗至德二载(年)正月,叛军安庆绪部将尹子奇带兵十三万围睢阳,许远向张巡告急,张巡自宁陵率军入睢阳城(见《资治通鉴》卷二一九)。 柄:权柄。 城陷而虏二句:此年十月,睢阳陷落,张巡、许远被虏。张巡与部将被斩,许远被送往洛阳邀功。 两家句:据《新唐书·许远传》载,安史乱平定后,大历年间,张巡之子张去疾轻信小人挑拨,上书代宗,谓城破后张巡等被害,惟许远独存,是屈降叛军,请追夺许远官爵。诏令去疾与许远之子许岘及百官议此事。两家子弟即指张去疾、许岘。 通知:通晓。 食其句:尹子奇围睢阳时,城中粮尽,军民以雀鼠为食,最后只得以妇女与老弱男子充饥。当时,张巡曾杀爱妾、许远曾杀奴仆以充军粮。 蚍蜉:黑色大蚁。蚁子:幼蚁。 而贼句:安史乱时,长安、洛阳陷落,玄宗逃往西蜀,唐室岌岌可危。 外无待:睢阳被围后,河南节度使贺兰进明等皆拥兵观望,不来相救。 </span> <div class="translation"> 许远虽然才能似乎比不上张巡,打开城门迎接张巡,地位本在张巡之上。他把指挥权交给张巡,甘居于其下,毫无猜疑妒忌,最终和张巡一起守城而死,成就了功名,城破后被俘,不过和张巡死的时间有先后的不同罢了。 张、许两家的子弟才智低下,不能了解其父辈的志向,认为张巡战死而许远被俘,怀疑许远是怕死而投降了叛军。 如果许远真的怕死,何苦守住这尺寸大小的地盘,以他所爱之人的肉充饥,来和叛军对垒而不投降呢?当他在包围中守城时,外面没有一点哪怕极为微弱的援助,所要效忠的,就是国家和皇上,而叛军会拿国家和皇上已被消灭的情况告诉他。 许远见救兵不来,而叛军越来越多,一定会相信他们的话;外面毫无希望却仍然死守,军民相食,人越来越少,即使是傻瓜也会计算日期而知道自己的死所了。许远不怕死也可以清楚了!哪有城破而自己的部下都已战死,他却偏偏蒙受耻辱苟且偷生?即使再笨的人也不愿这样做,唉!难道说像许远如此贤明的人会这样做吗? </div> 说者又谓远与巡分城而守,城之陷,自远所分始。以此诟(gòu)远,此又与儿童之见无异。 人之将死,其藏腑必有先受其病者;引绳而绝之,其绝必有处。 观者见其然,从而尤之,其亦不达于理矣!小人之好议论,不乐成人之美,如是哉!如巡、远之所成就,如此卓卓,犹不得免,其他则又何说! <span class="comment"> 说者句:张巡和许远分兵守城,张守东北,许守西南。城破时叛军先从西南处攻入,故有此说。 </span> <div class="translation"> 议论的人又认为许远和张巡分守城门,城陷落是从许远分守的西南方开始的。拿这个理由来诽谤许远,这又和小孩的见识没有两样。 人将要死的时候,他的内脏必定有一个先受到侵害的地方;扯紧绳子,把它拉断,绳断必定有一个先裂的地方。 有人看到这种情况,就来责怪这个先受侵害和先裂的地步,他也太不通达事理了!小人喜欢议论,不愿成人之美,竟到了这样的地步!像张巡、许远所造成的功业,如此杰出,尚且躲不掉小人的诽谤,其他人还有什么可说呢! </div> 当二公之初守也,宁能知人之卒不救,弃城而逆遁?苟此不能守,虽避之他处何益?及其无救而且穷也,将其创残饿羸(léi)之余,虽欲去,必不达。 二公之贤,其讲之精矣!守一城,捍天下,以千百就尽之卒,战百万日滋之师,蔽遮江淮,沮(jǔ)遏(è)其势,天下之不亡,其谁之功也! 当是时,弃城而图存者,不可一二数;擅强兵坐而观者,相环也。不追议此,而责二公以死守,亦见其自比于逆乱,设淫辞而助之攻也。 <span class="comment"> 羸:瘦弱。 二公二句:谓二公功绩前人已有精当的评价。此指李翰《进张中丞传表》所云:“巡退军睢阳,扼其咽领,前后拒守,自春徂冬,大战数十,小战数百,以少击众,以弱击强,出奇无穷,制胜如神,杀其凶丑九十余万。贼所以不敢越睢阳而取江淮,江淮所以保全者,巡之力也。” 沮遏:阻止。 </span> <div class="translation"> 当张、许二位刚守城的时候,哪能知道别人终不相救,从而预先弃城逃走呢?如果睢阳城守不住,即使逃到其他地方又有什么用处?等到没有救兵而且走投无路的时候,率领着那些受伤残废、饥饿瘦弱的残兵,即使想逃走,也一定无法到达要去的地方。 张、许二位的功绩,他们已经考虑得很周到了!守住孤城,捍卫天下,仅凭千百个濒临灭亡的士兵,来对付近百万天天增加的敌军,保护着江淮地区,挡住了叛军的攻势,天下能够不亡,这是谁的功劳啊! 在那个时候,丢掉城池而只想保全性命的人,不在少数;拥有强兵却安坐观望的人,一个接着一个。不追究讨论这些,却拿死守睢阳来责备张、许二位,也可见这些人把自己放在与逆乱者同类的地位,捏造谎言来帮他们一起攻击有功之人了。 </div> 愈尝从事于汴徐二府,屡道于两府间,亲祭于其所谓双庙者。其老人往往说巡、远时事云:南霁(jì)云之乞救于贺兰也,贺兰嫉巡、远之声威功绩出己上,不肯出师救;爱霁云之勇且壮,不听其语,强留之,具食与乐,延霁云坐。 霁云慷慨语曰:“云来时,睢(suī)阳之人,不食月余日矣!云虽欲独食,义不忍;虽食,且不下咽!” 因拔所佩刀,断一指,血淋漓,以示贺兰。一座大惊,皆感激为云泣下。 云知贺兰终无为云出师意,即驰去;将出城,抽矢射佛寺浮图,矢着其上砖半箭,曰:“吾归破贼,必灭贺兰!此矢所以志也。” 愈贞元中过泗州,船上人犹指以相语。城陷,贼以刃胁降巡,巡不屈,即牵去,将斩之;又降霁云,云未应。巡呼云曰:“南八,男儿死耳,不可为不义屈!”云笑曰:“欲将以有为也;公有言,云敢不死!”即不屈。 <span class="comment"> 愈尝句:韩愈曾先后在汴州(治所在今河南省开封市)、徐州(治所在今江苏省徐州市)任推官之职。唐称幕僚为从事。 双庙:张巡、许远死后,后人在睢阳立庙祭祀,称为双庙。 南霁云(?一年):魏州顿丘(今河南省清丰县西南)人。安禄山反叛,被遣至睢阳与张巡议事,为张所感,遂留为部将。 贺兰:复姓,指贺兰进明。时为御史大夫、河南节度使,驻节于临淮一带。 贞元:唐德宗李适年号(—年)、泗州:唐属河南道,州治在临淮(今江苏省泗洪县东南),当年贺兰屯兵于此。 南八:南霁云排行第八,故称。 </span> <div class="translation"> 我曾经在汴州、徐州任职,多次经过两州之间,亲自在那叫做双庙的地方祭祀张巡和许远。那里的老人常常说起张巡、许远时候的事情:南霁云向贺兰进明求救的时候,贺兰进明妒忌张巡、许远的威望和功劳超过自己,不肯派兵相救;但看中了南霁云的勇敢和壮伟,不采纳他的话,却勉力挽留他,还准备了酒食和音乐,请南霁云入座。 南霁云义气激昂说:“我来的时候,睢阳军民已经一个多月没有东西吃了!我即使想一个人享受,道义不能允许;即使吃了,我也难以下咽!” 于是拔出自己的佩刀,砍断一个手指,鲜血淋漓,拿给贺兰进明看。在座的人大吃一惊,都感动得为南霁云流下了眼泪。 南霁云知道贺兰进明终究没有为自己出兵的意思,立即骑马离去;将出城时,他抽出箭射寺庙的佛塔,那枝箭射进佛塔砖面半箭之深,说:“我回去打败叛军后,一定要消灭贺兰进明!就用这枝箭来作为标记。” 我于贞元年间经过泗州,船上的人还指点着说给我听。城破后,叛军拿刀逼张巡投降,张巡坚贞不屈,马上被绑走,准备杀掉;叛军又叫南霁云投降,南霁云没有吱声。张巡叫南霁云道:“南八,男子汉一死而已,不能向不义之人屈服!” 南霁云笑道:“我本想有所作为;您既然这样说,我哪敢不死!”于是誓不投降。 </div> 张籍曰:“有于嵩者,少依于巡;及巡起事,嵩常在围中。籍大历中于和州乌江县见嵩,嵩时年六十余矣。以巡初尝得临涣县尉,好学无所不读。籍时尚小,粗问巡、远事,不能细也。云:巡长七尺余,须髯若神。尝见嵩读《汉书》,谓嵩曰:“何为久读此?“ 嵩曰:“未熟也。“ 巡曰:“吾于书读不过三遍,终身不忘也。“因诵嵩所读书,尽卷不错一字。嵩惊,以为巡偶熟此卷,因乱抽他帙(zhì)以试,无不尽然。嵩又取架上诸书试以问巡,巡应口诵无疑。 嵩从巡久,亦不见巡常读书也。为文章,操纸笔立书,未尝起草。初守睢阳时,士卒仅万人,城中居人户,亦且数万,巡因一见问姓名,其后无不识者。巡怒,须髯辄张。及城陷,贼缚巡等数十人坐,且将戮。巡起旋,其众见巡起,或起或泣。 巡曰:“汝勿怖!死,命也。“ 众泣不能仰视。巡就戮时,颜色不乱,阳阳如平常。 远宽厚长者,貌如其心;与巡同年生,月日后于巡,呼巡为兄,死时年四十九。” 嵩贞元初死于亳宋间。或传嵩有田在亳(bó)宋间,武人夺而有之,嵩将诣州讼理,为所杀。嵩无子。张籍云。 <span class="comment"> 常:通“尝”,曾经。 大历:唐代宗李豫年号(—年)。和州乌江县:在今安徽省和县东北。 以巡句:张巡死后,朝廷封赏他的亲戚、部下,于嵩因此得官。 临涣:故城在今安徽省宿县西南。 帙:书套,也指书本。 仅:几乎。 亳:亳州,治所在今安徽省亳县。 宋:宋州,治所在睢阳。 </span> <div class="translation"> 张籍说:“有一个人叫于嵩,年轻时跟随张巡;等到张巡起兵抗击叛军,于嵩曾在围城之中。我大历年间在和州乌江县见到过于嵩,那时他已六十多岁了。因为张巡的缘故起先曾得到临涣县尉的官职,学习努力,无所不读。我那时还幼小,简单地询问过张巡、许远的事迹,不太详细。 他说:张巡身长七尺有余,一口胡须活像神灵。他曾经看见于嵩在读《汉书》,就对于嵩说:“你怎么老是在读这本书?“ 于嵩说:“没有读熟呀。“ 张巡说:“我读书不超过三遍,一辈子不会忘记。“就背诵于嵩所读的书,一卷背完不错一个字。 于嵩很惊奇,以为张巡是碰巧熟悉这一卷,就随便抽出一卷来试他,他都像刚才那样能背诵出来。于嵩又拿书架上其他书来试问张巡,张巡随口应声都背得一字不错。 于嵩跟张巡时间较久,也不见张巡经常读书。写起文章来,拿起纸笔一挥而就,从来不打草稿。起先守睢阳时,士兵将近万把人,城里居住的人家,也将近几万,张巡只要见一次问过姓名,以后没有不认识的。张巡发起怒来,胡须都会竖起。等到城破后,叛军绑住张巡等几十人让他们坐着,立即就要处死。张巡起身去小便(另说此处为”转身“),他的部下见他起身,有的跟着站起,有的哭了起来。 张巡说:“你们不要害怕!死是命中注定的。“ 大家都哭得不忍抬头看他。张巡被杀时,脸色毫不慌张,神态安详,就和平日一样。 许远是个宽厚的长者,相貌也和他的内心一样;和张巡同年出生,但时间比张巡稍晚,称张巡为兄,死时四十九岁。” 于嵩在贞元初年死在亳宋一带。有人传说他在那里有块田地,武人把它强夺霸占了,于嵩打算到州里提出诉讼,却被武人杀死。于嵩没有后代。这些都是张籍告诉我的。 </div>
C++
UTF-8
441
2.8125
3
[]
no_license
#ifndef Student_H #define Student_H #include <iostream> #include <string> #include "Course.h" using namespace std; const int MAXNUM = 20; class Student { public: Student(string nm, string no); string GetStuName(); string GetStuNumber(); void AssignGrade(string co, int gr); int GetGrade(string co); float FindAveGrade(); private: string name; string number; Course course_grades[MAXNUM]; int no_of_courses; }; #endif
Java
UTF-8
6,911
2.1875
2
[]
no_license
package at.wiencampus.se.apigateway.service; import at.wiencampus.se.common.dto.*; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.header.internals.RecordHeader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.requestreply.ReplyingKafkaTemplate; import org.springframework.kafka.requestreply.RequestReplyFuture; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.stereotype.Service; import java.util.List; @Service public class VehicleService { @Autowired private ReplyingKafkaTemplate<String, VehicleServiceRequest, VehicleServiceReply> requestReplyKafkaTemplate; @Value("${kafka.vehicle.topic.book.request}") public String REQUEST_TOPIC_BOOK; @Value("${kafka.vehicle.topic.book.reply}") public String REPLY_TOPIC_BOOK; @Value("${kafka.vehicle.topic.return.request}") public String REQUEST_TOPIC_RETURN; @Value("${kafka.vehicle.topic.return.reply}") public String REPLY_TOPIC_RETURN; @Value("${kafka.vehicle.topic.all.request}") public String REQUEST_TOPIC_ALL_VEHICLE; @Value("${kafka.vehicle.topic.all.reply}") public String REPLY_TOPIC_ALL_VEHICLE; @Value("${kafka.vehicle.topic.all_with_currency.request}") public String REQUEST_TOPIC_ALL_VEHICLE_WITH_CURRENCY; @Value("${kafka.vehicle.topic.all_with_currency.reply}") public String REPLY_TOPIC_ALL_VEHICLE_WITH_CURRENCY; @Value("${kafka.vehicle.topic.all_customer_rentals.request}") public String REQUEST_TOPIC_ALL_CUSTOMER_RENTALS; @Value("${kafka.vehicle.topic.all_customer_rentals.reply}") public String REPLY_TOPIC_ALL_CUSTOMER_RENTALS; @Value("${kafka.vehicle.topic.new.request}") public String REQUEST_TOPIC_NEW_VEHICLE; @Value("${kafka.vehicle.topic.new.reply}") public String REPLY_TOPIC_NEW_VEHICLE; public VehicleData createNew(VehicleData vehicle) { VehicleServiceRequest request = new VehicleServiceRequest(); request.setName(VehicleServiceName.NewVehicle); request.setVehicle(vehicle); //call MService VehicleServiceReply reply = sendAndReceive(request, REQUEST_TOPIC_NEW_VEHICLE, REPLY_TOPIC_NEW_VEHICLE); if (reply.getName() == VehicleServiceName.NewVehicle) { return reply.getVehicle(); } else { throw new UnsupportedOperationException("Response Type is wrong! (" + reply.getName() + ")"); } } public CustomerRentalData createVehicleRental(CustomerRentalData newCustomerRental) { VehicleServiceRequest request = new VehicleServiceRequest(); request.setName(VehicleServiceName.Book); request.setCustomerRental(newCustomerRental); //call MService VehicleServiceReply reply = sendAndReceive(request, REQUEST_TOPIC_BOOK, REPLY_TOPIC_BOOK); if (reply.getName() == VehicleServiceName.Book) { return reply.getCustomerRental(); } else { throw new UnsupportedOperationException("Response Type is wrong! (" + reply.getName() + ")"); } } public boolean returnRentalCar(String rentalId) { VehicleServiceRequest request = new VehicleServiceRequest(); request.setName(VehicleServiceName.Return); request.setRentalId(rentalId); //call MService VehicleServiceReply reply = sendAndReceive(request, REQUEST_TOPIC_RETURN, REPLY_TOPIC_RETURN); if (reply.getName() == VehicleServiceName.Return) { return reply.getIsReturned(); } else { throw new UnsupportedOperationException("Response Type is wrong! (" + reply.getName() + ")"); } } public List<VehicleData> getAllVehicles() { VehicleServiceRequest request = new VehicleServiceRequest(); request.setName(VehicleServiceName.AllVehicles); request.setCurrency(null); request.setCustomerId(null); request.setCustomerRental(null); request.setVehicle(null); request.setRentalId(null); //call MService VehicleServiceReply reply = sendAndReceive(request, REQUEST_TOPIC_ALL_VEHICLE, REPLY_TOPIC_ALL_VEHICLE); if (reply.getName() == VehicleServiceName.AllVehicles) { return reply.getVehicles(); } else { throw new UnsupportedOperationException("Response Type is wrong! (" + reply.getName() + ")"); } } public List<CustomerRentalData> getAllCustomerRentalForCustomer(String customerId) { VehicleServiceRequest request = new VehicleServiceRequest(); request.setName(VehicleServiceName.AllCustomerRentals); request.setCustomerId(customerId); //call MService VehicleServiceReply reply = sendAndReceive(request, REQUEST_TOPIC_ALL_CUSTOMER_RENTALS, REPLY_TOPIC_ALL_CUSTOMER_RENTALS); if (reply.getName() == VehicleServiceName.AllCustomerRentals) { return reply.getCustomerRentals(); } else { throw new UnsupportedOperationException("Response Type is wrong! (" + reply.getName() + ")"); } } public List<VehicleData> getAllVehicleForCurrency(String currency) { VehicleServiceRequest request = new VehicleServiceRequest(); request.setName(VehicleServiceName.AllVehiclesForCurrency); request.setCurrency(currency); //call MService VehicleServiceReply reply = sendAndReceive(request, REQUEST_TOPIC_ALL_VEHICLE_WITH_CURRENCY, REPLY_TOPIC_ALL_VEHICLE_WITH_CURRENCY); if (reply.getName() == VehicleServiceName.AllVehiclesForCurrency) { return reply.getVehicles(); } else { throw new UnsupportedOperationException("Response Type is wrong! (" + reply.getName() + ")"); } } private VehicleServiceReply sendAndReceive(VehicleServiceRequest request, String requestTopic, String replyTopic) { try { ProducerRecord<String, VehicleServiceRequest> record = new ProducerRecord<String, VehicleServiceRequest>(requestTopic, request); record.headers().add(new RecordHeader(KafkaHeaders.REPLY_TOPIC, replyTopic.getBytes())); RequestReplyFuture<String, VehicleServiceRequest, VehicleServiceReply> sendAndReceive = requestReplyKafkaTemplate.sendAndReceive(record); ConsumerRecord<String, VehicleServiceReply> consumerRecord = sendAndReceive.get(); VehicleServiceReply reply = consumerRecord.value(); if(reply.getException() != null) { throw new RuntimeException("Exception in the VehicleService!", reply.getException()); } return reply; } catch (Exception e) { throw new RuntimeException("sendAndReceive() Failed!", e); } } }
Java
UTF-8
751
2.84375
3
[]
no_license
package NC; public class NC24 { public class ListNode { int val; ListNode next = null; public ListNode(int i) { this.val =i; } } public ListNode deleteDuplicates (ListNode head) { // write code here ListNode dummy=new ListNode(0); dummy.next=head; ListNode pre=dummy; ListNode p=head; while(p!=null&&p.next!=null){ if(p.val==p.next.val){ while(p.next!=null&&p.val==p.next.val){ p=p.next; } pre.next=p.next; p=p.next; } else{ pre=p; p=p.next; } } return dummy.next; } }
C++
UTF-8
645
3.3125
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
#pragma once namespace Blah { enum class Endian { Little, Big }; template<class T> inline void swap_endian(T* value) { for (int i = 0; i < sizeof(T) / 2; i++) { char* _ptr = (char*)&value; char _temp = *(_ptr + i); *(_ptr + i) = *(_ptr + sizeof(T) - i - 1); *(_ptr + sizeof(T) - i - 1) = _temp; } } inline bool is_big_endian() { return (*((short*)"AB") == 0x4243); } inline bool is_little_endian() { return (*((short*)"AB") != 0x4243); } inline bool is_endian(const Endian& endian) { return (endian == Endian::Little && is_little_endian()) || (endian == Endian::Big && is_big_endian()); } }
C#
UTF-8
1,605
3
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncShark.Engine.FileSystem.InMemory { public class DirectoryInfoInMemoryFactory { public DirectoryInfoInMemory GetInstance(string fullName) { if (!Directory.Exists(fullName)) { throw new ArgumentException("fullName must represent a directory that exists!"); } var directoryInfoFacade = new DirectoryInfoFacade(new DirectoryInfo(fullName)); var directoryInfo = new DirectoryInfoInMemory(directoryInfoFacade); Build(directoryInfo); return directoryInfo; } private void Build(DirectoryInfoInMemory directoryInfo) { foreach (var subDirectoryPath in Directory.EnumerateDirectories(directoryInfo.FullName, "*.*", SearchOption.TopDirectoryOnly)) { var subDirectoryInfoFacade = new DirectoryInfoFacade(new DirectoryInfo(subDirectoryPath)); var subDirectoryInfo = new DirectoryInfoInMemory(subDirectoryInfoFacade); Build(subDirectoryInfo); directoryInfo.DirectoryInfos.Add(subDirectoryInfo); } foreach (var filePath in Directory.EnumerateFiles(directoryInfo.FullName, "*.*", SearchOption.TopDirectoryOnly)) { var fileInfoFacade = new FileInfoFacade(new FileInfo(filePath)); var fileInfo = new FileInfoInMemory(fileInfoFacade); } } } }
Python
UTF-8
3,141
2.546875
3
[ "Python-2.0", "CC-BY-4.0", "MIT" ]
permissive
"""test script for a few new invalid token catches""" import sys from test import support from test.support import os_helper from test.support import script_helper import unittest # TODO: RUSTPYTHON @unittest.expectedFailure class EOFTestCase(unittest.TestCase): def test_EOF_single_quote(self): expect = "unterminated string literal (detected at line 1) (<string>, line 1)" for quote in ("'", "\""): try: eval(f"""{quote}this is a test\ """) except SyntaxError as msg: self.assertEqual(str(msg), expect) self.assertEqual(msg.offset, 1) else: raise support.TestFailed def test_EOFS(self): expect = ("unterminated triple-quoted string literal (detected at line 1) (<string>, line 1)") try: eval("""'''this is a test""") except SyntaxError as msg: self.assertEqual(str(msg), expect) self.assertEqual(msg.offset, 1) else: raise support.TestFailed def test_EOFS_with_file(self): expect = ("(<string>, line 1)") with os_helper.temp_dir() as temp_dir: file_name = script_helper.make_script(temp_dir, 'foo', """'''this is \na \ntest""") rc, out, err = script_helper.assert_python_failure(file_name) self.assertIn(b'unterminated triple-quoted string literal (detected at line 3)', err) def test_eof_with_line_continuation(self): expect = "unexpected EOF while parsing (<string>, line 1)" try: compile('"\\xhh" \\', '<string>', 'exec', dont_inherit=True) except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise support.TestFailed def test_line_continuation_EOF(self): """A continuation at the end of input must be an error; bpo2180.""" expect = 'unexpected EOF while parsing (<string>, line 1)' with self.assertRaises(SyntaxError) as excinfo: exec('x = 5\\') self.assertEqual(str(excinfo.exception), expect) with self.assertRaises(SyntaxError) as excinfo: exec('\\') self.assertEqual(str(excinfo.exception), expect) @unittest.skipIf(not sys.executable, "sys.executable required") def test_line_continuation_EOF_from_file_bpo2180(self): """Ensure tok_nextc() does not add too many ending newlines.""" with os_helper.temp_dir() as temp_dir: file_name = script_helper.make_script(temp_dir, 'foo', '\\') rc, out, err = script_helper.assert_python_failure(file_name) self.assertIn(b'unexpected EOF while parsing', err) self.assertIn(b'line 1', err) self.assertIn(b'\\', err) file_name = script_helper.make_script(temp_dir, 'foo', 'y = 6\\') rc, out, err = script_helper.assert_python_failure(file_name) self.assertIn(b'unexpected EOF while parsing', err) self.assertIn(b'line 1', err) self.assertIn(b'y = 6\\', err) if __name__ == "__main__": unittest.main()
C#
UTF-8
514
2.734375
3
[]
no_license
using System.ComponentModel; namespace Converter_1_.VIewModel { public abstract class ViewModelBase:INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } }
Markdown
UTF-8
931
3.71875
4
[ "MIT" ]
permissive
938\. Range Sum of BST Easy Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** ![](https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg) **Input:** root = [10,5,15,3,7,null,18], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32. **Example 2:** ![](https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg) **Input:** root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range <code>[1, 2 * 10<sup>4</sup>]</code>. * <code>1 <= Node.val <= 10<sup>5</sup></code> * <code>1 <= low <= high <= 10<sup>5</sup></code> * All `Node.val` are **unique**.
C#
UTF-8
2,618
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BusinessAccessLayer; namespace PresentationLayer { public partial class StudentRegistration : Form { private StudentDetails stdDetails; public StudentRegistration() { InitializeComponent(); } public StudentRegistration(StudentDetails stdDetails, int ID) { InitializeComponent(); this.stdDetails = stdDetails; idValueLabel.Text = ID.ToString(); } private void nameLabel_Click(object sender, EventArgs e) { } // cancel clears the entered value and closing the registration form by displaying // student details form without adding any data private void cancelBtn_Click(object sender, EventArgs e) { nameTextBox.Clear(); activeCheckBox.Checked = false; gpaTextBox.Clear(); this.Close(); stdDetails.Show(); } // Ok button click adds the registration form data to the datagridview as a new row // by adding new row to the existing data grid view data private void okBtn_Click(object sender, EventArgs e) { DataTable dt = stdDetails.studentDetailsGridView.DataSource as DataTable; dt.Rows.Add(idValueLabel.Text, nameTextBox.Text, dateTimePicker.Value, gpaTextBox.Text, activeCheckBox.Checked); this.Close(); stdDetails.Show(); } // GPA text box validates the numeric field // And also checks whether the inserted GPA is valid data. private void gpaTextBox_Validating(object sender, CancelEventArgs e) { decimal num; if (decimal.TryParse(gpaTextBox.Text, out num)) { int integer_part = (int)Decimal.Truncate(num).ToString().Length; bool val = decimal.Round(num, 2) == num; if (integer_part >= 2 || !val) { MessageBox.Show("Please Enter valid GPA"); gpaTextBox.Clear(); gpaTextBox.Focus(); return; } } else { MessageBox.Show("Please enter valid input"); gpaTextBox.Clear(); gpaTextBox.Focus(); return; } } } }
C++
UTF-8
893
3.359375
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { vector<int> merge_vector; for(int i = 0;i<lists.size();i++) { ListNode* tmp = lists[i]; while(tmp) { merge_vector.push_back(tmp->val); tmp = tmp->next; } } if(merge_vector.size() == 0) return NULL; sort(merge_vector.begin(),merge_vector.end()); ListNode* merge = new ListNode(merge_vector[0]); ListNode* res = merge; for(int i = 1;i<merge_vector.size();i++) { ListNode* temp = new ListNode(merge_vector[i]); merge->next = temp; merge = merge->next; } return res; } };
Python
UTF-8
1,193
3.078125
3
[]
no_license
#!/usr/bin/env python import sys import requests import os import json calais_url = 'https://api.thomsonreuters.com/permid/calais' access_token = '<Access token>' def get_tags_util(input_string, headers): response = requests.post(calais_url, data=input_string, headers=headers, timeout=80) # print ('status code: %s' % response.status_code) content = json.loads(response.text) topics = [] for key, value in content.items(): if '_typeGroup' in value and value['_typeGroup'] == 'topics': topics.append(str(value['name'])) if response.status_code == 200: return topics # # Take a text/paragraph as input from the user, and return the relevant topics, the text is related to. # # Input: Welcome to Bangalore! # Output: ['Religion_Belief', 'Technology_Internet', 'Sports', 'Hospitality_Recreation', 'Business_Finance'] # def get_tags(input_string): try: headers = {'X-AG-Access-Token': access_token, 'Content-Type': 'text/raw', 'outputformat': 'application/json'} tags = get_tags_util(input_string, headers) return tags except Exception, e: print 'Error in connect ', e print get_tags(raw_input())
TypeScript
UTF-8
478
2.6875
3
[]
no_license
export class Produto { id: string; codigo: string; nome: string; precoUnitario: number; imagemUrl: string; quantidade: number; constructor(id: string, codigo: string, nome: string, precoUnitario: number, imagemUrl: string, quantidade: number) { this.id = id; this.codigo = codigo; this.nome = nome; this.precoUnitario = precoUnitario; this.imagemUrl = imagemUrl; this.quantidade = quantidade; } }
Ruby
UTF-8
458
2.546875
3
[]
no_license
Three parts of testing 1. Arrange can include: -instantiating objects vb: calc = Calculator.new('1,2') -setting mocks and stubs -populate databases with records to test against integration- tests 2. Act where we launch the behavior we want to test, usually a method call vb: result = calc.sum 3. Assert where we compare the 'expected' with the 'actual' result we computed while acting result.must_equal(3)
C
UTF-8
476
3.296875
3
[]
no_license
#include <stdio.h> #include <math.h> int obrnut(int x){ int suma=0,broj=x; int digit,brojac=0,i; //x=abs(x); digit = x%10; //suma=digit; while(!(x<=0)) { brojac++; x = x/10; } for(i=brojac;i>0;i--){ suma+=(broj%10)*pow(10,i-1); broj=broj/10; } return suma; } int main() { int broj,a; //printf("Tutorijal 7, Zadatak 4"); scanf("%d",&broj); a=obrnut(broj); printf("Broj je: %d!!",obrnut(broj)); return 0; }
JavaScript
UTF-8
4,370
2.890625
3
[ "MIT" ]
permissive
$(document).ready(function() { var goal = 0; var wins = 0; var losses = 0; var gems = []; var score = 0; var colors = ["green", "red", "blue", "yellow"]; var gemsContainer = $("#gems"); var goalContainer = $("#goal"); var scoreContainer = $("#total-score"); var statsContainer = $("#stats"); var cat = $(".normal, .fast, .slow"); var audio = new Audio('./audio/NyanCatoriginal.mp3'); audio.play(); audio.addEventListener('ended', function() { this.currentTime = 0; this.play(); }, false); audio.play(); $("#audio-controller").on('click','.audio-button', function() { audio.muted = !audio.muted; $(".audio-button").toggleClass("muted"); }); function initGame() { var goal = 0; var wins = 0; var losses = 0; var score = 0; //Set Goal Value goal = Math.floor((Math.random() * 120) + 19); gemsContainer.empty(); goalContainer.html(goal); scoreContainer.html(score); statsContainer.html("Wins: " + wins + "<br/>" + "Losses: " + losses); //Set Gems Values for (var i = 0; i < 4; i++) { gems.push({ color: colors[i], value: Math.floor((Math.random() * 12) + 1) }) } } function createGems() { for (var i = 0; i < gems.length; i++) { var newGem = $("<div>"); newGem.attr({ "id": gems[i].color, "class": "gem", "value": gems[i].value }); gemsContainer.append(newGem); } } function resetGame() { var goal = 0; var score = 0; //Set Goal Value goal = Math.floor((Math.random() * 120) + 19); gemsContainer.empty(); goalContainer.html(goal); scoreContainer.html(score); statsContainer.html("Wins: " + wins + "<br/>" + "Losses: " + losses); gems = []; for (var i = 0; i < 4; i++) { gems.push({ color: colors[i], value: Math.floor((Math.random() * 12) + 1) }) } } function updateGame(color, value) { //grab current score and add value of gem clicked var tempScore = parseInt(scoreContainer[0].innerHTML); var goalScore = parseInt(goalContainer[0].innerHTML); tempScore += value; if (tempScore > goalScore) { losses++; scoreContainer.html("You Lose!") setTimeout(function() { resetGame() gemsContainer.empty() createGems() cat.css('background-position', "-1000px"); }, 500); } else if (tempScore === goalScore) { wins++; scoreContainer.html("You Win!") setTimeout(function() { resetGame() gemsContainer.empty() createGems() cat.css('background-position', "-1000px"); }, 1000); } else { scoreContainer.html(tempScore); } var benchmarks = tempScore / goalScore; benchmarks = Math.floor(benchmarks * 100); updateCat(benchmarks); } //update the cat based on progress function updateCat(benchmarks) { if (benchmarks > 0 && benchmarks <= 20) { cat.css('background-position', "-1000px"); } else if (benchmarks <= 40) { cat.css('background-position', "-750px"); } else if (benchmarks <= 60) { cat.css('background-position', "-500px"); } else if (benchmarks <= 80) { cat.css('background-position', "-250px"); } else if (benchmarks <= 100) { cat.css('background-position', "-100px"); } if (wins === 1) { $(".slow, fast").css("display", "none"); $(".normal").css("display", "block"); } else if (wins >= 2) { $(".slow, .normal").css("display", "none"); $(".fast").css("display", "block"); } } //single gem on click $("#gems").on('click', '.gem', function() { var gem = this; var color = gem.id; var value = parseInt($(this).attr("value")); updateGame(color, value); }); initGame(); createGems(); });
C++
UTF-8
593
3.03125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <vector> using std::cout; using std::cin; using std::endl; using std::string; using namespace std; string garagem, *pgaragem; int main() { garagem = "palio"; *pgaragem = "0"; cout << "\nDigite o que esta em garagem: \n"; cout << garagem; cout << "\nDigite o que esta em *pgaragem: \n"; if(*pgaragem == 0){ cout << "\nO ponteiro *pgaragem esta vazio\n"; }else{ cout << *pgaragem; } string *pgaragem = &garagem; cout << "\nAgora atribui a *pgaragem = garagem: \n"; cout << "\nDigite o que esta em *pgaragem: \n"; cout << *pgaragem; }
Markdown
UTF-8
2,691
2.6875
3
[ "Apache-2.0" ]
permissive
# Sample Trellis Application [![Build Status](https://travis-ci.org/trellis-ldp/trellis-sample-app.png?branch=master)](https://travis-ci.org/trellis-ldp/trellis-sample-app) This project provides a skeleton for a custom Trellis application. For a full, working example, please examine the trellis-rosid-app directory in [trellis-ldp/trellis-rosid](https://github.com/trellis-ldp/trellis-rosid). You will need to add a persistence layer to make this code work. To do that, add your code to the `TrellisApplication` class inside the `run` method. It will be obvious. From there, you may wish to make further modifications to that method or to the `TrellisConfiguration` class. ## Running Trellis Unpack a zip or tar distribution. In that directory, modify `./etc/config.yml` to match the desired values for your system. To run trellis directly from within a console, issue this command: ```bash $ ./bin/trellis-app server ./etc/config.yml ``` ## Installation To install Trellis as a [`systemd`](https://en.wikipedia.org/wiki/Systemd) service on linux, follow the steps below. `systemd` is used by linux distributions such as CentOS/RHEL 7+ and Ubuntu 15+. 1. Move the unpacked Trellis directory to a location such as `/opt/trellis`. If you choose a different location, please update the `./etc/trellis.service` script. 2. Edit the `./etc/environment` file as desired (optional). 3. Edit the `./etc/config.yml` file as desired (optional). 4. Create a trellis user: ```bash $ sudo useradd -r trellis -s /sbin/nologin ``` 5. Create data directories. A different location can be used, but then please update the `./etc/config.yml` file. ```bash $ sudo mkdir /var/lib/trellis $ sudo chown trellis.trellis /var/lib/trellis ``` 6. Install the systemd file: ```bash $ sudo ln -s /opt/trellis/etc/trellis.service /etc/systemd/system/trellis.service ``` 7. Reload systemd to see the changes ```bash $ sudo systemctl daemon-reload ``` 8. Start the trellis service ```bash $ sudo systemctl start trellis ``` To check that trellis is running, check the URL: `http://localhost:8080` Application health checks are available at `http://localhost:8081/healthcheck` ## Building Trellis 1. Run `./gradlew clean install` to build the application or download one of the releases. 2. Unpack the appropriate distribution in `./build/distributions` 3. Start the application according to the steps above ## Configuration The web application wrapper (Dropwizard.io) makes many [configuration options](http://www.dropwizard.io/1.2.0/docs/manual/configuration.html) available. Any of the configuration options defined by Dropwizard can be part of your application's configuration file.
C#
UTF-8
508
2.515625
3
[]
no_license
using Calculator.Core; using Microsoft.AspNetCore.Mvc; namespace Api.Controllers { [ApiController] [Route("[controller]")] public class CalculatorController : ControllerBase { private readonly ICalculatorService _service; public CalculatorController(ICalculatorService service) { _service = service; } [HttpGet] public int Get(int first, int second) { return _service.Sum(first, second); } } }
PHP
UTF-8
752
2.53125
3
[ "MIT" ]
permissive
<?php require __DIR__ . "/../../vendor/autoload.php"; /** @file * Empty unit testing template/database version * @cond * Unit tests for the class */ class EmptyDBTest extends \PHPUnit_Extensions_Database_TestCase { /** * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection */ public function getConnection() { return $this->createDefaultDBConnection($pdo, 'cbowen'); } /** * @return PHPUnit_Extensions_Database_DataSet_IDataSet */ public function getDataSet() { return new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(); //return $this->createFlatXMLDataSet(dirname(__FILE__) . // '/db/users.xml'); } } /// @endcond
Java
UTF-8
2,994
2.453125
2
[]
no_license
package com.hq.uitest; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created by heqiang on 17/6/6. */ public class StringAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<String> mData; public boolean first = true; public StringAdapter(List<String> data){ mData = data; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_string,parent,false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder1, final int position) { if(holder1 instanceof ItemViewHolder){ ItemViewHolder holder = (ItemViewHolder) holder1; holder.tv_content.setText(mData.get(position)); if(mListener!=null){ holder.tv_content.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onItemClick(mData.get(position),holder1); } }); holder.tv_content.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mListener.onItemTouch(holder1); return false; } }); } // if(first) { // if (position > 5) { // holder.tv_content.setVisibility(View.GONE); // } else { // holder.tv_content.setVisibility(View.VISIBLE); // } // }else{ // if (position == 0 || position > 5) { // holder.tv_content.setVisibility(View.GONE); // } else { // holder.tv_content.setVisibility(View.VISIBLE); // } // } } } @Override public int getItemCount() { return mData.size(); } private OnItemClickListener mListener; public void setListener(OnItemClickListener mListener) { this.mListener = mListener; } public interface OnItemClickListener{ void onItemClick(String str, RecyclerView.ViewHolder holder); void onItemTouch(RecyclerView.ViewHolder holder); } class ItemViewHolder extends RecyclerView.ViewHolder{ TextView tv_content; // View view_null; public ItemViewHolder(View itemView) { super(itemView); tv_content = (TextView) itemView.findViewById(R.id.tv_rv_str); // view_null = itemView.findViewById(R.id.view_null); } } }
Java
UTF-8
671
2.03125
2
[]
no_license
package com.library.service; import java.util.List; import com.library.entity.*; public interface LibraryService { public List<Book> getResults(String keyword); public void createBookLoan(String isbn, int card_id); public int getLoans(int card_id); public void addBorrower(Borrower br); public boolean checkDuplicate(Borrower br); public List<BookLoan> getBookLoans(String key); public List<BookLoan> updateLoan(int loanid); public boolean isCardIdValid(int cardid); public List<Fines> getFines(int cardid); public List<Fines> payFines(int loanid); public List<BookLoan> getBookLoansByCardid(int key); }
Python
UTF-8
335
2.9375
3
[]
no_license
def chazhao(a,b): if len(a)!=len(b): print('false') else: A=[ord(x) for x in a] B=[ord(x) for x in b] s1=set(A) s2=set(B) if len(s1|s2)!=len(s1): print('false') else: print('true') import re a=input() m=re.split(r'\"',a) a=m[1] b=m[3] chazhao(a,b)
JavaScript
UTF-8
644
2.734375
3
[]
no_license
$(function() { function createColorArray(length) { let colors = ["#54ca76", "#f5c452", "#f2637f", "#9261f3","#31a4e6","55cbcb"] if (length <= colors.length) { return colors.slice(0, length); } } function createChart(chart_params) { ret = new Chart(canvas.getContext("2d"), { type: "doughnut", data: { labels: chart_params["labels"], datasets: [{ data: chart_params["values"], backgroundColor: createColorArray(chart_params["labels"].length) }] }, options: { animation: false } }); console.log("hello"); return ret; } })
Go
UTF-8
3,505
2.96875
3
[]
no_license
package cylon import ( "bytes" "encoding/json" "errors" "fmt" "log" "net/http" "net/url" "github.com/gorilla/mux" ) type Server struct { ai AI remoteRoot string localRoot string done chan bool } func NewServer(ai AI, remoteRoot string, localRoot string, done chan bool) *Server { s := &Server{ ai: ai, remoteRoot: remoteRoot, localRoot: localRoot, done: done, } return s } func (s *Server) CreateRouter() (*mux.Router, error) { r := mux.NewRouter() m := map[string]map[string]HttpApiFunc{ "GET": { "/status": s.status, }, "POST": { "/status": s.status, "/think": s.think, "/end": s.end, "/start": s.start, }, } for method, routes := range m { for route, handler := range routes { localRoute := route localHandler := handler localMethod := method f := makeHttpHandler(localMethod, localRoute, localHandler) r.Path(localRoute).Methods(localMethod).HandlerFunc(f) } } return r, nil } type joinMatchRequestMessage struct { Endpoint string `json:"endpoint"` Match string `json:"match"` } func (s *Server) Join(match string) error { j := &joinMatchRequestMessage{ Endpoint: s.localRoot, Match: match, } u, err := url.Parse(s.remoteRoot) if err != nil { return err } u.Path = "join" log.Println("Making request to ", u.String()) js, _ := json.Marshal(j) r, err := http.Post(u.String(), "application/json", bytes.NewBuffer(js)) if err != nil { return err } if r.StatusCode != http.StatusOK { return errors.New(fmt.Sprintf("expected HTTP 200 - OK, got %v", r.StatusCode)) } else { log.Println("OK") } return nil } func makeHttpHandler(localMethod string, localRoute string, handlerFunc HttpApiFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { writeCorsHeaders(w, r) if err := handlerFunc(w, r, mux.Vars(r)); err != nil { httpError(w, err) } } } func writeCorsHeaders(w http.ResponseWriter, r *http.Request) { w.Header().Add("Access-Control-Allow-Origin", "*") w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS") } type HttpApiFunc func(w http.ResponseWriter, r *http.Request, vars map[string]string) error func writeJSON(w http.ResponseWriter, code int, thing interface{}) error { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) val, err := json.Marshal(thing) w.Write(val) return err } func httpError(w http.ResponseWriter, err error) { statusCode := http.StatusInternalServerError if err != nil { http.Error(w, err.Error(), statusCode) } } func (s *Server) status(w http.ResponseWriter, r *http.Request, vars map[string]string) error { w.WriteHeader(http.StatusOK) return nil } func (s *Server) start(w http.ResponseWriter, r *http.Request, vars map[string]string) error { w.WriteHeader(http.StatusOK) return nil } func (s *Server) end(w http.ResponseWriter, r *http.Request, vars map[string]string) error { w.WriteHeader(http.StatusOK) s.done <- true return nil } func (s *Server) think(w http.ResponseWriter, r *http.Request, vars map[string]string) error { decoder := json.NewDecoder(r.Body) state := &RobotState{} err := decoder.Decode(state) if err != nil { log.Println(err) return err } commands := s.ai.Think(state) err = writeJSON(w, http.StatusOK, commands) if err != nil { log.Println(err) } return nil }
PHP
UTF-8
1,528
2.921875
3
[]
no_license
<?php /** * Class file for AmazonEc2TypeDescribeRouteTablesResponseType * @date 10/07/2012 */ /** * Class AmazonEc2TypeDescribeRouteTablesResponseType * @date 10/07/2012 */ class AmazonEc2TypeDescribeRouteTablesResponseType extends AmazonEc2WsdlClass { /** * The requestId * @var string */ public $requestId; /** * The routeTableSet * @var AmazonEc2TypeRouteTableSetType */ public $routeTableSet; /** * Constructor * @param string requestId * @param AmazonEc2TypeRouteTableSetType routeTableSet * @return AmazonEc2TypeDescribeRouteTablesResponseType */ public function __construct($_requestId = null,$_routeTableSet = null) { parent::__construct(array('requestId'=>$_requestId,'routeTableSet'=>$_routeTableSet)); } /** * Set requestId * @param string requestId * @return string */ public function setRequestId($_requestId) { return ($this->requestId = $_requestId); } /** * Get requestId * @return string */ public function getRequestId() { return $this->requestId; } /** * Set routeTableSet * @param RouteTableSetType routeTableSet * @return RouteTableSetType */ public function setRouteTableSet($_routeTableSet) { return ($this->routeTableSet = $_routeTableSet); } /** * Get routeTableSet * @return AmazonEc2TypeRouteTableSetType */ public function getRouteTableSet() { return $this->routeTableSet; } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } } ?>
Java
UTF-8
852
2.75
3
[]
no_license
package tests.bo; import bo.Agence; import bo.ComptePayant; import bo.Operation; import java.io.IOException; import java.sql.SQLException; public class TestOperation { public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException { Operation operation; System.out.printf("Test 1 - Création d'opération versement %n"); Operation.TypeOperation typeOperation = Operation.TypeOperation.values()[0]; operation = new Operation(1,typeOperation,1,1500); System.out.println(operation.toString()); System.out.printf("Test 2 - Création d'opération retrait %n"); Operation.TypeOperation typeOperation2 = Operation.TypeOperation.values()[1]; operation = new Operation(2,typeOperation2,1,1000); System.out.println(operation.toString()); } }
Java
UTF-8
890
3.125
3
[ "MIT" ]
permissive
package md.tekwill.exercises.inputoutput; public class Lanterns { public static void main(String[] args) { roofSpace(); roof(); light1(); roofSpace(); roof(); light2(); } public static void roof(){ System.out.println (" ***** "); System.out.println (" ********* "); System.out.println ("*************"); } public static void roofSpace(){ roof(); System.out.println(" "); } public static void light1(){ System.out.println("* | | | | | *"); System.out.println("*************"); } public static void light2(){ System.out.println(" ***** "); System.out.println("* | | | | | *"); System.out.println("* | | | | | *"); System.out.println(" ***** "); System.out.println(" ***** "); } }
C#
UTF-8
1,480
2.890625
3
[]
no_license
using ISynergy.Framework.Automations.States.Base; namespace ISynergy.Framework.Automations.States { /// <summary> /// Numeric trigger based on an integer. /// </summary> public class IntegerState : BaseState<int> { /// <summary> /// Default constructor. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="for"></param> public IntegerState(int from, int to, TimeSpan @for) : base(from, to, @for) { } } /// <summary> /// Numeric trigger based on a decimal. /// </summary> public class DecimalState : BaseState<decimal> { /// <summary> /// Default constructor. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="for"></param> public DecimalState(decimal from, decimal to, TimeSpan @for) : base(from, to, @for) { } } /// <summary> /// Numeric trigger based on a double. /// </summary> public class DoubleState : BaseState<double> { /// <summary> /// Default constructor. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="for"></param> public DoubleState(double from, double to, TimeSpan @for) : base(from, to, @for) { } } }
Python
UTF-8
848
4.25
4
[]
no_license
#직사각형 별찍기 #https://programmers.co.kr/learn/courses/30/lessons/12969?language=python3 #이 문제에는 표준 입력으로 두 개의 정수 n과 m이 주어집니다. #별(*) 문자를 이용해 가로의 길이가 n, 세로의 길이가 m인 직사각형 형태를 출력해보세요. #파이썬은 문자를 숫자로 곱하면 반복합니다. #map(): 입력값 받는다. 반복 가능한 자료형에 대해서 함수를 각각 적용한 결과 (여기선 int 함수를 쓴 것) #int함수? 그냥 input 값을 int로 받는 것 #strip(): 양쪽 공백 없애기(왼쪽 공백 lstrip(), 오른쪽 공백 rstrip()) a, b = map(int, input().strip().split(' ')) print(('*'*a +'\n')*b) #다른 사람 풀이 #row만큼 col에 *곱한 것 반복하기 col, row = map(int, input().split()) for i in range(row): print('*'*col)
Markdown
UTF-8
4,534
3.015625
3
[]
no_license
# Education Benefits Application Research with VCEs ## Goal and Research Questions - Goal - Get a more nuanced understanding of the current application experience process from "expert users" - Learn what the relevance of data entered is and how it's used by VCEs - Key research questions - What are the most confusing or difficult portions of the current process that we can focus on? - In particular, what portions cause the most problems with getting their applications approved (e.g., common errors they make because it's confusing) - What are the most important parts of the process that we should keep? ### Methods: - Interview ### Welcome and Opening Remarks (5 minutes) *[When the participant is ready, the moderator will begin the session with the following introduction.]* Thank you for joining us today. My name is [NAME] and we also have [NAME OF OTHERS OBSERVING] observing and taking notes for this session. We are doing this website feedback session on behalf of the team at the Department of Veterans Affairs working to build a new website that will help veterans get easier access to the benefits they deserve. The team wants to learn about the current education benefits application process today. We want to see what works well, and what doesn’t work well. In this session, I’ll ask you to tell me about your experiences with the application process, and give you the option to show me how you use the sites or any other tools. This will help us better understand how to make the site as easy to use and helpful as possible. Before we begin, I’d like to make a few things clear and explain how the session will work. * We aren’t trying to sell or promote any product or service to you. * We aren’t testing your ability. We’re just trying to figure out what works well on the website, and what doesn’t work well. So there are no right or wrong answers. We just want to hear your opinions and what you think so that we can make the site better. I won’t be offended by any opinions you express. * This entire feedback session should take about 30 minutes. I want to be sure not to keep you much longer, so I may occasionally interrupt you to move on to the next question or task. * We’ll be recording the screen activities as we look at the site. Recording our discussion today will help us capture everything you say accurately. * If for any reason and at any time you want to stop the session, please let me know. You will not be penalized in any way if we need to stop. ### Main questions - Can you tell me a little about your role and work? - How long have you working as a VCE (Veterans Claims Examiner) for education benefits? Have you done a lot? How many? What else does your work entail? - What does that process look like for you? Could you walk me through the steps? - [Follow-ups as needed about the steps of the process] - What parts of the application seem to consistently produce confusion for applicants or require extra work from the examiners? - What are the most common errors that Veterans submit with the application? How do you handle those situations? - Is there anything that requires extra work from you because of the way it gets entered on the form? - Can you tell me about a time when you had to get back in touch with an applicant for more information? - Are there parts of the application that you never need to reference for anything? - If you could wave a magic wand and improve three things in the application process, what would they be? What would the magically improved version be like? - What are the easiest parts of the process that should be kept as-is? ### Thank-You and Closing *[The moderator concludes each session by thanking the participant for their time and for offering his/her opinions and suggestions.]* Thank you very much for taking the time to give us your feedback today. We really appreciate your help! ### Direct questions if it doesn't come up - What is terminal leave and why does it matter? If a person is on active duty can they also be on terminal leave? - Do answers to military questions help to determine what a vet is eligible for or how much they are eligible for? - What content is expected in the ROTC comment field? Is it used? - Do we ever do anything with school info or is the state of the school enough? - What is the 'remarks' field for at the end of the application? Is it used often? - Is there anything you wish was part of the application but isn't? What problem does it solve?
Markdown
UTF-8
506
3.125
3
[ "MIT" ]
permissive
# ohm-grammar-ecmascript This directory contains Ohm grammars for various versions of the ECMAScript spec. Currently, only the ES5 grammar is reasonably complete, but we are working on ES6. ## Usage (NPM) You can install these grammars as an NPM package: ``` npm install ohm-grammar-ecmascript ``` After installing, you can use the ES5 grammar like this: ```js var es5 = require('ohm-grammar-ecmascript'); var result = es5.grammar.match('var x = 3; console.log(x);'); assert(result.succeeded()); ```
Java
UTF-8
2,025
2.75
3
[]
no_license
/******************************************************************************* * Copyright 2018 Mountain Fog, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package ai.idylnlp.nlp.features; import java.util.List; /** * Implementation of TF-IDF. * * Term Frequency - Inverse Document Frequency is a measure of how important a word is to a given * document in relation to a collection of documents. * * Adapted from https://guendouz.wordpress.com/2015/02/17/implementation-of-tf-idf-in-java/. * * @author Mountain Fog, Inc. * */ public class TFIDF { /** * Calculate the TF-IDF value for a given term. * * @param doc The document in question. * @param docs A list of all documents. * @param term The term. * @return A value indicating the term's importance * to the document. */ public double tfIdf(String[] doc, List<String[]> docs, String term) { return tf(doc, term) * idf(docs, term); } private double tf(String[] doc, String term) { double result = 0; for (String word : doc) { if (term.equalsIgnoreCase(word)) { result++; } } return result / doc.length; } private double idf(List<String[]> docs, String term) { double n = 0; for (String[] doc : docs) { for (String word : doc) { if (term.equalsIgnoreCase(word)) { n++; break; } } } return Math.log(docs.size() / n); } }
C++
UTF-8
795
3.046875
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct Student{ char name[11]; char id[11]; int grade; int flag; }stu[100010]; bool cmp(Student a, Student b){ if(a.flag != b.flag) return a.flag > b.flag; else return a.grade > b.grade; } int main(){ int n, g1, g2; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%s%s%d", stu[i].name, stu[i].id, &stu[i].grade); stu[i].flag = 0; } scanf("%d %d", &g1, &g2); int num = 0; for(int i = 0; i < n; i++){ if(stu[i].grade >= g1 && stu[i].grade <= g2){ stu[i].flag = 1; num++; } } if(num == 0){ printf("NONE"); } else{ sort(stu, stu + n, cmp); for(int i = 0 ;i < num; i++){ printf("%s %s\n", stu[i].name, stu[i].id); } } }
Markdown
UTF-8
5,014
2.640625
3
[]
no_license
# Oauth 2.0 Authorization Server 簡單範例說明 ## Authorization Code Grant +----------+ +----------+ | Resource | | User | | Owner | | Server | | | | | +----------+ +----------+ ^ ^ | | (B) (B) +----|-----+ Client Identifier +-------+-------+ | -+----(A)-- & Redirection URL ---->| | | User- | | Authorization | | Agent -+----(B)-- User authenticates --->| Server | | | | | | -+----(C)-- Authorization Code ---<| | +-|----|---+ +---------------+ | | ^ v (A) (C) | | | | | | ^ v | | +---------+ | | | |>---(D)-- Authorization Code ---------' | | Client | & Redirection URL | | | | | |<---(E)----- Access Token -------------------' +---------+ (w/ Optional Refresh Token) v ^ | | (F) (G) +-----------+ | +------------ Leet Code Answer -------- <| leet code | | | API | +---------- Carry Access Token in Header ---->| Server | +-----------+ 註: (A), (B), (C) 這三步的線拆成兩段,因為會經過 user-agent 跟 User Server ## 目錄結構 [這個專案的 GitHub 網址](https://github.com/powerbenson/oauth-server-simple-example) + leetcode -> leet code API Server 程式碼 (透過call api 拿到解答,但在這之前要先拿到access_token),解答程式碼檔案的路徑為 /leetcode/src/main/java/tw/idb/leetcode/service/AlphabetBoardPath.java + oauth -> Authorization Server 程式碼 (對Client進行認證,已經幫amaingtalker註冊了,client_id=amazingtalker、client_secret=amazingtalker-secret) + user -> User Server 程式碼 (對帳號密碼進行認證) + img -> img (放README.md的圖) + postman -> (放postman匯出的檔案,有/token、/alphabet-Board-Path兩隻API,記得要換掉code跟token) ## 操作步驟如下 + (A) 使用瀏覽器call以下網址 http://34.80.244.232/oauth/v1.0/authorization?client_id=amazingtalker&response_type=code&redirect_url=https://developers.google.com/oauthplayground&state= + (B) 輸入帳號密碼 amazingtalker/12345 <img src="./img/login_page.png" style="zoom:80%" /> + (C) 瀏覽器會redirect到(A)填的redirect_url,並且帶上code,把他複製下來,如下圖 <img src="./img/Authorization_Code.png" style="zoom:80%" /> + (D) 使用code去換access token,參考下方圖 參數名 | 必/選 | 填什麼 -------------|-------|-------------------------------------------- grant_type | 必 | authorization_code code | 必 | 在 (C) 拿到的 Authorization Code redirect_url | 必 | 跟 (A) 一樣是https://developers.google.com/oauthplayground client_id | 必 | amazingtalker client_secret| 必 | amazingtalker-secret POST /oauth/v1.0/token HTTP/1.1 Host: 34.80.244.232 Content-Type: application/x-www-form-urlencoded grant_type=authorization_code &code=STj9lixt3lxz0iLfK9bXZgDd7kEQklul &redirect_url=https://developers.google.com/oauthplayground &client_id=amazingtalker &client_secret=amazingtalker-secret + (E) Authorization Server會返回access_token跟refresh_token 如下 HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"a50f0d2d-6b70-40af-8291-cb9a83760e6d", "expires_in":604800, "token_type":"Bearer", "refresh_token":"b74bf35a-f722-4a8e-ac15-e452fe02473e", "additionalInformation": {} } + (F) 將在 (E) 步驟拿到的access_token夾帶在header call leet API Server 參數名 | 必/選 | 填什麼 -------------|-------|-------------------------------------------- target | 必 | 填寫英文字串 code | 必 | 在 (E) 拿到的 access_token GET /leetcode/v1.0/alphabet-Board-Path?target=leetcode HTTP/1.1 Host: 34.80.244.232 Authorization: Bearer 3dfc5073-ef78-4ba2-970a-d8febcc61011 + (G) 返回alphabet-Board-Path的解答
C++
UTF-8
907
3.125
3
[]
no_license
/** * \file Employe.h * \brief Classe de base abstraite Employe * \author etudiant * \version 0.1 * \date 2015-03-19 */ #ifndef EMPLOYE_H_ #define EMPLOYE_H_ #include "Date.h" #include "ContratException.h" namespace labo10 { /** * \class Employe * \brief Classe de base */ class Employe { public: Employe(const std::string& p_nom, const std::string& p_prenom, util::Date p_dateNaissance, int p_codeDepartement); virtual ~Employe() { } ; //Accesseurs std::string reqPrenom() const; std::string reqNomFamille() const; int reqCodeDepartement() const; util::Date reqDateNaissance() const; virtual double gains() const = 0; virtual std::string reqEmployeFormate() const; bool operator==(const Employe&) const; private: void verifieInvariant() const; std::string m_nomFamille; std::string m_prenom; int m_codeDepartement; util::Date m_dateNaissance; }; } #endif /* EMPLOYE_H_ */
C#
UTF-8
11,525
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OpenTK; using OpenTK.Graphics.OpenGL; namespace Lab3Boytsov { public partial class Form1 : Form { View view; bool loaded = false; public Form1() { InitializeComponent(); view = new View(); groupBox1.Visible = true; groupBox2.Visible = true; } private void glControl1_Load(object sender, EventArgs e) { loaded = true; view.Setup(); } private void glControl1_Paint(object sender, PaintEventArgs e) { if (!loaded) return; view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == false) { groupBox1.Visible = false; view.OffBigSphere(); } else { groupBox1.Visible = true; if (radioButton3.Checked == true) view.RefractBigSphere(); else if (radioButton1.Checked == true) view.DiffuseBigSphere(); else if (radioButton2.Checked == true) view.ReflectBigSphere(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } private void button1_Click(object sender, EventArgs e) //нажали на кнопку "ОК" { double x = 0, y = 0, z = 0; try { x = Convert.ToDouble(textBox1.Text); y = Convert.ToDouble(textBox2.Text); z = Convert.ToDouble(textBox3.Text); if ((x <= 1.0) && (y <= 1.0) && (z <= 1.0) && (x >= 0.0) && (y >= 0.0) && (z >= 0.0)) { view.ColorBigSphere((float)x,(float)y,(float)z); if (radioButton3.Checked == true) { view.RefractBigSphere(); } if (radioButton1.Checked == true) { view.DiffuseBigSphere(); } if (radioButton2.Checked == true) { view.ReflectBigSphere(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); groupBox1.Visible = true; } else MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button2_Click(object sender, EventArgs e) //если нажали кнопку "изменить" { groupBox1.Visible = true; } private void checkBox2_CheckedChanged(object sender, EventArgs e) //маленькая сфера { if (checkBox2.Checked == false) { groupBox2.Visible = false; view.OffSmallSphere(); } else { groupBox2.Visible = true; if (radioButton6.Checked == true) view.RefractSmallSphere(); else if (radioButton4.Checked == true) view.DiffuseSmallSphere(); else if (radioButton5.Checked == true) view.ReflectSmallSphere(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } private void button3_Click(object sender, EventArgs e) { double x = 0, y = 0, z = 0; try { x = Convert.ToDouble(textBox4.Text); y = Convert.ToDouble(textBox5.Text); z = Convert.ToDouble(textBox6.Text); if ((x <= 1.0) && (y <= 1.0) && (z <= 1.0) && (x >= 0.0) && (y >= 0.0) && (z >= 0.0)) { view.ColorSmallSphere((float)x, (float)y, (float)z); if (radioButton6.Checked == true) { view.RefractSmallSphere(); } if (radioButton4.Checked == true) { view.DiffuseSmallSphere(); } if (radioButton5.Checked == true) { view.ReflectSmallSphere(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } else MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button4_Click(object sender, EventArgs e) { groupBox2.Visible = true; } private void checkBox3_CheckedChanged(object sender, EventArgs e) //куб { if (checkBox3.Checked == false) { groupBox3.Visible = false; view.OffCub(); } else { groupBox3.Visible = true; if (radioButton9.Checked == true) view.RefractCub(); else if (radioButton7.Checked == true) view.DiffuseCub(); else if (radioButton8.Checked == true) view.ReflectCub(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } private void button5_Click(object sender, EventArgs e) { double x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0, x3 = 0, y3 = 0, z3 = 0; try { x1 = Convert.ToDouble(textBox7.Text); y1 = Convert.ToDouble(textBox8.Text); z1 = Convert.ToDouble(textBox9.Text); x2 = Convert.ToDouble(textBox10.Text); y2 = Convert.ToDouble(textBox11.Text); z2 = Convert.ToDouble(textBox12.Text); x3 = Convert.ToDouble(textBox13.Text); y3 = Convert.ToDouble(textBox14.Text); z3 = Convert.ToDouble(textBox15.Text); if ((x1 <= 1.0) && (y1 <= 1.0) && (z1 <= 1.0) && (x1 >= 0.0) && (y1 >= 0.0) && (z1 >= 0.0) && (x2 <= 1.0) && (y2 <= 1.0) && (z2 <= 1.0) && (x2 >= 0.0) && (y2 >= 0.0) && (z2 >= 0.0) && (x3 <= 1.0) && (y3 <= 1.0) && (z3 <= 1.0) && (x3 >= 0.0) && (y3 >= 0.0) && (z3 >= 0.0)) { view.ColorCub((float)x1, (float)y1, (float)z1, (float)x2, (float)y2, (float)z2, (float)x3, (float)y3, (float)z3); if (radioButton9.Checked == true) { view.RefractCub(); } if (radioButton7.Checked == true) { view.DiffuseCub(); } if (radioButton8.Checked == true) { view.ReflectCub(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } else MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button6_Click(object sender, EventArgs e) { groupBox3.Visible = true; } private void checkBox4_CheckedChanged(object sender, EventArgs e) //тетраэдр { if (checkBox4.Checked == false) { groupBox4.Visible = false; view.OffTet(); } else { groupBox4.Visible = true; if (radioButton12.Checked == true) view.RefractTet(); else if (radioButton10.Checked == true) view.DiffuseTet(); else if (radioButton11.Checked == true) view.ReflectTet(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } private void button7_Click(object sender, EventArgs e) { double x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0; try { x1 = Convert.ToDouble(textBox16.Text); y1 = Convert.ToDouble(textBox17.Text); z1 = Convert.ToDouble(textBox18.Text); x2 = Convert.ToDouble(textBox19.Text); y2 = Convert.ToDouble(textBox20.Text); z2 = Convert.ToDouble(textBox21.Text); if ((x1 <= 1.0) && (y1 <= 1.0) && (z1 <= 1.0) && (x1 >= 0.0) && (y1 >= 0.0) && (z1 >= 0.0) && (x2 <= 1.0) && (y2 <= 1.0) && (z2 <= 1.0) && (x2 >= 0.0) && (y2 >= 0.0) && (z2 >= 0.0)) { view.ColorTet((float)x1, (float)y1, (float)z1, (float)x2, (float)y2, (float)z2); if (radioButton12.Checked == true) { view.RefractTet(); } if (radioButton10.Checked == true) { view.DiffuseTet(); } if (radioButton11.Checked == true) { view.ReflectTet(); } view.Setup(); view.Update(); glControl1.SwapBuffers(); GL.UseProgram(0); } else MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { MessageBox.Show("Введите корректные данные", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button8_Click(object sender, EventArgs e) { groupBox4.Visible = true; } } }
Python
UTF-8
1,104
3.046875
3
[ "MIT" ]
permissive
#!/usr/bin/python from solver import * # import solver table = [(0,1,6,8,1), (4,0,3,4,2), (2,5,0,2,9), (5,7,4,0,7), (2,1,6,3,0)] state = [0,2,1] # genePool = [0,1,2] genePool=range(5) def printTable(): for row in table: print(row) def getMSTDist(state): MSTdist=0 for i in range(len(state)-1): MSTdist += table[state[i]][state[i+1]] # print table[state[i]][state[i+1]] # print 'MST',MSTdist return MSTdist def getFitness(state): return 1.0/(1.0+getMSTDist(state)) if __name__ == '__main__': print('-'*80) printTable() print('-'*80) print(getMSTDist(state)) population = init_population(15,genePool) # print 'population',population fitNode = genetic_algorithm(population, getFitness, genePool, f_thres=0.5, ngen=10000, pmut=0.5) print fitNode,'fitness:',getFitness(fitNode),'MST:',getMSTDist(fitNode)
C#
UTF-8
5,039
3.15625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Delegates2 { class MessageEventArgs : EventArgs { public string Message { get; set; } } class Messenger { public Action<string> MessageAvailable; //this is unsafe, the invoke is expose to the outside public event Action<string> SafeMessageAvailable;// this is safe, the invoke is not expose to the outside private Action<string> _messageAvailable; public event Action<string> CustomMessageAvailable { add { if (value.Target==null) { return; } Console.WriteLine("someone subscribed"); _messageAvailable += value; } remove { Console.WriteLine("someone unsubscribed"); _messageAvailable -= value; } } public event EventHandler<MessageEventArgs> StandardMessageAvailable; public void Send(string message) { MessageAvailable?.Invoke(message); SafeMessageAvailable?.Invoke(message); _messageAvailable?.Invoke(message); StandardMessageAvailable?.Invoke(this, new MessageEventArgs {Message = message}); } } class Program { delegate bool FilterPredicate(int x); delegate bool GenericFilterPredicate<T>(T x); static void Main(string[] args) { //DelegateExample(); //EventsMotivationExample(); CustomEventExample(); StandardNetEvents(); } private static void StandardNetEvents() { var messenger = new Messenger(); messenger.StandardMessageAvailable += MessengerOnStandardMessageAvailable; messenger.Send("Hello standard"); } private static void MessengerOnStandardMessageAvailable(object sender, MessageEventArgs messageEventArgs) { Console.WriteLine($"standard printer, msg {messageEventArgs.Message}"); } private static void CustomEventExample() { var messenger = new Messenger(); messenger.CustomMessageAvailable += StaticPrinter; messenger.Send("Hello static"); } private static void StaticPrinter(string msg) { Console.WriteLine($"I'm static printer, message:{msg}"); } private static void EventsMotivationExample() { var messenger = new Messenger(); messenger.MessageAvailable += s => Console.WriteLine($"s1 {s}"); messenger.MessageAvailable += s => Console.WriteLine($"s2 {s}"); messenger.MessageAvailable?.Invoke("Melicious Message"); //security breach messenger.SafeMessageAvailable += s => Console.WriteLine($"s1 {s}"); messenger.SafeMessageAvailable += s => Console.WriteLine($"s2 {s}"); //messenger.SafeMessageAvailable?.Invoke("Melicious Message"); //doesnt compile messenger.Send("Hello"); } private static void DelegateExample() { GenericFilterPredicate<int> myFilters = FilterByModulo2; myFilters += FilterByModulo3; var evenNumbers = Filter(new[] {1, 2, 3, 4, 5, 6}, FilterByModulo2); var by3Numbers = Filter(new[] {1, 2, 3, 4, 5, 6}, FilterByModulo3); var filtered = Filter(new[] {1, 2, 3, 4, 5, 6}, myFilters); var by4Numbers = Filter(new[] {1, 2, 3, 4, 5, 6}, x => x%4 == 0); Action<int> act1; // void Action<T1>(T1 arg1) --> T1 is int Action<int, string> act2; // void Action<T1,T2>(T1 arg1,T2 arg2) --> T1 is int T2 is string Func<int, int> func1; // R Func<T1,R>(T1 arg1) --> T1 is int R is int Func<int, string, int> func2; // R Func<T1,T2,R>(T1 arg1, T2 arg2) --> T1 is int T2 is string R is int foreach (var evenNumber in evenNumbers) { Console.WriteLine(evenNumber); } } private static bool FilterByModulo3(int i) { return i % 3 == 0; } private static bool FilterByModulo2(int i) { return i % 2 == 0; } static IEnumerable<int> FilterInts(IEnumerable<int> items, FilterPredicate pred) { foreach (var item in items) { if (pred(item)) { yield return item; } } } static IEnumerable<TItem> Filter<TItem>(IEnumerable<TItem> items, GenericFilterPredicate<TItem> pred) { foreach (var item in items) { if (pred(item)) { yield return item; } } } } }
C#
UTF-8
1,251
2.59375
3
[ "MIT" ]
permissive
using Rail.Mvvm; using Rail.Tracks; using System; using System.Diagnostics; namespace Rail.TrackEditor.ViewModel { [DebuggerDisplay("{Id} {Name} {Value}")] public class TrackNamedValueViewModel : BaseViewModel { private readonly TrackNamedValue namedValue; public TrackNamedValueViewModel() : this(new TrackNamedValue()) { } public TrackNamedValueViewModel(TrackNamedValue namedValue) { this.namedValue = namedValue; } public TrackNamedValue NamedValue { get { return this.namedValue; } } public Guid Id { get { return this.namedValue.Id; } } public string Name { get { return this.namedValue.Name; } set { this.namedValue.Name = value.Trim(); NotifyPropertyChanged(nameof(Name)); } } public double Value { get { return this.namedValue.Value; } set { this.namedValue.Value = value; NotifyPropertyChanged(nameof(Value)); } } public static TrackNamedValueViewModel Null { get { return new TrackNamedValueViewModel(new TrackNamedValue() { Id = Guid.Empty, Name = "0", Value = 0 }); } } } }
C++
UTF-8
1,557
3.71875
4
[]
no_license
#include <iostream> #include <vector> using namespace std; class Heap { public: void push(int number) { m_data.insert(m_data.begin(), number); heapify(0); } int pop() { if (empty()) return -1; int number = m_data[0]; m_data[0] = m_data[m_data.size() - 1]; m_data.pop_back(); heapify(0); return number; } void print() { for (vector<int>::iterator it = m_data.begin(); it != m_data.end(); ++it) cout<<*it; cout<<endl; } bool empty() { if (!m_data.size()) return true; return false; } int top() { if (!empty()) return m_data.front(); return -1; } protected: void heapify(int index) { int i = index; int left = 2 * i + 1; int right = 2 * i + 2; int size = m_data.size(); if (left < size && compare(m_data[left], m_data[index])) index = left; if (right < size && compare(m_data[right], m_data[index])) index = right; if (i != index) { swap(m_data[index], m_data[i]); heapify(index); } } virtual bool compare(int a, int b) = 0; private: vector<int> m_data; }; class MaxHeap : public Heap { protected: bool compare(int a, int b) { return a > b; } }; class MinHeap : public Heap { protected: bool compare(int a, int b) { return a < b; } };
Java
UTF-8
7,048
2.21875
2
[]
no_license
package HealthTracker; import com.jfoenix.controls.JFXToggleButton; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.Pane; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import java.net.URL; import java.util.Locale; import java.util.ResourceBundle; public class SettingsController implements Initializable { @FXML private Pane pane1; @FXML private Text tit1; @FXML private Text tit2; @FXML private Text opt1; @FXML private Text opt2; @FXML private Text opt3; @FXML private Text opt4; @FXML private Text opt5; @FXML private Button cal_btn; @FXML private Button ex_btn; @FXML private ComboBox<String> cbx1; @FXML private ComboBox<String> cbx2; @FXML private JFXToggleButton tgl1; @FXML private JFXToggleButton tgl2; @FXML private JFXToggleButton tgl3; @FXML private Button btn_group; @FXML private Button btn_workouts; @FXML private Button btn_home; @FXML private Button btn_user; @FXML private Button btn_settings; public static String unit = "km"; public static boolean large_font_size = false; public static boolean text_to_speech = false; public static boolean goal_option = true; public static boolean english_selected = true; @FXML private void redirect(ActionEvent event) { if (event.getSource() == btn_user) { System.out.println("Already on page."); return; } try { Parent newRoot = null; if (event.getSource() == cal_btn) { newRoot = FXMLLoader.load(getClass().getResource("calories.fxml")); } if (event.getSource() == ex_btn) { newRoot = FXMLLoader.load(getClass().getResource("exercise.fxml")); } if (event.getSource() == btn_group) { newRoot = FXMLLoader.load(getClass().getResource("groups.fxml")); } if (event.getSource() == btn_workouts) { newRoot = FXMLLoader.load(getClass().getResource("exercise.fxml")); } if (event.getSource() == btn_home) { newRoot = FXMLLoader.load(getClass().getResource("home.fxml")); } if (event.getSource() == btn_settings) { newRoot = FXMLLoader.load(getClass().getResource("settings.fxml")); } Scene scene = new Scene(newRoot); Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); appStage.setScene(scene); appStage.show(); } catch (Exception e) { System.out.println("Could not redirect: " + e); } } private void changeSize(){ if (large_font_size) { opt1.setFont(Font.font( 19)); opt2.setFont(Font.font( 19)); opt3.setFont(Font.font( 19)); opt4.setFont(Font.font(19)); opt5.setFont(Font.font(19)); }else { opt1.setFont(Font.font( 15)); opt2.setFont(Font.font( 15)); opt3.setFont(Font.font( 15)); opt4.setFont(Font.font( 15)); opt5.setFont(Font.font( 15)); } } //TRANSLATIONS METHOD //do it like this in other pages.. //lang_du.properties has german //lang_en.prop has english private void loadLang(String lang){ Locale locale = new Locale(lang); ResourceBundle bundle = ResourceBundle.getBundle("HealthTracker.lang",locale); //SET ALL TEXT BELOW tit1.setText(bundle.getString("settingsTitle1")); tit2.setText(bundle.getString("settingsTitle2")); opt1.setText(bundle.getString("opt1")); opt2.setText(bundle.getString("opt2")); opt3.setText(bundle.getString("opt3")); opt4.setText(bundle.getString("opt4")); opt5.setText(bundle.getString("opt5")); } @FXML public void tglAct1(ActionEvent event){ if(text_to_speech){ text_to_speech = false; }else { text_to_speech = true; // runnable for that thread //for speech call like this in all controler if(SettingsController.text_to_speech){ new Thread(() -> new SpeachClass().runSpeach("Track Settings Panel. Text to speech. Larger font. Language. DISABLE goal option. preferred units.")).start(); } } } @FXML public void tglAct2(ActionEvent event){ if(large_font_size){ large_font_size = false; }else { large_font_size = true; } changeSize(); } @FXML public void tglAct3(ActionEvent event){ if(goal_option){ goal_option = false; }else { goal_option = true; } } @Override public void initialize(URL url,ResourceBundle rb){ ObservableList<String> hobbies = FXCollections.observableArrayList("English","German"); ObservableList<String> hobbies2 = FXCollections.observableArrayList("Kilometers","Miles"); cbx1.getItems().setAll(hobbies); cbx1.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)->{ if(newVal.equals("English")){ loadLang("en"); english_selected = true; }else { loadLang("du"); english_selected = false; } }); cbx2.getItems().setAll(hobbies2); cbx2.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)->{ if(newVal.equals("Kilometers")){ unit = "km"; }else { unit = "ml"; } }); //SETTING VALUES FOR PANEL cbx2.getSelectionModel().select(SettingsController.unit.equals("km")? "Kilometers" : "Miles"); cbx1.getSelectionModel().select(SettingsController.english_selected? "English" : "German"); tgl1.setSelected(SettingsController.text_to_speech ? true : false); tgl2.setSelected(SettingsController.large_font_size ? true : false); tgl3.setSelected(SettingsController.goal_option ? true : false); //END //COPY if(SettingsController.english_selected){ loadLang("en"); }else{ loadLang("du"); } // if(SettingsController.text_to_speech){ new Thread(() -> new SpeachClass().runSpeach("Track Settings Panel. Text to speech. Larger font. Language. DISABLE goal option. preferred units.")).start(); } // changeSize(); } }
Python
UTF-8
4,397
2.859375
3
[]
no_license
print("-- Vigenère Cipher Decoder --") ciphertext = input("Input the message to decode: ") original = ciphertext caps = [0] * len(ciphertext) for i in range(len(ciphertext)): if ord(ciphertext[i]) >= 65 and ord(ciphertext[i]) <= 90: caps[i] = 1 # print(caps) keylen = int(input("Input the length of the key: ")) # http://cs.wellesley.edu/~fturbak/codman/letterfreq.html genfreq = {'a': 0.0820011, 'b': 0.0106581, 'c': 0.0344391, 'd': 0.0363709, 'e': 0.124167, 'f': 0.0235145, 'g': 0.0181188, 'h': 0.0350386, 'i': 0.0768052, 'j': 0.0019984, 'k': 0.00393019, 'l': 0.0448308, 'm': 0.0281775, 'n': 0.0764055, 'o': 0.0714095, 'p': 0.0203171, 'q': 0.0009325, 'r': 0.0668132, 's': 0.0706768, 't': 0.0969225, 'u': 0.028777, 'v': 0.0124567, 'w': 0.0135225, 'x': 0.00219824, 'y': 0.0189182, 'z': 0.000599} # genfreq={'a': 8.17, 'b':1.29 , 'c': 2.78, 'd': 4.25, 'e':12.70, 'f': 2.23, 'g': 2.02, # 'h': 6.09, 'i': 6.97, 'j': 0.15, 'k': 0.77, 'l': 4.03, 'm': 2.41, 'n': 6.75, # 'o': 7.51, 'p': 1.93, 'q': 0.10, 'r': 5.99, 's':6.33, 't': 9.06, 'u': 2.76, # 'v': 0.98, 'w': 2.36, 'x': 0.15, 'y': 1.97, 'z': 0.07} #genfreq = sorted(genfreq.items(), key=lambda x:x[1], reverse = True) #print (genfreq) ciphertext = ciphertext.lower() # splitting sections = [] for i in range(keylen): sections.append([]) count = 0 for i in ciphertext: if ord(i) >= 65 and ord(i) <= 90: if count == keylen: count = 0 sections[count].append(i) count = count + 1 elif ord(i) >= 97 and ord(i) <= 122: if count == keylen: count = 0 sections[count].append(i) count = count + 1 # print(sections) caesars = [] for i in range(keylen): caesars.append([]) for j in range(26): caesars[i].append([]) # caesar # FIX SPACES AND PUNCUTATION AND OTHER CHARS for i in range(keylen): for j in range(26): translated = "" for k in sections[i]: ck = ord(k) - j # shift by j if ck < 97: ck = ck + 26 translated = translated+chr(ck) # print(translated) caesars[i][j] = translated # print("caesars") # print(caesars) # DICTIONARIES dictionaries = [] for i in range(keylen): dictionaries.append([]) for j in range(26): dictionaries[i].append({}) for i in range(keylen): for j in range(26): dictionaries[i][j] = dict((chr(key), 0) for key in range(97, 123)) for i in range(keylen): for j in range(26): for k in caesars[i][j]: dictionaries[i][j][k] = dictionaries[i][j][k] + 1 #dictionaries[i][j] = sorted(dictionaries[i][j].items(), key=lambda x: x[1], reverse=True) # print(dictionaries) sums = [] for i in range(keylen): sums.append([]) for j in range(26): sums[i].append([]) # chi for i in range(keylen): for j in range(26): sum = 0 for k in dictionaries[i][j]: # print(dictionaries[i][j][k]) freq # print(k) letter caesarlength = len(caesars[i][j]) gf = genfreq[k] chi = dictionaries[i][j][k] - (caesarlength*gf) chi = chi ** 2 chi = chi / (caesarlength*gf) sum = sum + chi # print(sum) sums[i][j] = sum # print(sums) ckey = "" for i in range(keylen): low = sums[i].index(min(sums[i])) sums[i] = chr(low+97) ckey = ckey+sums[i] # print(ckey) # print(sums) diff = len(ciphertext) - len(sums) if diff > 0: for i in range(diff): sums.append(sums[i]) # print(sums) index = 0 check = 0 decrypted = [] for i in range(len(ciphertext)): if ciphertext[i].islower(): index = (ord(ciphertext[i])-96) - (ord(sums[i+check])-96) index = (index % 26) + 97 decrypted.append(chr(index)) elif ciphertext[i].isupper(): index = (ord(ciphertext[i]) - 65) - (ord(sums[i+check]) - 96) index = (index % 26) + 66 decrypted.append(chr(index)) else: index = ord(ciphertext[i]) check = check - 1 decrypted.append(chr(index)) d = "" for i in decrypted: d = d + i ckey = ckey.upper() print("Found Key: " + ckey) final = "" print("Decrypted message: ") for i in range(len(d)): if caps[i] == 1: print(d[i].upper(), end="") else: print(d[i], end="")
Java
UTF-8
5,968
2.40625
2
[]
no_license
package me.emersondantas.coursescounter.activity; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import me.emersondantas.coursescounter.R; import me.emersondantas.coursescounter.adapter.CourseAdapter; import me.emersondantas.coursescounter.exception.InvalidInputException; import me.emersondantas.coursescounter.model.bean.Course; import me.emersondantas.coursescounter.model.dao.CourseDAO; public class AddNewCourseActivity extends AppCompatActivity { private Button btnBack, btnRegister; private EditText etName, etNumLessons, etNumHours, etCurrentLesson, etLink; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_new_course); btnBack = findViewById(R.id.btnBack); btnRegister = findViewById(R.id.btnRegister); etName = findViewById(R.id.etName); etNumLessons = findViewById(R.id.etNumLessons); etNumHours = findViewById(R.id.etNumHours); etCurrentLesson = findViewById(R.id.etNumCurrentLesson); etLink = findViewById(R.id.etLink); listeneningBtnBack(); listeningBtnRegister(); } public void listeneningBtnBack(){ btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void listeningBtnRegister(){ btnRegister.setOnClickListener( new View.OnClickListener(){ @Override public void onClick(View v) { Course newCourse = null; try { newCourse = catchingDados(); CourseDAO.getInstance(getApplicationContext()).insertInTo(newCourse); clearAllImput(); CourseAdapter.getInstance().updateRecyclerView(CourseDAO.getInstance(null).selectAllFromTable()); AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddNewCourseActivity.this); alertDialog.setTitle("Curso cadastrado com sucesso!"); alertDialog.setIcon(android.R.drawable.ic_dialog_info); alertDialog.setNeutralButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); alertDialog.show(); } catch (InvalidInputException e) { showSnackBarResult(v, false); } } }); } private Course catchingDados() throws InvalidInputException { int numLessons = 0, numHours = 0, currentLesson = 0; Drawable erroIcon = getResources().getDrawable(R.drawable.ic_error_red_24dp); String erro = ""; String name = etName.getText().toString(); if(name.equals("")){ etName.setCompoundDrawablesWithIntrinsicBounds(null, null, erroIcon, null); erro += "Name input is empty" + " - "; }else{ etName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } try { numLessons = Integer.parseInt(etNumLessons.getText().toString()); etNumLessons.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); }catch(NumberFormatException ex){ etNumLessons.setCompoundDrawablesWithIntrinsicBounds(null, null, erroIcon, null); erro += "Lessons number is empty" + " - "; } try { numHours = Integer.parseInt(etNumHours.getText().toString()); etNumHours.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); }catch(NumberFormatException ex){ etNumHours.setCompoundDrawablesWithIntrinsicBounds(null, null, erroIcon, null); erro += "Hours number is empty" + " - "; } try { currentLesson = Integer.parseInt(etCurrentLesson.getText().toString()); etCurrentLesson.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); }catch(NumberFormatException ex){ etCurrentLesson.setCompoundDrawablesWithIntrinsicBounds(null, null, erroIcon, null); erro += "Current lesson number is empty" + " - "; } String link = etLink.getText().toString(); if(link.equals("")){ etLink.setCompoundDrawablesWithIntrinsicBounds(null, null, erroIcon, null); erro += "Link is empty"; }else{ etLink.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } if(erro.equals("")) { return new Course(name, numLessons, numHours, currentLesson, link); }else{ throw new InvalidInputException(erro); } } private void clearAllImput(){ etName.setText(""); etNumLessons.setText(""); etNumHours.setText(""); etCurrentLesson.setText(""); etLink.setText(""); } private void showSnackBarResult(View v, boolean result){ Snackbar resultBar = Snackbar.make(v, "result", Snackbar.LENGTH_LONG); if(result == true){ resultBar.setText("Curso cadastrado com sucesso!"); resultBar.setAction("Confirmar", new View.OnClickListener(){ @Override public void onClick(View v) { finish(); } }); }else{ resultBar.setText("Preencha os campos corretamente!"); } resultBar.show(); } }
Java
UTF-8
1,099
3.3125
3
[]
no_license
package org.mine.thread; import java.io.IOException; import java.io.PipedReader; import java.io.PipedWriter; /** * PipedReader、PipedWriter、PipedInputStream、PipedOutputStream * 主要用于线程间传输数据,传输介质为内存 * */ public class Piped { public static void main(String[] args) throws IOException { PipedWriter pipedWriter = new PipedWriter(); PipedReader pipedReader = new PipedReader(); // pipedReader.connect(pipedWriter); pipedWriter.connect(pipedReader); Thread print = new Thread(new Print(pipedReader), "Thread_print"); print.start(); int write = 0; while((write = System.in.read()) != -1){ pipedWriter.write(write); } } private static class Print implements Runnable{ private PipedReader pipedReader; public Print(PipedReader pipedReader){ this.pipedReader = pipedReader; } @Override public void run() { int receive = 0; try { while((receive = this.pipedReader.read()) != -1){ System.out.print(receive); } } catch (IOException exception) { exception.printStackTrace(); } } } }
Python
UTF-8
4,067
3.109375
3
[]
no_license
import os from scipy import signal from scipy.io import wavfile from scipy.fftpack import fft # fourier transform import matplotlib.pyplot as plot import numpy as np def calc_ITD(sound): samplerate, data = wavfile.read("./sounds/" + sound) left_channel = data[:, 0] # get all rows in column 0 (left channel) right_channel = data[:, 1] # get all rows in column 1 (right channel) left_max = max(left_channel, key=abs) right_max = max(right_channel, key=abs) time_l = left_channel.tolist().index(left_max) time_r = right_channel.tolist().index(right_max) ITD = (abs(abs(time_l) - abs(time_r)) / samplerate) * 1000 f = open(f'./ITD/{sound.replace(".wav", ".txt")}', 'w+') f.write(f"left_max: {left_max} right_max: {right_max} ITD: {ITD}") print(f"left_max: {left_max} right_max: {right_max} ITD: {ITD}, left time: {time_l}, right time: {time_r}") def create_plots(sound): samplerate, data = wavfile.read("./sounds/" + sound) left_channel = data[:, 0] # get all rows in column 0 (left channel) right_channel = data[:, 1] # get all rows in column 1 (right channel) normal_left = left_channel / np.linalg.norm(left_channel) normal_right = right_channel / np.linalg.norm(right_channel) time = np.linspace(0, (len(left_channel) / samplerate) * 1000, num=len(left_channel)) plot.plot(time, left_channel, color="blue") plot.plot(time, right_channel, color="red") plot.legend(['Left ear', 'Right ear']) plot.xlabel("Time (ms)") plot.ylabel("Amplitude (normalised)") plot.title(sound.replace('.wav', '').capitalize()) plot.savefig(f'plots/{sound.replace("wav", "png")}') def create_frequency_plots(sound): fs, data = wavfile.read("./sounds/" + sound) # fs, Audiodata = wavfile.read(AudioName) # Plot the audio signal in time plot.plot(data[:, 1]) plot.title('Audio signal in time',size=16) # spectrum n = len(data[:, 1]) AudioFreq = fft(data[:, 1]) AudioFreq = AudioFreq[0:int(np.ceil((n+1)/2.0))] #Half of the spectrum MagFreq = np.abs(AudioFreq) # Magnitude MagFreq = MagFreq / float(n) # power spectrum MagFreq = MagFreq**2 if n % 2 > 0: # ffte odd MagFreq[1:len(MagFreq)] = MagFreq[1:len(MagFreq)] * 2 else:# fft even MagFreq[1:len(MagFreq) -1] = MagFreq[1:len(MagFreq) - 1] * 2 plot.figure() freqAxis = np.arange(0,int(np.ceil((n+1)/2.0)), 1.0) * (fs / n); plot.plot(freqAxis/1000.0, 10*np.log10(MagFreq)) #Power spectrum plot.xlabel('Frequency (kHz)'); plot.ylabel('Power spectrum (dB)'); #Spectrogram N = 512 #Number of point in the fft f, t, Sxx = signal.spectrogram(data[:, 1], fs,window = signal.blackman(N),nfft=N) plot.figure() plot.pcolormesh(t, f,10*np.log10(Sxx)) # dB spectrogram #plot.pcolormesh(t, f,Sxx) # Lineal spectrogram plot.ylabel('Frequency [Hz]') plot.xlabel('Time [seg]') plot.title('Spectrogram with scipy.signal',size=16); plot.savefig(f'./plots/{sound.replace(".wav", "-spectrogram.png")}') # plot.show() def create_periodogram(sound): fs, data = wavfile.read("./sounds/" + sound) left_channel = data[:, 1] # Fixing random state for reproducibility # np.random.seed(19680801) dt = 0.00005 t = np.arange(0, 10, dt) r = np.exp(-t / 0.05) cnse = np.convolve(left_channel, r) * dt cnse = cnse[:len(t)] s = 0.1 * np.sin(2 * np.pi * t) + cnse # plot.subplot(211) # plot.plot(t, s) # plot.subplot(212) plot.psd(s, 512, 1 / dt) #time = (0:1)/(fs:len(left_channel)) #pxx = psd(spectrum.periodogram, left_channel, 'Fs', fs, 'NFFT', len(left_channel)) #plot.savefig(f'./plots/{sound.replace(".wav", "-periodogram.png")}') # plot.psd(left_channel, Fs=fs, NFFT=len(left_channel)) plot.savefig(f'./plots/{sound.replace(".wav", "-periodogram-right.png")}') plot.clf() for file in os.listdir("./sounds"): # create_plots(file) # create_frequency_plots(file) # create_periodogram(file) calc_ITD(file)
Java
UTF-8
1,352
2.390625
2
[ "Apache-2.0" ]
permissive
package by.bsu.command.impl; import by.bsu.command.Command; import by.bsu.controller.JspPageName; import by.bsu.exception.service.CarServiceException; import by.bsu.exception.service.OrderServiceException; import by.bsu.service.impl.CarServiceImpl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.sql.Date; public class SearchCarsCommand implements Command { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String page = null; String city = request.getParameter(LOCATION_CITY_ATTR_NAME); Date startDate = Date.valueOf(request.getParameter(START_DATE_ATTR_NAME)); Date finishDate = Date.valueOf(request.getParameter(FINISH_DATE_ATTR_NAME)); session.setAttribute(ST_DATE_ATTR_NAME, startDate); session.setAttribute(FIN_DATE_ATTR_NAME, finishDate); try { request.setAttribute(CARLIST_ATTR_NAME, CarServiceImpl.getInstance().searchCars(city, startDate.getTime(), finishDate.getTime())); page = JspPageName.DISPLAY_PAGE; } catch (CarServiceException | OrderServiceException e) { page = JspPageName.ERROR_PAGE; } return page; } }
Python
UTF-8
3,710
4.03125
4
[ "MIT" ]
permissive
import numpy as np class NeuralNetwork(): def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. np.random.seed(1) # We model a 3 layer network, with 3 input connections and 1 output connection. # We assign random weights to a 3 x 4 matrix, with values in the range -1 to 1 # and mean 0 for the first layerself. # And 4 x 1 matrix for the second layer self.synaptic_weights_0 = 2 * np.random.random((3,4)) - 1 self.synaptic_weights_1 = 2 * np.random.random((4,1)) - 1 #sigmoid function def __sigmoid(self, x, deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) def __ReLU(self, x, deriv=False): if(deriv==True): return 1. * (x > 0) return x * (x > 0) # We train the neural network through a process of trial and error. # Adjusting the synaptic weights each time. def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in range(number_of_training_iterations): # Pass the training set through our neural network (a single neuron). layer0 = training_set_inputs [layer1, layer2] = self.think(training_set_inputs) output = layer2 # Calculate the error (The difference between the desired output # and the predicted output). output_layer_error = training_set_outputs - output if(iteration % 10000) == 0: print("Error:" + str(np.mean(np.abs(output_layer_error)))) # Multiply the error by the input and again by the gradient of the Sigmoid curve. # This means less confident weights are adjusted more. # This means inputs, which are zero, do not cause changes to the weights. #backpropagation layer_2_delta = output_layer_error * self.__sigmoid(output, deriv=True) layer_1_error = layer_2_delta.dot(self.synaptic_weights_1.T) layer_1_delta = layer_1_error * self.__sigmoid(layer1, deriv=True) #update weights - gradient descent self.synaptic_weights_1 += layer1.T.dot(layer_2_delta) self.synaptic_weights_0 += layer0.T.dot(layer_1_delta) # The neural network thinks. def think(self, inputs): # Pass inputs through our neural network. layer1 = self.__sigmoid(np.dot(inputs, self.synaptic_weights_0)) layer2 = self.__sigmoid(np.dot(layer1, self.synaptic_weights_1)) return [layer1, layer2] def run(): #Intialise a single neuron neural network. neural_network = NeuralNetwork() print("Random starting synaptic weights: ") print(neural_network.synaptic_weights_0) print(neural_network.synaptic_weights_1) # The training set. We have 4 examples, each consisting of 3 input values # and 1 output value. training_set_inputs = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_set_outputs = np.array([[0, 1, 1, 0]]).T # Train the neural network using a training set. # Do it 10,000 times and make small adjustments each time. neural_network.train(training_set_inputs, training_set_outputs, 60000) print ("New synaptic weights after training: ") print (neural_network.synaptic_weights_0) print (neural_network.synaptic_weights_1) # Test the neural network with a new situation. print ("Considering new situation [1, 0, 0] -> ?: ") [layer1, layer2] = neural_network.think(np.array([1, 0, 0])) print(layer2) if __name__ == '__main__': run()
JavaScript
UTF-8
642
2.78125
3
[]
no_license
var fs = require('fs'); var stream = fs.createWriteStream("render.ppm"); var image = [] var width = 255 var height = 255 for (var y = 0; y < height; y++) { var row = [] for (var x = 0; x < width; x++) { var pixel = [] pixel[0] = Math.round(y%255) pixel[1] = Math.round(x%255) pixel[2] = Math.round(255) row[x] = pixel } image[y] = row } stream.once('open', function(fd) { stream.write("P3\n#JS PPM\n" + image[0].length + " " + image.length + "\n255\n"); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { stream.write(image[y][x].join(" ") + " ") } stream.write("\n") } stream.end(); });
Java
UTF-8
18,127
2.265625
2
[]
no_license
/* Created by Petar Shomov <petar@sprettur.is> and contributors Copyright (c) 2009 Síminn hf (http://www.siminn.is). All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Inital version of this file contributed by Síminn hf. (http://www.siminn.is) */ package is.siminn.asgard.objectmapping; import static is.siminn.asgard.objectmapping.Mappings.*; import is.siminn.asgard.objectmapping.transformation.StringToIntegerTransformation; import static org.testng.Assert.*; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Test public class MappingsTest { @BeforeMethod public void setup() { flush(); } public void should_map_one_property_from_src_object_into_another_property_in_destination() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertEquals(customerDest.getCity(), "city 17"); } public void should_map_two_properties_from_source_to_destination() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); from(srcObj.getPostalcode()).to(destObj).setPostalcode(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); customerSrc.setPostalcode("101"); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertEquals(customerDest.getCity(), "city 17"); assertEquals(customerDest.getPostalcode(), "101"); } public void should_clear_mappings_on_flush() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); from(srcObj.getPostalcode()).to(destObj).setPostalcode(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); customerSrc.setPostalcode("101"); Customer customerDest = new Customer(); flush(); transform(customerSrc, customerDest); assertNull(customerDest.getCity()); assertNull(customerDest.getPostalcode()); } public void finalize_method_does_not_get_recorded_as_part_of_the_transformation() { initMapping(); System.gc(); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); customerSrc.setPostalcode("101"); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertEquals(customerDest.getCity(), "city 17"); assertEquals(customerDest.getPostalcode(), "101"); } private void initMapping() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); from(srcObj.getPostalcode()).to(destObj).setPostalcode(null); } public void should_apply_mapping_appropriate_for_the_class() { CustomerLocal otherSrcObj = src(CustomerLocal.class); Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(otherSrcObj.getCity()).to(destObj).setCustomertype(null); from(srcObj.getCity()).to(destObj).setCity(null); from(srcObj.getPostalcode()).to(destObj).setPostalcode(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); customerSrc.setPostalcode("101"); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertEquals(customerDest.getCity(), "city 17"); assertEquals(customerDest.getPostalcode(), "101"); assertNull(customerDest.getCustomertype()); } public void should_apply_mapping_appropriate_for_a_subclass_when_that_class_is_registered_in_mappings() { CustomerLocal otherSrcObj = src(CustomerLocal.class); Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(otherSrcObj.getCity()).to(destObj).setCustomertype(null); from(srcObj.getCity()).to(destObj).setCity(null); from(srcObj.getPostalcode()).to(destObj).setPostalcode(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); customerSrc.setPostalcode("101"); CustomerSubClass customerDest = new CustomerSubClass(); transform(customerSrc, customerDest); assertEquals(customerDest.getCity(), "city 17"); assertEquals(customerDest.getPostalcode(), "101"); assertNull(customerDest.getCustomertype()); } public void should_apply_transformation() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).applyTransformation(new SimpleTransformation()).to(destObj).setCity(null); Customer customerSrc = new Customer(); customerSrc.setCity(" city 17 "); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertEquals(customerDest.getCity(), "city 17"); } public void should_skip_transformation_if_the_filter_does_not_approve() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).applyFilter(new Filter<String>() { public boolean allow(String input, Object context) { return false; } }).to(destObj).setCity(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertNull(customerDest.getCity()); } public void should_omit_object_from_collection_if_the_filter_does_not_approve() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getAccounts()).applyCollectionFilter(new Filter<Account>() { public boolean allow(Account input, Object context) { return input.getAccountNo().equals("1"); } }).to(Account.class, destObj.getAccounts()); Account account1 = new Account(); account1.setAccountNo("1"); Account account2 = new Account(); account2.setAccountNo("2"); Customer customerSrc = new Customer(); customerSrc.getAccounts().add(account1); customerSrc.getAccounts().add(account2); Customer customerDest = new Customer(); transform(customerSrc, customerDest); assertEquals(customerDest.getAccounts().size(),1); assertEquals(customerDest.getAccounts().get(0).getAccountNo(),"1"); } public void should_not_modify_destination_object_if_source_is_null() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); Customer customerDest = new Customer(); customerDest.setCity("city 17"); transform(null, customerDest); assertEquals(customerDest.getCity(), "city 17"); } public void should_not_throw_if_destination_object_is_null() { Customer srcObj = src(Customer.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); Customer customerSrc = new Customer(); customerSrc.setCity("city 17"); transform(customerSrc, null); assertEquals(customerSrc.getCity(), "city 17"); } public void should_map_src_object_to_many_fields_on_dest_object() { CustomerLocal srcObj = src(CustomerLocal.class); Customer intermediate = dest(Customer.class); Account destination = dest(Account.class); from(srcObj.getCity()).to(intermediate).setCity(null); from(srcObj).to(destination).setCustomer(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity("city 17"); final Account dest = new Account(); transform(customerSrc, dest); assertEquals(dest.getCustomer().getCity(), "city 17"); } public void should_map_src_object_then_applyTransformations_to_dest_method() { CustomerLocal srcObj = src(CustomerLocal.class); Customer intermediate = dest(Customer.class); from(srcObj).applyTransformation(new Transformation<CustomerLocal>() { public Object apply(CustomerLocal input, Object context) { return "the city"; } }).to(intermediate).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); final Customer dest = new Customer(); transform(customerSrc, dest); assertEquals(dest.getCity(), "the city"); } public void should_auto_trim_all_String_values_in_destinations() { CustomerLocal srcObj = src(CustomerLocal.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity(" city 17 "); final Customer dest = new Customer(); transform(customerSrc, dest); assertEquals(dest.getCity(), "city 17"); } public void transform_should_return_the_destination_object() { CustomerLocal srcObj = src(CustomerLocal.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).to(destObj).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity(" city 17 "); final Customer dest = new Customer(); Customer dest2 = transform(customerSrc, dest); assertSame(dest2, dest); } public void should_map_typed_collection_using_mapping_of_collected_object_class(){ Customer dest = dest(Customer.class); CustomerType2 src = src(CustomerType2.class); from(src.getAccounts()).to(Account.class, dest.getAccounts()); Account destAccount = dest(Account.class); AccountType2 srcAccountType = src(AccountType2.class); from(srcAccountType.getAccountNo()).to(destAccount).setAccountNo(null); Customer destObj = new Customer(); CustomerType2 srcObj = new CustomerType2(); srcObj.getAccounts().add(new AccountType2("ble")); srcObj.getAccounts().add(new AccountType2("bla")); transform(srcObj, destObj); assertEquals(destObj.getAccounts().size(),2, "Destination object should have same number of items in the collection"); List<Account> list = destObj.getAccounts(); assertEquals(list.get(0).getAccountNo(),"ble", "Should be ble"); assertEquals(destObj.getAccounts().get(1).getAccountNo(),"bla", "Should be bla"); } @Test(enabled = false) public void should_map_properties_on_name_on_similar_objects() { Customer destObj = dest(Customer.class); CustomerType2 srcObj = src(CustomerType2.class); from(srcObj).toObject(destObj); final Customer dest = new Customer(); CustomerType2 src = new CustomerType2(); src.setCity("Reykjavik"); transform(src, dest); assertEquals(dest.getCity(), src.getCity()); } public void should_return_src_object_when_calling_transform_and_there_are_no_mappings_for_src_and_destinatioan_and_they_are_the_same_type() { final String src = "src"; final String dest = "dest"; assertSame(transform(src, dest), src); } enum TestEnum {a, b} public void should_process_enum_value_normally_as_part_of_transformation(){ EnumClassParams srcObj = src(EnumClassParams.class); EnumClassParams destObj = dest(EnumClassParams.class); from(srcObj.getA()).to(destObj).setA(null); final EnumClassParams enumClassParamsSrc = new EnumClassParams(); enumClassParamsSrc.setA(TestEnum.b); EnumClassParams destt = transform(enumClassParamsSrc, new EnumClassParams()); assertEquals(destt.getA(), TestEnum.b); } @Test public void should_report_exact_field_in_exception_on_a_transformation_failure() { CustomerLocal srcObj = src(CustomerLocal.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).applyTransformation(new StringToIntegerTransformation()).to(destObj).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity(" city 17 "); final Customer dest = new Customer(); try { transform(customerSrc, dest); fail("Expecting an exception"); } catch (Exception e) { assertTrue(e.getMessage().indexOf("getCity")>=0, "Actual message: " + e.getMessage()); assertTrue(e.getMessage().indexOf("setCity")>=0, "Actual message: " + e.getMessage()); } } @Test public void should_pass_context_information_along_into_ContextTransformation() { CustomerLocal srcObj = src(CustomerLocal.class); Customer destObj = dest(Customer.class); final Map projectionContext = new HashMap(); from(srcObj.getCity()).applyTransformation(new ContextTransformation<String>(){ public Object apply(TransformationContext<String> stringTransformationContext) { assertSame(stringTransformationContext.getParams(), projectionContext); return null; } }).to(destObj).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity(" city 17 "); final Customer dest = new Customer(); transform(customerSrc, dest, projectionContext); } @Test public void should_pass_transformed_input_on_to_next_transformation_in_a_transformation_chain() { CustomerLocal srcObj = src(CustomerLocal.class); Customer destObj = dest(Customer.class); final Map projectionContext = new HashMap(); from(srcObj.getCity()).applyTransformation(new ContextTransformation<String>(){ public Object apply(TransformationContext<String> stringTransformationContext) { return "onetransform"; } }).applyTransformation(new ContextTransformation<String>() { public Object apply(TransformationContext<String> stringTransformationContext) { assertEquals("onetransform", stringTransformationContext.getInput()); return null; } }).to(destObj).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity(" city 17 "); final Customer dest = new Customer(); transform(customerSrc, dest, projectionContext); } @Test public void should_transform_null_ProjectionContext_to_an_empty_map() { CustomerLocal srcObj = src(CustomerLocal.class); Customer destObj = dest(Customer.class); from(srcObj.getCity()).applyTransformation(new ContextTransformation<String>(){ public Object apply(TransformationContext<String> stringTransformationContext) { assertEquals(stringTransformationContext.getParams().size(), 0); return null; } }).to(destObj).setCity(null); CustomerLocal customerSrc = new CustomerLocal(); customerSrc.setCity(" city 17 "); final Customer dest = new Customer(); transform(customerSrc, dest, null); } private class SimpleTransformation implements Transformation<String> { public String apply(String input, Object context) { return input.trim(); } } private class CustomerSubClass extends Customer { } public static class CustomerType2 { private String city; private String postalcode; private String customertype; private List<AccountType2> accounts = new ArrayList<AccountType2>(); public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPostalcode() { return postalcode; } public void setPostalcode(String postalcode) { this.postalcode = postalcode; } public void setCustomertype(String customertype) { this.customertype = customertype; } public String getCustomertype() { return customertype; } public List<AccountType2> getAccounts(){ return accounts; } } public static class AccountType2{ private String accountNo; public AccountType2() { } public AccountType2(String accountNo) { this.accountNo = accountNo; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } } public static class CustomerLocal { private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } } }
Java
UTF-8
11,416
2.375
2
[]
no_license
package view; import controller.CadastroViewController; import javax.swing.JTextField; public class CadastroView extends javax.swing.JFrame { private final CadastroViewController controller; public CadastroView() { initComponents(); controller = new CadastroViewController(this); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); txtCpf = new javax.swing.JTextField(); txtNome = new javax.swing.JTextField(); txtDataNascimento = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtSexo = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); txtCargo = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); txtPerfilUsuario = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jPanel1.setBackground(new java.awt.Color(190, 144, 212)); jPanel2.setBackground(new java.awt.Color(190, 144, 212)); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setBackground(new java.awt.Color(44, 62, 80)); txtCpf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCpfActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setText("CPF"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("Nome"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("Data de Nascimento"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("Sexo"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("Cargo"); jButton1.setText("Cadastrar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); txtCargo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCargoActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("Perfil de Usuario"); jPanel3.setBackground(new java.awt.Color(190, 144, 212)); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Cadastro"); jPanel3.add(jLabel7); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 530, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(155, 155, 155) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtCargo) .addComponent(txtPerfilUsuario) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel5)) .addGap(101, 101, 101)) .addComponent(txtDataNascimento) .addComponent(txtNome, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCpf) .addComponent(txtSexo) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(163, 163, 163)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(50, 50, 50) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(jLabel2) .addGap(4, 4, 4) .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addGap(4, 4, 4) .addComponent(txtPerfilUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(29, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtCpfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCpfActionPerformed }//GEN-LAST:event_txtCpfActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed controller.salvaUsuario(); }//GEN-LAST:event_jButton1ActionPerformed private void txtCargoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCargoActionPerformed }//GEN-LAST:event_txtCargoActionPerformed public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CadastroView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadastroView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadastroView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadastroView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CadastroView().setVisible(true); } }); } public JTextField getTxtCargo() { return txtCargo; } public void setTxtCargo(JTextField txtCargo) { this.txtCargo = txtCargo; } public JTextField getTxtCpf() { return txtCpf; } public void setTxtCpf(JTextField txtCpf) { this.txtCpf = txtCpf; } public JTextField getTxtDataNascimento() { return txtDataNascimento; } public void setTxtDataNascimento(JTextField txtDataNascimento) { this.txtDataNascimento = txtDataNascimento; } public JTextField getTxtNome() { return txtNome; } public void setTxtNome(JTextField txtNome) { this.txtNome = txtNome; } public JTextField getTxtSexo() { return txtSexo; } public void setTxtSexo(JTextField txtSexo) { this.txtSexo = txtSexo; } public JTextField getTxtPerfilUsuario() { return txtPerfilUsuario; } public void setTxtPerfilUsuario(JTextField txtPerfilUsuario) { this.txtPerfilUsuario = txtPerfilUsuario; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JTextField txtCargo; private javax.swing.JTextField txtCpf; private javax.swing.JTextField txtDataNascimento; private javax.swing.JTextField txtNome; private javax.swing.JTextField txtPerfilUsuario; private javax.swing.JTextField txtSexo; // End of variables declaration//GEN-END:variables }
Java
UTF-8
325
2.265625
2
[]
no_license
package com.valtech.azubi.bankanwendung.model.core; import com.valtech.azubi.bankanwendung.model.entity.Konto; public class KontoGesperrtException extends Exception{ public KontoGesperrtException(Konto k) { super("Konto mit der Kontonummer: "+k.getKontoNr()+" gesperrt! Keine Transaktionen möglich!"); } }
Java
UTF-8
4,726
2.125
2
[]
no_license
package ent.ast; import ent.types.*; import polyglot.ast.*; import polyglot.translate.*; import polyglot.types.*; import polyglot.util.*; import polyglot.visit.*; import java.util.Collections; import java.util.ArrayList; import java.util.List; public class ModeParamTypeNode_c extends TypeNode_c implements ModeParamTypeNode { protected Id id; protected List<ModeTypeNode> lowerBounds; protected List<ModeTypeNode> upperBounds; protected boolean isDynRecvr; public ModeParamTypeNode_c(Position pos, Id id, boolean isDynRecvr, List<ModeTypeNode> lowerBounds, List<ModeTypeNode> upperBounds) { super(pos); this.id = id; this.isDynRecvr = isDynRecvr; this.lowerBounds = CollectionUtil.nonNullList(lowerBounds); this.upperBounds = CollectionUtil.nonNullList(upperBounds); } // Property Methods public Id id() { return this.id; } public boolean isDynRecvr() { return this.isDynRecvr; } public List<ModeTypeNode> lowerBounds() { return this.lowerBounds; } protected <N extends ModeParamTypeNode_c> N lowerBounds(N n, List<ModeTypeNode> lb) { if (CollectionUtil.equals(this.lowerBounds(), lb)) return n; n = this.copyIfNeeded(n); n.lowerBounds = ListUtil.copy(lb, true); return n; } public List<ModeTypeNode> upperBounds() { return this.upperBounds; } protected <N extends ModeParamTypeNode_c> N upperBounds(N n, List<ModeTypeNode> ub) { if (CollectionUtil.equals(this.upperBounds(), ub)) return n; n = this.copyIfNeeded(n); n.upperBounds = ListUtil.copy(ub, true); return n; } @Override public String name() { return this.id().id(); } protected <N extends ModeParamTypeNode_c> N reconstruct(N n, List<ModeTypeNode> lb, List<ModeTypeNode> ub) { n = this.lowerBounds(n, lb); n = this.upperBounds(n, ub); return n; } // Node Methods @Override public Node visitChildren(NodeVisitor v) { List<ModeTypeNode> lb = visitList(this.lowerBounds(), v); List<ModeTypeNode> ub = visitList(this.upperBounds(), v); Node n = this.reconstruct(this, lb, ub); return n; } @Override public Node copy(NodeFactory nf) { EntNodeFactory pnf = (EntNodeFactory)nf; return pnf.ModeParamTypeNode(this.position(), this.id(), this.isDynRecvr(), ListUtil.copy(this.lowerBounds(), true), ListUtil.copy(this.upperBounds(), true)); } @Override public Node buildTypes(TypeBuilder tb) throws SemanticException { EntTypeSystem ts = (EntTypeSystem)tb.typeSystem(); ModeTypeVariable mtVar = null; if (ts.createdModeTypes().containsKey(this.name())) { ModeType mt = ts.createdModeTypes().get(this.name()); List<Type> bounds = new ArrayList<>(); bounds.add(mt); mtVar = ts.createModeTypeVariable(this.position(), "_"); mtVar.upperBounds(bounds); mtVar.lowerBounds(bounds); } else { mtVar = ts.createModeTypeVariable(this.position(), this.id().id()); } return this.type(mtVar); } @Override public Node disambiguate(AmbiguityRemover sc) throws SemanticException { ModeTypeVariable mtVar = (ModeTypeVariable)this.type(); EntTypeSystem ts = (EntTypeSystem)sc.typeSystem(); boolean ambiguous = false; List<Type> upperBoundTypes = new ArrayList<Type>(); for (ModeTypeNode tn : this.upperBounds()) { if (!tn.isDisambiguated()) { ambiguous = true; } upperBoundTypes.add(tn.type()); } List<Type> lowerBoundTypes = new ArrayList<Type>(); for (ModeTypeNode tn : this.lowerBounds()) { if (!tn.isDisambiguated()) { ambiguous = true; } lowerBoundTypes.add(tn.type()); } if (ambiguous) { return this; } if (!this.lowerBounds().isEmpty() || !this.upperBounds().isEmpty()) { mtVar.upperBounds(upperBoundTypes); mtVar.lowerBounds(lowerBoundTypes); } if (this.isDynRecvr()) { mtVar.isDynRecvr(true); } if (!mtVar.inferBounds()) { throw new SemanticException("Unable to infer bounds for mode type variable"); } if (mtVar.upperBound() == ts.DynamicModeType() && mtVar.isDynRecvr()) { throw new SemanticException( "Mode type variable cannot be a dynamic reciever with a dynamic mode upper bound."); } return this; } @Override public Node extRewrite(ExtensionRewriter rw) throws SemanticException { return null; } @Override public void prettyPrint(CodeWriter w, PrettyPrinter tr) {} }