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
Python
UTF-8
1,599
2.65625
3
[]
no_license
#coding=utf-8 import pickle, time, logging from redis import WatchError class RedisPriorityQueue(object): def __init__(self, redis_client, key, max_size): self._redis_client = redis_client self._key = key self._pipe = redis_client.pipeline() self._maxsize = max_size logging.info('Start RedisPriorityQueue for %s, max_size = %s', key, max_size) def put(self, score, item, check_maxsize=True): while check_maxsize and self.qsize() > self._maxsize: logging.info('redis_pq full: %s > %s', self.qsize(), self._maxsize) time.sleep(1) data = pickle.dumps(item) self._redis_client.zadd(self._key, score, data) def free_slot(self): return self._maxsize - self.qsize() def get(self): while True: try: item = None self._pipe.watch(self._key) data_list = self._pipe.zrevrange(self._key, 0, 0, withscores=False) if data_list: item = pickle.loads(data_list[0]) self._pipe.multi() self._pipe.zrem(self._key, data_list[0]) self._pipe.execute() if item: return item else: time.sleep(1) except WatchError: time.sleep(1) finally: self._pipe.reset() def qsize(self): return self._redis_client.zcard(self._key) def clear(self): return self._redis_client.zremrangebyrank(self._key, 0, -1)
C
UTF-8
3,095
2.703125
3
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include "../../bionic/pthread_internal.h" pthread_internal_t *__get_thread(void); #define MAX_THREAD_ID ((1 << 15) - 1) // 0 until the second thread other than the main thread is created. // 2 <= g_next_tid < 32768 after the second thread is created. // Note that bionic's mutex depends on 15 bit thread ID. See // libc/bionic/pthread.c for detail. static pid_t g_next_tid; // g_tid_map[tid] will be zero if and only if the tid is not allocated. static int8_t g_tid_map[MAX_THREAD_ID + 1]; // Protects global variables above. static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; pid_t gettid() { // Defined in libc/stdlib/exit.c. Updated to 1 at the beginning of // pthread_create in libc/bionic/pthread.c. No lock is needed when // accessing this variable since pthread_create is always a memory // barrier as written in the __thread_entry function. extern int __isthreaded; if (!__isthreaded) { // The second thread is not created yet. The thread ID of the main // thread is always 1 on NaCl bionic. Note that we may not be able // to access TLS yet. We should have this test first. return 1; } int tid = __get_thread()->tid; if (tid) return tid; static const int kStderrFd = 2; static const char kMsg[] = "gettid is called for uninitialized thread\n"; write(kStderrFd, kMsg, sizeof(kMsg) - 1); abort(); } __attribute__((visibility("hidden"))) pid_t __allocate_tid() { pthread_mutex_lock(&g_mu); int cnt = 0; // The main thread always uses TID=1. while (g_next_tid < 2 || g_tid_map[g_next_tid]) { g_next_tid++; if (g_next_tid > MAX_THREAD_ID) g_next_tid = 1; // All thread IDs are being used. if (++cnt > MAX_THREAD_ID) { pthread_mutex_unlock(&g_mu); return -1; } } pid_t tid = g_next_tid; g_tid_map[tid] = 1; pthread_mutex_unlock(&g_mu); return tid; } __attribute__((visibility("hidden"))) void __deallocate_tid(pid_t tid) { pthread_mutex_lock(&g_mu); if (!g_tid_map[tid]) { static const int kStderrFd = 2; if (!tid) { static const char kMsg[] = "__deallocate_tid is called for tid=0\n"; write(kStderrFd, kMsg, sizeof(kMsg) - 1); } else { static const char kMsg[] = "__deallocate_tid is called for uninitialized thread\n"; write(kStderrFd, kMsg, sizeof(kMsg) - 1); } abort(); } g_tid_map[tid] = 0; pthread_mutex_unlock(&g_mu); }
Java
UTF-8
1,664
2.65625
3
[ "BSD-3-Clause", "MIT" ]
permissive
package org.firstinspires.ftc.teamcode.hardware.scoring.intake; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.teamcode.hardware.State; import org.firstinspires.ftc.teamcode.hardware.Subsystem; public class Intake implements Subsystem { public Intake() {} private DcMotor motor; private enum intakeState implements State { INTAKING("Intaking"), OUTTAKING("Outtaking"), STOPPED("Stopped"); private String str; intakeState(String str) {this.str = str;} @Override public String getStateVal() { return this.str; } } private intakeState state; @Override public void init(HardwareMap hwMap) { motor = hwMap.get(DcMotor.class, "intake"); motor.setDirection(DcMotorSimple.Direction.FORWARD); motor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); motor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); state = intakeState.STOPPED; } @Override public void start() { } @Override public void reset() { motor.setPower(0); state = intakeState.STOPPED; } @Override public void stop() { motor.setPower(0); state = intakeState.STOPPED; } public void intake() { motor.setPower(-.7); state = intakeState.INTAKING; } public void outtake() { motor.setPower(.7); state = intakeState.OUTTAKING; } @Override public State getState() { return state; } }
JavaScript
UTF-8
903
3.484375
3
[ "MIT" ]
permissive
"use strict"; function swap(data, i, j) { var tmp; if (i === j) { return; } tmp = data[j]; data[j] = data[i]; data[i] = tmp; } function partition(data, start, end) { var pivot = data[start]; var i, j, tmp; for (i = start + 1, j = start; i < end; i++) { if (data[i] < pivot) { swap(data, i, ++j); } } swap(data, start, j); return j; } function findK(data, start, end, k) { var pos; while (start < end) { pos = partition(data, start, end); if (pos === k) { return data[k]; } if (pos > k) { end = pos; } else { start = pos + 1; } } } module.exports = { // Calculate n-th percentile of 'data' using Nearest Rank Method // http://en.wikipedia.org/wiki/Percentile#The_Nearest_Rank_method calc: function (data, n) { return findK(data.concat(), 0, data.length, Math.ceil(data.length * n / 100) - 1); } };
Ruby
UTF-8
11,028
3.265625
3
[]
no_license
# frozen_string_literal: true # typed: true require 'sorbet-runtime' require 'scanf' class Complex def x self.real end def y self.imag end end class String def last self[-1] end def first self[0] end end class Array def top self[0] end def right self[1] end def bottom self[2] end def left self[3] end def top=(v) self[0] = v end def right=(v) self[1] = v end def bottom=(v) self[2] = v end def left=(v) self[3] = v end def flip_edges(op) if op == 'none' self.dup elsif op == 'vert' [self.bottom, self.right.reverse, self.top, self.left.reverse] elsif op == 'horz' [self.top.reverse, self.left, self.bottom.reverse, self.right] else raise "huh #{op}" end end def flip_both(op1, op2) self.flip_edges(op1).flip_edges(op2) end end # AoC class AoC extend T::Sig def initialize(data) @tile_rows = {} @original_tile_rows = {} data.split("\n\n").each do |tiles| rows = tiles.split("\n") key = rows[0].scanf("Tile %d:")[0] @tile_rows[key] = rows[1..] @original_tile_rows[key] = rows[1..] end @min_x = 0 @min_y = 0 @max_x = 0 @max_y = 0 @pos_to_tile = {} @tiles_to_pos = {} @directions = 4.times.to_a @opp_directions = @directions.rotate(2) @direction_words = ["top ", "right ", "bottom", "left "] @opp_direction_words = @direction_words.rotate(2) end def dir_word(dir, opp: false, wide: false) word = (opp ? @opp_direction_words : @direction_words)[dir] word = word.strip unless wide word end def pos_direction(pos, direction) if direction == 0 pos += 1i elsif direction == 1 pos += 1 elsif direction == 2 pos -= 1i elsif direction == 3 pos -= 1 end pos end def set_tile_pos(tile, pos) @pos_to_tile[pos] = tile @tiles_to_pos[tile] = pos @min_x = [@min_x, pos.x].min @min_y = [@min_y, pos.y].min @max_x = [@max_x, pos.x].max @max_y = [@max_y, pos.y].max end def build_tile_edges! @tile_edges = @tile_rows.map do |id, rows| [id, get_tile_edges(rows)] end.to_h end def get_tile_edges(rows) top = rows[0] right = rows.map(&:last).join("") bottom = rows[-1] left = rows.map(&:first).join("") [top, right, bottom, left] end def does_tile_fit(our_id:, our_edge:, their_id:, their_direction:) # Try all rotations 4.times do |rotate_index| # Try all pairs of mirroring ["none", "vert", "horz"].repeated_combination(2).each do |flip1, flip2| other_tile = flip_tile(flip_tile(rotate_tile(@tile_rows[their_id], rotate_index), flip1), flip2) real_other_edges = get_tile_edges(other_tile) if our_edge == real_other_edges[their_direction] # puts "FOUND1: rot(#{rotate_index}), flip(#{flip1}, #{flip2})" # puts "#{their_id} is placed #{dir_word(their_direction, opp: true)} to #{our_id}" @tile_edges[their_id] = real_other_edges @tile_ops[their_id] = [rotate_index, flip1, flip2] @tile_rows[their_id] = other_tile # puts "ops for #{their_id} are #{rotate_index}, #{flip1}, #{flip2}" return true end end end return false end def bruteforce_find(our_id:, direction:) # puts "\n## Looking #{dir_word(direction)} of #{our_id}\n\n" our_edge = @tile_edges[our_id][direction] their_direction = @opp_directions[direction] @tiles_to_search.each do |their_id| fits = does_tile_fit( our_id: our_id, our_edge: our_edge, their_id: their_id, their_direction: their_direction ) if fits return their_id end end return nil end def one tile_count = @tile_rows.size tiles_per_row = Math.sqrt(tile_count).to_i puts "There are #{tile_count} tiles, tiles_per_row is #{tiles_per_row}" @tile_ops = {} @tiles_to_search = [] @op_tree = {} build_tile_edges! @tile_rows.map do |id, _| @tiles_to_search << id @tile_ops[id] = [] end pos = 0 + 0i first_tile = @tiles_to_search.shift set_tile_pos(first_tile, pos) @tile_ops[first_tile] = [0, 'none', 'none'] @op_tree[first_tile] = [] @positions_to_process = [0 + 0i] while !@positions_to_process.empty? pos = @positions_to_process.shift tile_id = @pos_to_tile[pos] # Look in each direction @directions.each do |direction| try_pos = pos_direction(pos, direction) # Don't look again if we already found something there if (tile = @pos_to_tile[try_pos]) # puts "- Not looking #{dir_word direction} because tile #{tile} is there." next end found_tile = bruteforce_find(our_id: tile_id, direction: direction) if found_tile set_tile_pos(found_tile, try_pos) @tiles_to_search.delete(found_tile) # puts "\n- Placing #{found_tile} at #{try_pos}" @positions_to_process << try_pos end end end corners = [ @pos_to_tile[@min_x + 1i*@min_y], # topleft @pos_to_tile[@max_x + 1i*@min_y], # topright @pos_to_tile[@max_x + 1i*@max_y], # bottomright @pos_to_tile[@min_x + 1i*@max_y], # bottomleft ] [corners, corners.inject(:*)] end # trim outermost edge def trim_all_tiles! @tile_rows = @tile_rows.map do |id, rows| # cut top and bottom rows = rows[1..-2] # cut first and last rows = rows.map {|str| str[1..-2] } [id, rows] end.to_h end def flip_tile(rows, direction) if direction == "horz" return rows.map(&:reverse) elsif direction == "vert" return rows.reverse elsif direction == 'none' return rows.dup else raise direction end end def rotate_tile(rows, amount) rows = rows.dup if amount == 0 return rows end rows = rows.map(&:chars) amount.times do rows = rows.transpose.map(&:reverse) end rows.map! &:join rows end def apply_tile_ops! @tile_rows = @tile_rows.map do |id, rows| ops = @tile_ops[id] puts "applying ops for #{id} are #{ops}" rotate_amount, flip1, flip2 = ops rows = rotate_tile(rows, rotate_amount) rows = flip_tile(flip_tile(rows, flip1), flip2) [id, rows] end.to_h end def print_tile(id, orig: false, rows: nil) if id.is_a? Complex id = @pos_to_tile[id] elsif !id.is_a?(Integer) raise "print_tile got #{id.class}" end rows ||= (orig ? @original_tile_rows : @tile_rows)[id] puts "[Tile #{id}]" puts rows.join("\n") end def two_build_image # Build everything from part 1 puts "Part1: #{one}" # unset some things from part1 remove_instance_variable :@positions_to_process remove_instance_variable :@tiles_to_search # print layout puts (@min_y..@max_y).each do |y| (@min_x..@max_x).each do |x| tile_id = @pos_to_tile[Complex(x, y)] print "#{tile_id} " end puts end puts # make all tiles correct trim_all_tiles! # print_tile(0+0i, orig: true) # I have no idea why I need to do this @tile_rows.each do |id, rows| @tile_rows[id] = flip_tile(@tile_rows[id], 'vert') end puts 'All tiles have been flipped vertically :+1:' lines_per_tile = @tile_rows[@pos_to_tile[0 + 0i]].size puts "There are #{lines_per_tile} lines per tile.\n\n" # print layout image = [] (@min_y..@max_y).each do |y| this_rows_lines = [] 8.times do |line_y| ys = [] (@min_x..@max_x).each do |x| tile_id = @pos_to_tile[Complex(x, y)] ys << @tile_rows[tile_id][line_y] # print "#{tile_id} " end this_rows_lines << ys end # puts this_rows_lines.map{|x| x.join(" ")}.join("\n") image << this_rows_lines.map{|x| x.join} # puts # break end image.flatten! puts puts puts image.join("\n") image end def get_image img_path = $filename + ".image" if File.file?(img_path) return IO.binread(img_path).split end image = two_build_image File.write(img_path, image.join("\n")+"\n") image end def try_shape(shape) image = @image pound_offsets = [] shape.each_with_index do |row, y| row.chars.each_with_index do |char, x| if char == '#' pound_offsets << [x, y] end end end shape_width = shape.first.size image_width = image.first.size x_moves = image_width - shape_width + 1 y_moves = image.size - shape.size + 1 puts "Need to move right #{x_moves}, down #{y_moves}" y_moves.times do |y_base| x_moves.times do |x_base| base = Complex(x_base, y_base) should_print = base.x == 2 && base.y == 2 found = true pound_offsets.each do |offset| coord = base + Complex(*offset) char = image[coord.y][coord.x] # puts "#{coord} is #{char}" if should_print if char != '#' found = false end end if found puts "Found at #{base}" write_os(base, pound_offsets) end end end end def write_os(base, pound_offsets) pound_offsets.each do |offset| coord = base + Complex(*offset) @image[coord.y][coord.x] = 'O' end end def two @image = get_image puts @image.join("\n") shape = [ " # ", "# ## ## ###", " # # # # # # " ] 4.times do |rotate_index| # Try all pairs of mirroring ["none", "vert", "horz"].repeated_combination(2).each do |flip1, flip2| modified_shape = flip_tile(flip_tile(rotate_tile(shape, rotate_index), flip1), flip2) try_shape(modified_shape) end end @image.join("\n").count("#") end def test_tile_ops tile = ["abc", "def", "ghi"] puts "tile: \n#{tile.join("\n")}" puts "\nflip horz: \n#{flip_tile(tile, "horz").join("\n")}" puts "\nflip vert: \n#{flip_tile(tile, "vert").join("\n")}" puts "\nrotate_tile(tile, 0): \n#{rotate_tile(tile, 0).join("\n")}" puts "\nrotate_tile(tile, 1): \n#{rotate_tile(tile, 1).join("\n")}" puts "\nrotate_tile(tile, 2): \n#{rotate_tile(tile, 2).join("\n")}" puts "\nrotate_tile(tile, 3): \n#{rotate_tile(tile, 3).join("\n")}" tile = <<~EOF.strip.split("\n") #.#.#####. .#..###### ..#....... ######.... ####.#..#. .#...#.##. #.#####.## ..#.###... ..#....... ..#.###... EOF puts "\n\n\n\n\nOriginal:" puts tile end end def main n = ARGV.shift $filename = ARGV.first runner = AoC.new ARGF.read if n == '1' puts "Result: #{runner.one}" elsif n == '2' puts "Result: #{runner.two}" end end main
Ruby
UTF-8
195
3.3125
3
[]
no_license
=begin n = 1 while n <= 5 n.downto 1 do |i| print "* " end puts n += 1 end =end n=1 n= gets.chomp.to_i while n <= 10 n.upto 10 do |i| puts ("* " * n).rjust(1) end puts n += 1 end
C
UTF-8
1,024
3.859375
4
[]
no_license
# include <stdio.h> # include <stdlib.h> # define NO_OF_CHARS 256 # define bool int /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ char *removeDups(char *str) { bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while(*(str + ip_ind)) { temp = *(str + ip_ind); if(bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); printf("\n%s", str); res_ind++; } ip_ind++; } printf("\n ip_index %d res_index %d", ip_ind,res_ind); /* After above step string is stringiittg. Removing extra iittg after string*/ //Figure out how?? *(str+res_ind) = '\0'; return str; } /* Driver program to test removeDups */ int main() { char str[] = "geeksforgeeks"; printf("\n%s", removeDups(str)); getchar(); return 0; }
PHP
UTF-8
1,902
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php class Admin_model extends CI_Model { public function category_add($data) { if ($this->db->insert('category', $data)) { return true; } } public function category_update($data, $id) { $this->db->set($data); $this->db->where('cat_id', $id); if ($this->db->update('category', $data)) { return true; } } public function category_delete($id) { $this->db->where('cat_id', $id); if ($this->db->delete('category')) { return true; } } //product public function product_add($data) { if ($this->db->insert('product', $data)) { return true; } } public function product_delete($id) { $this->db->where('p_id', $id); if ($this->db->delete('product')) { return true; } } public function product_update($data, $id) { $this->db->set($data); $this->db->where('p_id', $id); if ($this->db->update('product', $data)) { return true; } } public function get_product($limit, $start) { $this->db->limit($limit, $start); $this->db->join('category', 'product.p_cat = category.cat_id'); $query = $this->db->get('product'); return $query->result(); } public function get_count() { return $this->db->count_all('product'); } public function get_cat_count($id) { $this->db->where('p_cat', $id); $query = $this->db->get('product'); return $query->num_rows(); } public function get_cat_product($limit, $start, $id) { $this->db->limit($limit, $start); $this->db->join('category', 'product.p_cat = category.cat_id'); $this->db->where('p_cat',$id); $query = $this->db->get('product'); return $query->result(); } } ?>
Python
UTF-8
2,558
2.609375
3
[]
no_license
import json import os import urllib.request # ftp naar de remote omgeving import ftplib import localvar from bs4 import BeautifulSoup import datetime # specify the url toscrape_page = localvar.s # query the website and return the html to the variable ‘page’ page = urllib.request.urlopen(toscrape_page) # webpagina wordt in de soup gegooid soup = BeautifulSoup(page, 'html.parser') xtra = '' AlleShows = [] for item in soup.find_all('div'): if type(item.get('class')) is list and 'agendeDetailContainer' in item.get('class'): # eerste de basisgegevens opzoeken for it in item.find_all('span'): if type(it.get('class')) is list and 'p15' in it.get('class'): aShow = it.get_text().strip().replace('\n', ';').split(';') #vervolgens in een ander stuk de link en en/og het uitverkocht is for it2 in item.find_all('a'): if type(it2.get('class')) is list and 'infoLink' in it2.get('class'): href = it2.get('href') if type(it2.get('class')) is list and 'ticketAT' in it2.get('class') and 'soldout' in it2.get('class'): xtra = [it2.get('href').split('=')[1], href, 'soldout'] else: if 'ticketAT' in it2.get('class'): xtra = [it2.get('href').split('=')[1], href, ''] newShow = aShow + xtra AlleShows.append(newShow) # array van array omzetten naar array van dict's showsArrOfDicts = [] for show in AlleShows: if show[1] == 'vandaag': today = datetime.date.today() show[1] = today.strftime("%d %B") if show[1] == 'morgen': tm = datetime.date.today() + datetime.timedelta(days=1) show[1] = tm.strftime("%d %B") thisdict = {'tijd': show[0], 'dag': show[1], 'naam': show[2], 'type': show[3], 'id' : show[4], 'url': show[5], 'soldout': show[6]} showsArrOfDicts.append(thisdict) myFile = 'show_json.json' if os.path.exists(myFile): os.remove(myFile) # json dump van de shows with open(myFile, 'a') as write_file: write_file.write('[') cnt = 1 # vervolgens iedere dict json dumpen en wrappen in een array for ds in showsArrOfDicts: json.dump(ds, write_file) if cnt < len(showsArrOfDicts): write_file.write(',') cnt += 1 write_file.write(']') # maximale grootte vergroten/begrenzen ftplib.FTP.maxline = 65536 ftp = ftplib.FTP(localvar.h) ftp.login(localvar.un, localvar.ww) with open(myFile, 'rb') as ftpup: ftp.storbinary('STOR ' + myFile, ftpup) ftp.close()
Python
UTF-8
161
3.984375
4
[]
no_license
def programFive(x): for i in range(1, x + 1): if x % i == 0: print(i) x = int(input("Please enter an integer: ")) print(programFive(x))
C
UTF-8
378
2.796875
3
[]
no_license
#ifndef BST_H #define BST_H #include <stdlib.h> #include <stdio.h> typedef struct treeNode { int data; struct treeNode *pRight; struct treeNode *pLeft; }TreeNode; TreeNode *makeNode(int newData); void insertNode(TreeNode **pRoot, int data); void inOrderTraversal(TreeNode *pRoot); void preOrderTraversal(TreeNode *pRoot); void postOrderTraversal(TreeNode *pRoot); #endif
Python
UTF-8
2,996
4.03125
4
[]
no_license
# --------------------------------------- # CSCI 127, Joy and Beauty of Data # Program 3: Msuic CSV Library # Jack Telenko # Last Modified: October 18, 2018 # --------------------------------------- # Answers questions about song excel sheet asked in #1-5. # --------------------------------------- # -------------------------------------- def menu(): print() print("1. Identify longest song.") print("2. Identify number of songs in a given year.") print("3. Identify all songs by a given artist.") print("4. Enter an artists name to request their identification code.") print("5. Quit.") def longest_song(): file = open("music.csv", "r") file.readline() longest = [0,'placeHolder'] for line in file: row = line.split(",") if float(row[9]) > longest[0]: longest[0] = float(row[9]) longest[1] = row[33] print("Title:", longest[1]) print("Length to nearest second:", round(longest[0])) file.close() def songs_by_year(year): file = open("music.csv", "r") file.readline() numSongs = 0 file.readline() for line in file: row = [] row = line.split(',') if int(row[len(row)-1])== int(year): numSongs += 1 print ("The number of songs from", year, "is", numSongs) file.close() def all_songs_by_artist(artist): file = open("music.csv", "r") file.readline() alist = [] count = 0 print("Songs in alphabetical order") print("---------------------------") for line in file: row = line.split(",") song = row[len(row)-14] if artist.upper() == row[2].upper(): alist.append(song) alist.sort() for song in alist: count += 1 print(str(count) + " " + song) print("---------------------------") file.close() def artist_id(artist): file = open("music.csv", "r") file.readline() alist = [] for line in file: row = line.split(",") ident = row[len(row)-34] if artist.upper() == row[2].upper(): alist.append(ident) for ident in alist: pass print("The artist id for", artist, "is", ident) file.close() return ident # -------------------------------------- def main(): choice = 0 while (choice != 5): menu() choice = int(input("Enter your choice: ")) if (choice == 1): longest_song() elif (choice == 2): year = int(input("Enter desired year: ")) songs_by_year(year) elif (choice == 3): artist = input("Enter name of artist: ").lower() all_songs_by_artist(artist) elif (choice == 4): artist = input("Enter artist name: ").lower() artist_id(artist) elif (choice != 5): print("That is not a valid option. Please try again.") main()
Java
UTF-8
12,838
2.078125
2
[]
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 becasuninorte; import javax.swing.JOptionPane; /** * * @author JONATHAN */ public class BecaBeneficio extends javax.swing.JFrame { static SQLclass query; String v1[] = {"id", "nombre", "cupos"}; String v2[] = {"id", "descripción"}; String v[] = {"id_beca", "nombre_beca", "beneficio"}; String idBecaTable, idBeneficioTable, NombreBeca, DesBeneficio; public BecaBeneficio(SQLclass query) { initComponents(); this.setLocationRelativeTo(null); this.idBeca.setEditable(false); this.idBeneficio.setEditable(false); this.query = query; Becas_table.setModel(query.query("select * from beca", v1)); Beneficios_table.setModel(query.query("select * from beneficio", v2)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel4 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); Becas_table = new javax.swing.JTable(); jLabel3 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); Beneficios_table = new javax.swing.JTable(); jLabel4 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); Beca_beneficios_table = new javax.swing.JTable(); jLabel5 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); idBeca = new javax.swing.JTextField(); idBeneficio = new javax.swing.JTextField(); Join = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setPreferredSize(new java.awt.Dimension(1100, 652)); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS)); jPanel4.setBackground(new java.awt.Color(255, 7, 11)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(255, 7, 11)); jPanel1.setPreferredSize(new java.awt.Dimension(512, 309)); jPanel1.setLayout(new java.awt.BorderLayout()); Becas_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); Becas_table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Becas_tableMouseClicked(evt); } }); jScrollPane1.setViewportView(Becas_table); jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER); jLabel3.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Becas"); jPanel1.add(jLabel3, java.awt.BorderLayout.PAGE_START); jPanel4.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1, 440, 320)); jPanel2.setBackground(new java.awt.Color(255, 7, 11)); jPanel2.setPreferredSize(new java.awt.Dimension(512, 309)); jPanel2.setLayout(new java.awt.BorderLayout()); Beneficios_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); Beneficios_table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Beneficios_tableMouseClicked(evt); } }); jScrollPane2.setViewportView(Beneficios_table); jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER); jLabel4.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("Beneficios"); jPanel2.add(jLabel4, java.awt.BorderLayout.PAGE_START); jPanel4.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(649, 11, 450, 309)); jPanel3.setBackground(new java.awt.Color(255, 7, 11)); jPanel3.setLayout(new java.awt.BorderLayout()); Beca_beneficios_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); Beca_beneficios_table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Beca_beneficios_tableMouseClicked(evt); } }); jScrollPane3.setViewportView(Beca_beneficios_table); jPanel3.add(jScrollPane3, java.awt.BorderLayout.CENTER); jLabel5.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText("Beneficios de la beca seleccionada"); jPanel3.add(jLabel5, java.awt.BorderLayout.PAGE_START); jPanel4.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 345, 1100, 310)); jLabel1.setFont(new java.awt.Font("Monospaced", 1, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Id Beca:"); jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 150, -1, 20)); jLabel2.setFont(new java.awt.Font("Monospaced", 1, 12)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Id beneficio:"); jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 190, -1, 20)); idBeca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { idBecaActionPerformed(evt); } }); jPanel4.add(idBeca, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 150, 72, -1)); jPanel4.add(idBeneficio, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 190, 72, -1)); Join.setText("Unir"); Join.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JoinActionPerformed(evt); } }); jPanel4.add(Join, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 220, 170, -1)); getContentPane().add(jPanel4); pack(); }// </editor-fold>//GEN-END:initComponents private void JoinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JoinActionPerformed String idbeca = idBeca.getText(); String idbeneficio = idBeneficio.getText(); if (idbeca.equals("") || idbeneficio.equals("")) { JOptionPane.showMessageDialog(null, "Debe seleccionar una beca y un beneficio"); } else { if (JOptionPane.showConfirmDialog(null, "¿Confirma darle a la beca " + NombreBeca + " con id=" + idbeca + "\n el beneficio: " + DesBeneficio) == 0) { String comand = "insert into beneficio_de_beca values (" + idbeca + "," + idbeneficio + ")"; System.out.println(comand); query.ejecutar(comand); String join = "select b.id, nombre, descripcion from beca b inner join beneficio_de_beca bdb on (b.id = bdb.id_beca)" + " inner join beneficio bn on (bdb.id_beneficio = bn.id) where b.id = " + idbeca; Beca_beneficios_table.setModel(query.query(join, v)); idBeca.setText(""); idBeneficio.setText(""); } } }//GEN-LAST:event_JoinActionPerformed private void Becas_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Becas_tableMouseClicked int seleccionado = Becas_table.rowAtPoint(evt.getPoint()); idBecaTable = String.valueOf(Becas_table.getValueAt(seleccionado, 0)); idBeca.setText(idBecaTable); NombreBeca = String.valueOf(Becas_table.getValueAt(seleccionado, 1)); String join = "select b.id, nombre, descripcion from beca b inner join beneficio_de_beca bdb on (b.id = bdb.id_beca)" + " inner join beneficio bn on (bdb.id_beneficio = bn.id) where b.id = " + idBecaTable; Beca_beneficios_table.setModel(query.query(join, v)); }//GEN-LAST:event_Becas_tableMouseClicked private void Beneficios_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Beneficios_tableMouseClicked int seleccionado = Beneficios_table.rowAtPoint(evt.getPoint()); idBeneficioTable = String.valueOf(Beneficios_table.getValueAt(seleccionado, 0)); idBeneficio.setText(idBeneficioTable); DesBeneficio = String.valueOf(Beneficios_table.getValueAt(seleccionado, 1)); }//GEN-LAST:event_Beneficios_tableMouseClicked private void Beca_beneficios_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Beca_beneficios_tableMouseClicked // TODO add your handling code here: }//GEN-LAST:event_Beca_beneficios_tableMouseClicked private void idBecaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idBecaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_idBecaActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(BecaBeneficio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BecaBeneficio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BecaBeneficio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BecaBeneficio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BecaBeneficio(query).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable Beca_beneficios_table; private javax.swing.JTable Becas_table; private javax.swing.JTable Beneficios_table; private javax.swing.JButton Join; private javax.swing.JTextField idBeca; private javax.swing.JTextField idBeneficio; 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.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; // End of variables declaration//GEN-END:variables }
Shell
UTF-8
732
3.234375
3
[]
no_license
#!/bin/sh # chkconfig:345 85 15 # description:watch service # processname: watchpy lock="webhealth.py" start(){ echo “service start....” su root -c "python /home/monitor/webhealth.py -a www.baidu.com -p 80 &" } # 停止服务方法 stop(){ echo "services stop ..." pkill -f $lock } status(){ if [ -e $lock ];then echo "$0 service start" else echo "$0 service stop" fi } #重新启动 restart(){ stop start } case "$1" in "start") start ;; "stop") stop ;; "status") status ;; "restart") restart ;; *) echo "$0 start|stop|status|restart" ;; esac
Python
UTF-8
1,989
3.109375
3
[]
no_license
################################################################################ ####################### Extract the Window/Door Sensors' Data ################## ######## To calcuat the opening area of each window/door ######## ######## write data (local_time, sensor_id, motion_status) into a file ######### ################################################################################ #!/usr/bin/env python import sys import string import re import os def process_extracted_data(line, d, all_extracted_data): str_split = re.split(r'\|', line) ### Skip some special notation: ---------+------ if len(str_split) >= 2: local_time = str_split[5].strip() ## local time motion_status = str_split[6].rstrip() ## OPEN/CLOSE; sensor_id = str_split[9].rstrip() ## sensor id/name motion_status = motion_status.replace(" ","") sensor_id = sensor_id.replace(" ","") temp = [local_time, sensor_id, motion_status] all_extracted_data.append(temp) if sensor_id in d.keys(): d[sensor_id] += [temp] else: d[sensor_id] = [temp] return d, all_extracted_data def extract_sensor_data_func(finpath, sensor_type): house_name = re.split(r'/', finpath) print("") print("#####################") print("Start extracting %s sensor data from house: %s"%(sensor_type, house_name[-2])) fin = open(finpath, 'rU') raw_data = fin.readlines() fin.close() d = {} all_extracted_data = [] for line in raw_data: if (sensor_type == "window_door" and ("OPEN" in line or "CLOSE" in line)): d, all_extracted_data = process_extracted_data(line, d, all_extracted_data) if (sensor_type == "temperature" and "Control4-Temperature" in line): d, all_extracted_data = process_extracted_data(line, d, all_extracted_data) if (sensor_type == "motion" and "Control4-Motion" in line): d, all_extracted_data = process_extracted_data(line, d, all_extracted_data) print("Finish extracting %s sensor data from house: %s"%(sensor_type, house_name[-2])) return d, all_extracted_data
Java
UTF-8
1,043
2.140625
2
[]
no_license
package actions; import hlta.testexec.testcontrol.java.ActionBase; import db.*; import hlta.testexec.testcontrol.java.TestCase; public class Db2Logon extends ActionBase { public Db2Logon(Object object, Object param, Object extParam, Object[] args) { super(object, param, extParam, args); // TODO Auto-generated constructor stub } @Override public void doAction(Object object, Object param, Object extParam, TestCase.Step step,Object... args) {} public void doAction(Object object, Object param, Object extParam, Object... args) { // TODO Auto-generated method stub // object: dbName; param: userName; extParam: pwd; args: [address, instance] AutoQuery query = null; if(args!=null&&args.length>=1){ if(args[0]==null&&args[1]==null){ query = new AutoQuery((String)object,(String)param,(String)extParam); query.connect(); } else { query = new AutoQuery((String)args[0],(String)args[1],(String)object,(String)param,(String)extParam); query.remoteConnect(); } } } }
Java
UTF-8
2,157
2.375
2
[ "Apache-2.0", "BSD-3-Clause", "LGPL-2.0-or-later" ]
permissive
/* * Copyright 2014 Confluent 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 io.confluent.rest.examples.helloworld; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotEmpty; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import io.confluent.rest.annotations.PerformanceMetric; @Path("/hello") @Produces("application/vnd.hello.v1+json") public class HelloWorldResource { HelloWorldRestConfig config; public HelloWorldResource(HelloWorldRestConfig config) { this.config = config; } /** * A simple response entity with validation constraints. */ public static class HelloResponse { @NotEmpty private String message; public HelloResponse() { /* Jackson deserialization */ } public HelloResponse(String message) { this.message = message; } @JsonProperty public String getMessage() { return message; } } @GET @PerformanceMetric("hello-with-name") public HelloResponse hello(@QueryParam("name") String name) { // Use a configuration setting to control the message that's written. The name is extracted from // the query parameter "name", or defaults to "World". You can test this API with curl: // curl http://localhost:8080/hello // -> {"message":"Hello, World!"} // curl http://localhost:8080/hello?name=Bob // -> {"message":"Hello, Bob!"} return new HelloResponse( String.format(config.getString(HelloWorldRestConfig.GREETING_CONFIG), (name == null ? "World" : name))); } }
Python
UTF-8
135
3.0625
3
[]
no_license
import random a = random.sample(range(1, 50), 14) b = random.sample(range(1, 50), 19) c = print([i for i in a for j in b if i == j])
Java
UTF-8
2,715
2.390625
2
[]
no_license
package com.example.tp01_exo8; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity implements go_to.SendMessages { ListView lv_horaires ; ArrayAdapter<String>adapter; ListAdapter list_adapter; List<HashMap<String, String>> liste = new ArrayList<HashMap<String, String>>(); HashMap<String, String> element ; private static final String[] VILLES = new String[]{"Paris","Montpellier","Lyon","Nime","Lille","Strasbourg", "Grenoble","Tours","Perpignan","Toulouse","Marseille", "Nantes","Nice","Bordeaux","Rennes"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv_horaires= (ListView)findViewById(R.id.lv_horaires); } // receive data form fragments @Override public void iAmMSG(String msg) { String d = msg.split(":")[0]; String a = msg.split(":")[1]; final String[][] hors = new String[][]{ {"Lundi","8:00"},{"Lundi","9:00"},{"Lundi","10:00"},{"Lundi","11:00"},{"Lundi","12:00"},{"Lundi","13:00"}, {"Mardi","8:00"},{"Mardi","9:00"},{"Mardi","10:00"},{"Mardi","11:00"},{"Mardi","12:00"},{"Mardi","13:00"}, {"Mercredi","8:00"},{"Mercredi","9:00"},{"Mercredi","10:00"},{"Mercredi","11:00"},{"Mercredi","12:00"},{"Mercredi","13:00"}, {"Jeudi","8:00"},{"Jeudi","9:00"},{"Jeudi","10:00"},{"Jeudi","11:00"},{"Jeudi","12:00"},{"Jeudi","13:00"}, {"Vendredi","8:00"},{"Vendredi","9:00"},{"Vendredi","10:00"},{"Vendredi","11:00"},{"Vendredi","12:00"},{"Vendredi","13:00"}, {"Samedi","8:00"},{"Samedi","9:00"},{"Samedi","10:00"},{"Samedi","11:00"},{"Samedi","12:00"},{"Samedi","13:00"}, {"Dimanche","11:00"} }; for (int i=0; i<hors.length;i++){ element = new HashMap<String, String>(); element.put("v1",hors[i][0]); element.put("v2",hors[i][1]); liste.add(element); list_adapter = new SimpleAdapter(this,liste,android.R.layout.simple_list_item_2, new String[]{"v1","v2"},new int[] {android.R.id.text1,android.R.id.text2}); } adapter =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,VILLES); lv_horaires.setAdapter(list_adapter); } }
Java
UTF-8
577
2.140625
2
[]
no_license
package com.xinyu.Utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class utils { private static Configuration cfg=null; private static SessionFactory sessionFactory=null; static { cfg=new Configuration(); cfg.configure(); sessionFactory=cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static Session getSessionObject(){ return sessionFactory.getCurrentSession(); } }
PHP
UTF-8
245
3.046875
3
[]
no_license
<?php $a = [ 'a' => 1, 'b' => 2, 'c' => 'Yo <3 a Json' ]; $a = json_encode($a); echo $a; $b = json_decode($a, true); var_dump($b); echo "<br>"; echo "<br>"; echo $b["c"] . ' | '. $b['a']. ' | '. $b['b']. ' | '; ?>
Python
UTF-8
225
2.59375
3
[ "MIT" ]
permissive
with open('SPECS.md', 'r') as f: t = f.read() print('A:',sum(map(t.count,"aA")),'\nE:',sum(map(t.count,"Ee")),'\nI:',sum(map(t.count,"iI")),'\nO:',sum(map(t.count,"oO")),'\nU:',sum(map(t.count,"uU")))
C++
UTF-8
551
3.890625
4
[]
no_license
// This program reads data from a file into an array. #include <iostream> #include <fstream> using namespace std; int main() { const int ARRAY_SIZE = 10; // Array size int numbers[ARRAY_SIZE]; // Array with 10 elements int count = 0; // Loop counter variable ifstream inputFile; // Input file stream object // Open the input file - TenNumbers.txt. // Read the numbers from the file into the array. // Close the file. inputFile.close(); // Display the numbers read: cout << "The numbers are: "; return 0; }
Java
UTF-8
317
1.65625
2
[]
no_license
package com.exchange.rate.exchrate.repo; import com.exchange.rate.exchrate.enteties.ExchangeRateModel; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ExchangeRateRepo extends JpaRepository<ExchangeRateModel, Integer> { }
Python
UTF-8
633
3.625
4
[]
no_license
import string try: def Calcular_leta_DNI(): lista = "TRWAGMYFPDXBNJZSQVHLCKE" numeros = "1234567890" dni =input("Introduzca el DNI(con letra): ") respuesta= "No ha introducido un DNI valido" if (len(dni) == 9): letra = dni[8].upper() dni = dni[:8] if ( len(dni) == len( [n for n in dni if n in numeros] ) ): if lista[int(dni)%23] == letra: respuesta="El DNI introducido es correcto" print(respuesta) except: print('Error, ha ocurrido algo imprevisto') print('Vuelve a intentarlo') Calcular_leta_DNI()
Go
UTF-8
1,370
3.546875
4
[ "MIT" ]
permissive
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * 84. Largest Rectangle in Histogram * * Hard * * Given an array of integers heights representing the histogram's bar height where the width of * each bar is 1, return the area of the largest rectangle in the histogram. * * Example 1: * Input: heights = [2,1,5,6,2,3] * * Output: 10 * Explanation: The above is a histogram where width of each bar is 1. * The largest rectangle is shown in the red area, which has an area = 10 units. * * Example 2: * Input: heights = [2,4] * Output: 4 * * Constraints: * 1 <= heights.length <= 105 * 0 <= heights[i] <= 104 * *** =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ func largestRectangleArea(heights []int) int { heights = append([]int{-2}, heights...) heights = append(heights, -1) size := len(heights) stack := make([]int, 1, size) end := 1 res := 0 for end < size { if heights[stack[len(stack)-1]] < heights[end] { stack = append(stack, end) end++ continue } begin := stack[len(stack)-2] index := stack[len(stack)-1] height := heights[index] area := (end - begin - 1) * height res = max(res, area) stack = stack[:len(stack)-1] } return res } func max(a, b int) int { if a > b { return a } return b }
C
UTF-8
3,175
3.453125
3
[]
no_license
/* Carlos Eduardo de Oliveira Ribeiro - 180099094 Estudo dirigido 10 - Problema do pombo correio usando variaveis de condicao. */ #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <semaphore.h> #include "unistd.h" #define N 10 //número de usuários #define CARTAS 20 //quantidade de cartas na mochila int contador = 0; int local = 0; pthread_cond_t usuario = PTHREAD_COND_INITIALIZER; pthread_cond_t pombo = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void * f_usuario(void *arg); void * f_pombo(void *arg); int main(int argc, char **argv){ int i; pthread_t usuario[N]; int *id; for(i = 0; i < N; i++){ id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&(usuario[i]),NULL,f_usuario, (void *) (id)); } pthread_t pombo; id = (int *) malloc(sizeof(int)); *id = 0; pthread_create(&(pombo),NULL,f_pombo, (void*) (id)); pthread_join(pombo,NULL); } void * f_pombo(void *arg){ while(1){ pthread_mutex_lock(&lock); while(contador != CARTAS){ // Enquanto nao tiver cartas suficientes na mochila do pombo o pombo dorme printf("Pombo dormindo\n"); pthread_cond_wait(&pombo, &lock); } printf("Pombo indo da cidade A até a B\n"); // Pombo se locomove para a cidade B local = 1; // Altera o lugar do pombo pthread_mutex_unlock(&lock); sleep(5); // Sleep para atrasar a chegada do pombo ao local A pthread_mutex_lock(&lock); printf("Pombo voltou para a cidade A\n"); local = 0; // Flag indicadora, mostrando que o pombo esta na cidade certa contador = 0; // Contador da quantidade de cartas na mochila printf("Acordando os usuários\n"); pthread_cond_broadcast(&usuario); // Acordando os usuarios pois o pombo ja esta disponivel a receber cartas. pthread_mutex_unlock(&lock); } } void * f_usuario(void *arg){ int id = *((int *) arg ); while(1){ sleep(2); pthread_mutex_lock(&lock); printf("Usuario %d escrevendo\n", id); // Usuario escrevendo uma carta sleep(1); while( local == 1 || contador == CARTAS){ //Caso o pombo não esteja em A ou a mochila estiver cheia, então o usuario dorme printf("Pombo não esta no local ou a mochila ta cheia, usuario %d esta dormindo\n", id); pthread_cond_wait(&usuario, &lock); } contador++; printf("Usuario %d colocou a carta na mochila do pombo", id); //Posta sua carta na mochila do pombo printf("\t\tMochila %d\n", contador); sleep(1); if(contador == CARTAS){ //Caso a mochila fique cheia, acorda o pombo pthread_cond_signal(&pombo); } pthread_mutex_unlock(&lock); } }
Markdown
UTF-8
79,113
2.640625
3
[]
no_license
# 13장 동시성 이번 장에서는 동시성(concurrent) 코드 작성이라는 중요한 주제를 다룬다. 이번 장의 목표는 코루틴을 이해하는 것이다. 코루틴은 코틀린의 뛰어난 기능 중 하나로 버전 1.1부터 도입됐고 1.3부터 정식으로 릴리스(release) 상태로 격상됐다. 먼저 코틀린 코루틴을 뒷받침하는 일시중단 가능한 함수(suspending function)와 구조적인 복잡성에 대해 살펴보고, 조금씩 동시성 흐름 제어, 코루틴의 생명 주기에 따른 상태 변화, 코루틴 취소나 코루틴의 예외 처리, 동시성 작업이 스레드를 할당받는 방법 등의 주제로 나아간다. 그 후, 동시성 작업 사이에 통신을 구현하거나 스레드 안전한(thread-safe) 방식으로 변경 가능한 상태를 공유하고 싶을 때 사용할 수 있는 채널이나 액터와 같은 주제도 살펴본다. 마무리로는 스레드 생성, 동기화(synchronization)와 락(lock) 사용 등 자바 동시성 API를 코틀린에서 사용할 때 도움이 되는 유틸리티들에 대해 논의한다. ## 구조 - 코루틴 - 동시성 통신 - 자바 동시성 사용 ## 목표 코루틴 라이브러리가 제공하는 동시성 기본 요소들을 사용하는 방법을 배우고, 이를 통해 규모를 가변적으로 조절할 수 있는(scalable), 반응형(responsive) 코드를 작성한다. ## 코루틴 코틀린 프로그램에서도 쉽게 자바 동시성 기본 요소를 사용해 스레드 안전성을 달성할 수 있다. 하지만 자바 동시성 요소를 사용해도 대부분의 동시성 연산이 블러킹(blocking) 연산이기 때문에 여전히 몇가지 문제가 남는다. 다른 말로 설명하면, `Thread.sleep()`, `Thread.join()`, `Object.wait()`은 실행이 끝날 때까지 블럭된다. 스레드를 블럭하고 실행을 나중에 재개하려면 시스템 수준에서 계산 비용이 많이 드는 문맥 전환(context switch)을 해야 하기 때문에 프로그램 성능에 부정적인 영향이 있을 수 있다. 설상가상으로 스레드마다 상당한 양의 시스템 자원을 유지해야 하기 때문에 동시성 스레드를 아주 많이 사용하는 것은 비실용적이거나 (운영체제나 시스템 종류에 따라) 아예 불가능할 수도 있다. 더 효율적인 접근 방법은 비동기(asynchronous) 프로그래밍이다. 동시성 연산에 대해 해당 연산이 완료될 때 호출될 수 있는 람다를 제공할 수 있고, 원래 스레드는 블럭된 상태로 작업 완료를 기다리는 대신 (고객 요청을 처리하거나 UI 이벤트를 처리하는 등의) 다른 유용한 작업을 계속 수행할 수 있다. 이런 접근 방법의 가장 큰 문제는 일반적인 명령형 제어 흐름을 사용할 수 없어서 엄청나게 코드 복잡도가 늘어난다는 점에 있다. 코틀린에서는 두 접근 방법의 장점을 함께 취할 수 있다. 코루틴이라는 강력한 메커니즘 덕분에 우리에게 익숙한 명령형 스타일로 코드를 작성하면 컴파일러가 코드를 자동으로 효율적인 비동기 계산으로 변환해준다. 이런 메커니즘은 실행을 잠시 중단했다가 나중에 중단한 지점부터 실행을 다시 재개할 수 있는 일시중단 가능한 함수라는 개념을 중심으로 이뤄진다. [코틀린 버전 1.4.3에 맞추겠습니다.] 대부분의 코루틴 기능이 별도 라이브러리로 제공되기 때문에 명시적으로 프로젝트 설정에 이를 추가해야 한다. 이 책에서 사용하는 버전은 `org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3`라는 메이븐(maven) 좌표(coordinate)를 통해 사용할 수 있다. >##### IDE 팁: >인텔리제이 IDEA를 메이븐이나 그레이들 같은 빌드 시스템을 채택하지 않고 사용하고 있다면 다음과 같은 단계를 거쳐 코루틴 라이브러리를 추가할 수 있다. 1. `Porject View` 패널의 루트 노드에서 `F4`를 누르거나 오른쪽 클릭을 해서 `Open Module Settings`를 선택하라. 2. 왼쪽의 `Libraries`를 클릭하고 맨 위에 있는 툴바에서 `+` 버튼을 클릭한 다음, `From Maven ...` 옵션을 선택하라. 3. 라이브러리의 메이븐 아티팩트 좌표를 입력하고(예: `org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3`) OK를 클릭하라(그림 13.1). 4. IDE는 여러분이 지정한 라이브러리와 관련된 의존관계 라이브러리를 함께 다운로드해서 프로젝트 모듈에 추가해준다. OK를 눌러서 변경된 내용을 적용하라. >##### 그림 13.1: 코틀린 코루틴 라이브러리 다운로드받기 이제부터는 코루틴 라이브러리에서 쓰이는 기본 개념을 설명하고 이런 개념을 동시성 프로그래밍에 어떻게 적용하는지 살펴본다. ## 코루틴과 일시중단 함수 전체 코루틴 라이브러리를 뒷받침하는 기본 요소는 일시중단 함수이다. 이 함수는 일반적인 함수를 더 일반화해서 함수 본문의 원하는 지점에서 함수에 필요한 모든 런타임 문맥을 저장하고 함수 실행을 중단한 다음, 나중에 필요할 때 다시 실행을 계속 진행할 수 있게 한 것이다. 코틀린에서는 이런 함수에 `suspend`라는 변경자를 붙인다. ``` suspend fun foo() { println("Task started") delay(100) println("Task finished") } ``` `delay()` 함수는 코루틴 라이브러리에 정의된 일시중단 함수다. 이 함수는 `Thread.sleep()`과 비슷한 일을 한다. 하지만 `delay()`는 현재 스레드를 블럭시키지 않고 자신을 호출한 함수를 일시중단시키고 스레드를 (다른 일시중단된 함수를 다시 계속 실행하는 등의) 다른 작업을 수행할 수 있게 풀어준다. 일시중단 함수는 일시중단 함수와 일반 함수를 원하는대로 호출할 수 있다. 일시중단 함수를 호출하면 해당 호출 지점이 일시중단 지점이 된다. 일시중단 지점은 임시로 실행을 중단했다가 나중에 재개할 수 있는 지점을 말한다. 반면 일반 함수 호출은 (지금까지 우리가 다뤄온) 일반 함수처럼 작동해서 함수 실행이 다 끝난 뒤 호출한 함수로 제어가 돌아온다. 반면에 코틀린은 일반 함수가 일시중단 함수를 호출하는 것을 금지한다. ``` fun foo() { println("Task started") delay(100) // Error: delay is a suspend function println("Task finished") } ``` >##### IDE 팁: >인텔리제이 코틀린 플러그인을 사용하면 일시중단을 호출하는 소스 코드 줄의 왼쪽에 특별한 아이콘이 표시되기 때문에 쉽게 일시중단 함수 호출을 구분할 수 있다(그림 13.1). >##### 그림 13.1: IDE에서 본 일시중단 호출 일시중단 함수를 일시중단 함수에서만 호출할 수 있다면, 어떻게 일반 함수에서 일시중단 함수를 호출할 수 있을까? 가장 뻔한 답은 `main()`을 `suspend`로 표시하는 것이다. ``` import kotlinx.coroutines.delay suspend fun main() { println("Task started") delay(100) println("Task finished") } ``` 이 코드를 실행하면 예상대로 다음 두 문장이 100밀리초 간격으로 표시되는 것을 볼 수 있다. ``` Task started Task finished ``` 더 실제적인 경우 동시성 코드의 동작을 제어하고 싶기 때문에, 공통적인 생명주기(life cycle)와 문맥이 정해진 몇몇 작업(task)이 정의된 구체적인 영역안에서만 동시성 함수를 호출한다. (이런 구체적 영역을 제공하기 위해) 코루틴을 실행할 때 사용하는 여러가지 함수를 코루틴 빌더(coroutine builder)라고 부른다. 코루틴 빌더는 `CoroutineScope` 인스턴스의 확장 함수로 쓰인다. `CoroutineScope`에 대한 구현 중 가장 기본적인 것으로 `GlobalScope` 객체가 있다. `GlobalScope` 객체를 사용하면 독립적인 코루틴을 만들 수 있고, 이 코루틴은 자신만의 작업을 내포할 수 있다. 이제 자주 사용하는 `launch()`, `async()`, `runBlocking()`이라는 코루틴 빌더를 살펴보자. ### 코루틴 빌더 `launch()` 함수는 코루틴을 시작하고, 코루틴을 실행중인 작업의 상태를 추적하고 변경할 수 있는 `Job` 객체를 돌려준다. 이 함수는 `CoroutineScope.() -> Unit` 타입의 일시중단 람다를 받는다. 이 람다는 새 코루틴의 본문에 해당한다. 간단한 예제를 보자. ``` import kotlinx.coroutines.* import java.lang.System.* fun main() { val time = currentTimeMillis() GlobalScope.launch { delay(100) println("Task 1 finished in ${currentTimeMillis() - time} ms") } GlobalScope.launch { delay(100) println("Task 2 finished in ${currentTimeMillis() - time} ms") } Thread.sleep(200) } ``` 이 코드를 실행하면 다음과 비슷한 동작을 볼 수 있다. ``` Task 2 finished in 176 ms Task 1 finished in 176 ms ``` 여기서 알아둘만한 내용으로는 두 작업이 프로그램을 시작한 시점을 기준으로 거의 동시에 끝났다는 점에서 알 수 있는 것처럼 두 작업이 실제로 병렬적으로 실행됐다는 점이다. 다만 실행 순서가 항상 일정하게 보장되지는 않기 때문에 상황에 따라 둘 중 어느 한쪽이 더 먼저 표시될 수 있다. 코루틴 라이브러리는 필요할 때 실행 순서를 강제할 수 있는 도구도 제공한다. 동시성 통신 관련한 절에서 이에 대해 설명한다. `main()` 함수 자체는 `Thread.sleep()`을 통해 메인 스레드 실행을 잠시 중단한다. 이를 통해 코루틴 스레드가 완료될 수 있도록 충분한 시간을 제공한다. 코루틴을 처리하는 스레드는 데몬 모드(daemon mode)로 실행되기 때문에 `main()` 스레드가 이 스레드보다 빨리 끝나버리면 자동으로 실행이 끝나버린다. 일시중단 함수의 내부에서 `sleep()`와 같은 스레드를 블럭시키는 함수를 실행할 수도 있지만 그런 식의 코드는 코루틴을 사용하는 목적에 위배된다는 점을 염두에 둬야 한다. 그래서 동시성 작업의 내부에서는 일시중단 함수인 `delay()`를 사용해야 한다. >##### IDE 팁: >인텔리제이 코틀린 플러그인은 `Thread.sleep()`이나 `Thread.join()` 같은 잠재적인 블러킹 함수를 호출하면 경고를 표시해준다. 코루틴은 스레드보다 훨씬 가볍다. 특히, 코루틴은 유지해야 하는 상태가 더 간단하고 일시중단 및 재개시 완전한 문맥 전환을 사용하지 않아도 되기 때문에 엄청난 수의 코루틴을 충분히 동시에 실행할 수 있다. `launch()` 빌더는 동시성 작업이 결과를 만들어내지 않는 경우 적합하다. 그래서 이 빌더는 `Unit` 타입을 반환하는 람다를 인자로 받는다. 하지만 결과가 필요한 경우에는 `async()`라는 다른 빌더 함수를 사용해야 한다. 이 함수는 `Deferred`의 인스턴스를 돌려준다. 이 인스턴스는 `Job`의 하위 타입으로 `await()` 메서드를 통해 계산 결과에 접근할 수 있게 해준다. `await()` 메서드를 호출하면 `await()`은 계산이 완료되거나(따라서 결과가 만들어지거나), 계산 작업이 취소될 때까지 현재 코루틴을 일시중단시킨다. 작업이 취소되는 경우 `await()`는 예외를 발생시키면서 실패한다. `async()`를 자바의 퓨처(future)에 해당하는 일시중단 빌더라고 생각할 수 있다. 예제를 살펴보자. ``` import kotlinx.coroutines.* suspend fun main() { val message = GlobalScope.async { delay(100) "abc" } val count = GlobalScope.async { delay(100) 1 + 2 } delay(200) val result = message.await().repeat(count.await()) println(result) } ``` 이 경우에는 `main()`을 `suspend`로 표시해서 두 `Deferred` 작업에 대해 직접 `await()` 메서드를 호출했다. 출력은 기대대로 다음과 같다. ``` abcabcabc ``` `launch()`와 `async()` 빌더의 경우 (일시중단 함수 내부에서) 스레드 호출을 블럭시키지는 않지만, 백그라운드 스레드를 공유하는 풀(pool)을 통해 작업을 실행한다. 앞에서 살펴본 `launch()` 예제에서는 메인 스레드가 처리할 일이 별로 없었기 때문에 `sleep()`을 통해 백그라운드 스레드에서 실행되는 작업이 완료될 때까지 기다려야 했다. 반대로 `runBlocking()` 빌더는 디폴트로 현재 스레드에서 실행되는 코루틴을 만들고 코루틴이 완료될 때까지 현재 스레드의 실행을 블럭시킨다. 코루틴이 성공적으로 끝나면 일시중단 람다의 결과가 `runBlocking()` 호출의 결괏값이 된다. 코루틴이 취소되면 `runBlocking()`은 예외를 던진다. 반면에 블럭된 스레드가 인터럽트되면 `runBlocking()`에 의해 시작된 코루틴도 취소된다. 예를 살펴보자. ``` import kotlinx.coroutines.* fun main() { GlobalScope.launch { delay(100) println("Background task: ${Thread.currentThread().name}") } runBlocking { println("Primary task: ${Thread.currentThread().name}") delay(200) } } ``` 이 프로그램을 실행하면 다음과 비슷한 결과를 볼 수 있다. ``` Primary task: main Background task: DefaultDispatcher-worker-2 ``` `runBlocking()` 내부의 코루틴은 메인 스레드에서 실행된 반면 `launch()`로 시작한 코루틴은 공유 풀에서 백그라운드 스레드를 할당받았음을 알 수 있다. 이런 블러킹 동작으로 인해 `runBlocking()`을 다른 코루틴 안에서 사용하면 안된다. `runBlocking()`은 블러킹 호출과 넌블러킹 호출 사이의 다리 역할을 하기 위해 고안된 코루틴 빌더이기 때문에, 테스트나 메인 함수에서 최상위 빌더로 사용하는 등의 경우에만 `runBlocking()`을 써야 한다. ### 코루틴 영역과 구조적 동시성 [저자의 자식-부모 관계 설명이 반대입니다.] 지금까지 살펴본 예제 코루틴은 전역 영역(global scope)에서 실행됐다. 전역 영역이란 코루틴의 생명주기가 전체 애플리케이션의 생명주기에 의해서만 제약되는 영역이다. 경우에 따라서는 코루틴이 어떤 연산을 수행하는 도중에만 실행되기를 바랄 수도 있다. 동시성 작업 사이의 부모 자식 관계로 인해 이런 실행 시간 제한이 가능하다. 어떤 코루틴을 다른 코루틴의 문맥에서 실행하면 후자가 전자의 부모가 된다. 이 경우 자식의 실행이 모두 끝나야 부모가 끝날 수 있도록 부모와 자식의 생명주기가 연관된다. 이런 기능을 구조적 동시성(structured concurrency)라고 부른다. 지역 변수 영역 안에서 블럭이나 서브루틴을 사용하는 경우와 구조적 동시성을 비교할 수 있다. 예제를 살펴보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { println("Parent task started") launch { println("Task A started") delay(200) println("Task A finished") } launch { println("Task B started") delay(200) println("Task B finished") } delay(100) println("Parent task finished") } println("Shutting down...") } ``` 이 코드는 최상위 코루틴을 시작하고 현재 `CoroutineScope` 인스턴스 안에서 `launch`를 호출(영역 객체는 일시중단 람다의 수신객체로 전달된다)해서 두가지 자식 코루틴을 시작한다. 이 프로그램을 실행하면 다음 결과를 볼 수 있다. ``` Parent task started Task A started Task B started Parent task finished Task A finished Task B finished Shutting down... ``` 지연을 100밀리초만 줬기 때문에 `runBlocking()` 호출의 일시중단 람다로 이뤄진 부모 코루틴의 주 본문이 더 빨리 끝난다는 점을 알 수 있다. 하지만 부모 코루틴 자체는 이 시점에 실행이 끝나지 않고 일시중단 상태로 두 자식이 모두 끝날 때까지 기다린다. `runBlocking()`이 메인 스레드를 블럭하고 있었기 때문에 부모 스레드가 끝나야 메인 스레드의 블럭이 풀리고 마지막 메시지가 출력된다. `coroutineScope()` 호출로 코드 블럭을 감싸면 커스텀 영역을 도입할 수도 있다. `runBlocking()`과 비슷하게 `coroutineScope()` 호출은 람다의 결과를 반환하고, 자식들이 완료되기 전까지 실행이 완료되지 않는다. `coroutineScope()`와 `runBlocking()`의 가장 큰 차이는 `coroutineScope()`쪽이 일시중단 함수라서 현재 스레드를 블럭시키지 않는다는 점에 있다. ``` import kotlinx.coroutines.* fun main() { runBlocking { println("Custom scope start") coroutineScope { launch { delay(100) println("Task 1 finished") } launch { delay(100) println("Task 2 finished") } } println("Custom scope end") } } ``` 여기서 앞의 `coroutineScope()` 호출이 자식 코루틴이 실행이 끝날 때까지 일시중단되기 때문에 `Custom scope end` 메시지가 마지막에 표시된다는 점을 확인하라. 일반적으로 부모 자식 관계는 예외 처리와 취소 요청을 공유하는 영역을 정의하는 더 복잡한 코루틴 계층 구조를 만들어낼 수 있다. 이 주제에 대해서는 코루틴 잡(job)과 취소에 대해 설명할 때 다시 다룬다. ## 코루틴 문맥 코루틴마다 `CoroutineContext` 인터페이스로 표현되는 문맥이 연관되어 있다. 코루틴을 감싸는 변수 영역의 `coroutineContext` 프로퍼티를 통해 이 문맥에 접근할 수 있다. 문맥은 키-값 쌍으로 이뤄진 불변 컬렉션이며, 코루틴에서 사용할 수 있는 여러가지 데이터가 들어있다. 이 데이터 중 일부는 코루틴 장치에 있어 특별한 의미를 가지며, 런타임에 코루틴이 실행되는 방식에 영향을 끼친다. 두가지 요소에 특히 관심을 가질만하다. - 코루틴이 실행중인 취소 가능한 작업을 표현하는 잡(job) - 코루틴과 스레드의 연관을 제어하는 디스패처(dispatcher) 일반적으로 문맥은 `CoroutineContext.Element`를 구현하는 아무 데이터나 저장할 수 있다. 특정 원소에 접근하려면 `get()` 메서드나 인덱스 연산자에 키를 넘겨야 한다. ``` GlobalScope.launch { // 현재 잡을 얻고 “Task is active: true”를 출력 println("Task is active: ${coroutineContext[Job.Key]!!.isActive}") } ``` 디폴트로 `launch()`, `async()` 등의 표준 코루틴 빌더에 의해 만들어지는 코루틴은 현재 문맥을 이어받는다. 필요하면 빌더 함수에 `context` 파라미터를 지정해서 새 문맥을 넘길 수도 있다. 새 문맥을 만들려면 두 문맥의 데이터를 합쳐주는 `plus()` 함수/`+` 연산자를 사용하거나, 주어진 키에 해당하는 원소를 문맥에서 제거해주는 `minusKey()` 함수를 사용하면 된다. ``` import kotlinx.coroutines.* private fun CoroutineScope.showName() { println("Current coroutine: ${coroutineContext[CoroutineName]?.name}") } fun main() { runBlocking { showName() // Current coroutine: null launch(coroutineContext + CoroutineName("Worker")) { showName() // Current coroutine: Worker } } } ``` 코루틴을 실행하는 중간에 `withContext()`에 새 문맥과 일시중단 람다를 넘겨서 문맥을 전환시킬 수도 있다. 예를 들어 어떤 코드 블럭을 다른 스레드에서 실행하고 싶을 때 이런 기능이 유용하다. 코루틴 디스패처에 대해 다룰 때 이런 스레드 건너뛰기 기능의 예제를 살펴본다. ## 코루틴 흐름 제어와 잡 생명주기 잡은 동시성 작업의 생명주기를 표현하는 객체다. 잡을 사용하면 작업 상태를 추적하고 필요할 때 작업을 취소할 수 있다. 그림 13.3을 보면 잡이 취할 수 있는 상태에 대해 알 수 있다. 그림에서 각 상태의 의미와 잡의 상태가 한 상태에서 다른 상태로 어떻게 전이되는지에 대해 자세히 살펴보자. >##### 그림 13.3: 잡 상태 [그림번역] 신규(New) start - 시작 활성화(Active) complete - 완료 finish - 끝 완료중(Completing) 완료됨(Completed) cancel/fail - 취소/실패 취소중(Cancelling) 취소됨(Cancelled) [번역끝] 활성화 상태는 작업이 시작됐고 아직 완료나 취소로 끝나지 않았다는 뜻이다. 이 상태는 보통 디폴트 상태다. 다른 말로, 잡은 생성되자 마자 활성화 상태가 된다. `launch()`나 `async()`는 `CoroutineStart` 타입의 인자를 지정해서 잡의 초기 상태를 선택하는 기능을 제공하기도 한다. - `CoroutineStart.DEFAULT`는 디폴트 동작이며, 잡을 즉시 시작한다. - `CoroutineStart.LAZY`는 잡을 자동으로 시작하지 말라는 뜻이다. 이 경우에는 잡이 신규 상태가 되고 시작을 기다리게 된다. 신규 상태의 잡에 대해 `start()`나 `join()` 메서드를 호출하면 잡이 시작되면서 활성화 상태가 된다. 예제를 보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { val job = launch(start = CoroutineStart.LAZY) { println("Job started") } delay(100) println("Preparing to start...") job.start() } } ``` 이 예제는 자식 코루틴의 시작을 부모 코루틴이 메시지를 호출한 뒤로 미룬다. 출력은 다음과 같다. ``` Preparing to start... Job started ``` 활성화 상태에서는 코루틴 장치가 잡을 반복적으로 일시중단 및 재개시킨다. 잡이 다른 잡을 시작할 수도 있는데, 이 경우 새 잡은 기존 잡의 자식이 된다. 따라서 잡의 부모 자식관계는 동시성 계산 사이에 트리 형태의 의존 구조를 만든다. `children` 프로퍼티를 통해 완료되지 않은 자식 잡들을 얻을 수 있다. 다음 코드를 보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { val job = coroutineContext[Job.Key]!! launch { println("This is task A") } launch { println("This is task B") } // 2 children running println("${job.children.count()} children running") } } ``` 코루틴이 일시중단 람다 블럭의 실행을 끝내면 잡의 상태는 완료중 상태로 바뀐다. 이 상태는 기본적으로 자식들의 완료를 기다리는 상태다. 잡은 모든 자식이 완료될 때까지 이 상태를 유지하고, 모든 자식이 완료되면 잡의 상태가 완료중에서 완료됨으로 바뀐다. 잡의 `join()` 메서드를 사용하면 조인 대상 잡이 완료될 때까지 현재 코루틴을 일시중단시킬 수 있다. 다음 프로그램은 루트 코루틴의 메시지가 두 자식 메시지의 실행이 끝난 후에 출력되도록 보장해준다. ``` import kotlinx.coroutines.* fun main() { runBlocking { val job = coroutineContext[Job.Key]!! val jobA = launch { println("This is task A") } val jobB = launch { println("This is task B") } jobA.join() jobB.join() println("${job.children.count()} children running") } } ``` 결과는 다음과 같다. ``` This is task A This is task B 0 children running ``` 예상대로 `job.children.count()`를 평가하는 시점에는 활성화된 자식이 없다. 현재 잡 상태를 잡의 `isActive`, `isCancelled`, `isComplete` 프로퍼티로부터 추적할 수 있다. 이들의 의미를 다음 표에 정리했다. `Job` 인터페이스 문서에서 이에 대한 정보를 볼 수 있다. | 잡 상태 | `isActive` | `isCompleted` | `isCancelled` | |--------|--------|--------|--------| | 신규 | `flase` | `flase` | `flase` | | 활성화 | `true` | `flase` | `flase` | | 완료중 | `true` | `flase` | `flase` | | 취소중 | `flase` | `flase` | `true` | | 취소됨 | `flase` | `true` | `true` | | 완료됨 | `flase` | `true` | `flase` | [completeing과 active를 구분할 수 없다고 해야 합니다.] 완료됨이거나 취소됨인 상태의 잡의 `isCompleted`가 `true`라는 점에 유의하라. `isCancelled` 프로퍼티를 검사하면 이들을 구분할 수 있다. 반면 잡 외부에서 활성화된 작업과 완료중인 작업을 구분할 수는 없다. ## 취소 잡의 `cancel()` 메서드를 호출하면 잡을 취소할 수 있다. 이 메서드는 더이상 필요가 없는 계산을 중단시킬 수 있는 표준적인 방법을 제공한다. 취소는 협력적이다. 즉, 취소 가능한 코루틴이 스스로 취소가 요청됐는지 검사해서 적절히 반응을 해줘야 한다. 다음 프로그램을 살펴보자. ``` import kotlinx.coroutines.* suspend fun main() { val squarePrinter = GlobalScope.launch(Dispatchers.Default) { var i = 1 while (true) { println(i++) } } delay(100) // 자식 잡이 어느정도 실행될 시간을 준다 squarePrinter.cancel() } ``` 이 코드는 정수를 계속 출력하는 코루틴을 시작한다. 이 코루틴이 100밀리초 실행된 다음에 중단되게 했다. 하지만 이 프로그램을 실행하면 `squarePrinter`가 계속 실행되는 모습을 볼 수 있다. 이유는 이 코루틴이 취소를 위해 협력하지 않기 때문이다. 이런 문제를 해결하는 방법으로, 다음 작업을 수행하기 전에 코루틴이 취소됐는지 검사하는 방법이 있다. ``` import kotlinx.coroutines.* suspend fun main() { val squarePrinter = GlobalScope.launch(Dispatchers.Default) { var i = 1 while (isActive) { println(i++) } } delay(100) // 자식 잡이 어느정도 실행될 시간을 준다 squarePrinter.cancel() } ``` `isActive` 확장 프로퍼티는 현재 잡이 활성화된 상태인지 검사한다. `CoroutineScope`(일시중단 람다의 수신 객체가 이 타입임)의 이 프로퍼티를 살펴보면 단순히 현재 잡의 `isActive`에게 위임하고 있음을 알 수 있다. 이제 부모 코루틴이 `cancel()` 메서드를 호출하면 `squarePrinter`의 상태가 취소중으로 바뀌고, 그 다음 `isActive` 검사를 통해 루프를 종료시킬 수 있다. 코루틴이 실행을 끝내면 상태가 취소됨으로 바뀐다. 이 코드를 실행해보면 대략 100밀리초 이후 코루틴이 중단되는 모습을 볼 수 있다. 다른 해법은 상태를 검사하는 대신에, `CancellatinoExcption`을 발생시키면서 취소에 반응할 수 있게 일시중단 함수를 호출하는 것이다. 이 예외는 잡을 취소하는 과정이 진행중이라는 사실을 전달하는 토큰 역할을 하기 위해 코루틴 라이브러리 내부에서 쓰이는 예외다. 코루틴 라이브러리에 정의된 `delay()`나 `join()` 등의 모든 일시중단 함수가 이 예외를 발생시켜준다. 한가지 예를 추가하자면, `yield()`를 들 수 있다. 이 함수는 실행중인 잡을 일시중단시켜서 자신을 실행중인 스레드를 다른 코루틴에게 양보한다(마치 `Thread.yield()`를 호출하면 현재 스레드를 일시중단시키고 다른 스레드가 실행될 수 있는 기회를 부여하는 것과 비슷하다). ``` import kotlinx.coroutines.* suspend fun main() { val squarePrinter = GlobalScope.launch(Dispatchers.Default) { var i = 1 while (true) { yield() println(i++) } } delay(100) // 자식 잡이 어느정도 실행될 시간을 준다 squarePrinter.cancel() } ``` 부모 코루틴이 취소되면 자동으로 모든 자식의 실행을 취소한다. 이 과정은 부모에게 속한 모든 잡 계층이 취소될 때까지 계속된다. 다음 예제를 살펴보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { val parentJob = launch { println("Parent started") launch { println("Child 1 started") delay(500) println("Child 1 completed") } launch { println("Child 2 started") delay(500) println("Child 2 completed") } delay(500) println("Parent completed") } delay(100) parentJob.cancel() } } ``` 이 프로그램은 한쌍의 자식을 시작하는 코투틴을 시작한다. 이렇게 만들어진 세가지 작업은 모두 완료 메시지를 표시하기 전에 500밀리초를 기다린다. 하지만 부모 잡이 100밀리초만에 취소된다. 그 결과, 세 잡 중 어느 하나도 완료 상태로 도달하지 못하며, 프로그램 출력은 다음과 같아진다. ``` Parent started Child 1 started Child 2 started ``` ## 타임아웃 경우에 따라 작업이 완료되기를 무작정 기다릴 수 없어서 타임아웃을 설정해야 할 때가 있다. 코루틴 라이브러리는 정확히 이럴 때 사용할 수 있는 `withTimeout()`이라는 함수를 제공한다. 다음 예제는 파일을 읽는 도중에 타임아웃이 걸린 코루틴을 시작한다. ``` import kotlinx.coroutines.* import java.io.File fun main() { runBlocking { val asyncData = async { File("data.txt").readText() } try { val text = withTimeout(50) { asyncData.await() } println("Data loaded: $text") } catch (e: Exception) { println("Timeout exceeded") } } } ``` 파일을 50밀리초 안에 읽을 수 있다면 `withTimeout()`은 결과를 돌려주기만 한다. 하지만 50밀리초 안에 파일을 읽을 수 없으면 `TimeoutCancellationException`을 던지기 때문에 파일을 읽는 코루틴이 취소된다. 비슷한 함수로 `withTimeoutOrNull()`이라는 것도 있다. 이 함수는 타임아웃이 발생하면 예외를 던지는 대신 널 값을 돌려준다. ## 코루틴 디스패치하기 코루틴은 스레드와 무관하게 일시중단 가능한 계산을 구현할 수 있게 해주지만, 코루틴을 실행하려면 여전히 스레드와 연관을 시켜야 한다. 코루틴 라이브러리에는 특정 코루틴을 실행할 때 사용할 스레드를 제어하는 작업을 담당하는 특별한 콤포넌트가 있다. 이 콤포넌트를 코루틴 디스패처(dispatcher)라고 부른다. 디스패처는 코루틴 문맥의 일부다. 따라서 `launch()`나 `runBlocking()` 등의 코루틴 빌더 함수에서 이를 지정할 수 있다. 디스패처는 그 자체로 원소가 하나뿐인 문맥이기도 하다. 코루틴 빌더에게 디스패처를 넘길 수 있다. ``` import kotlinx.coroutines.* fun main() { runBlocking { // 전역 스레드 풀 디스패처를 사용해 코루틴을 실행한다 launch(Dispatchers.Default) { println(Thread.currentThread().name) // DefaultDispatcher-worker-1 } } } ``` 코루틴 디스패처는 병렬 작업 사이에 스레드를 배분해주는 자바 실행기(executor)와 비슷하다. 실제로 `asCoroutineDispatcher()` 확장 함수를 사용하면 기존 실행기 구현을 그에 상응하는 코루틴 디스패처로 쉽게 바꿀 수 있다. 다음 예제는 실행하는 스레드에 `WorkerThread1`, `WorkerThread2` 등의 이름을 부여하는 커스텀 스레드 팩터리를 사용하는 풀 기반의 실행기 서비스를 정의한다. 명시적으로 작업자 스레드를 데몬 스레드로 지정해서 코루틴 실행이 끝난 후에 프로그램이 종료되지 못하는 일이 없게 했다는 점에 유의하라. ``` import kotlinx.coroutines.* import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.atomic.AtomicInteger fun main() { val id = AtomicInteger(0) val executor = ScheduledThreadPoolExecutor(5) { runnable -> Thread( runnable, "WorkerThread-${id.incrementAndGet()}" ).also { it.isDaemon = true } } executor.asCoroutineDispatcher().use { dispatcher -> runBlocking { for (i in 1..3) { launch(dispatcher) { println(Thread.currentThread().name) delay(1000) } } } } } ``` `delay()`는 실행기가 별도의 스레드를 만들게 한다. 따라서 이 코드는 다음과 같은 결과를 출력한다. ``` WorkerThread-1 WorkerThread-2 WorkerThread-3 ``` 하지만 구체적인 스레드 순서는 다를 수 있다. `ExecutorService`의 인스턴스에 대해 `asCoroutineDispatcher()` 호출하면 `ExecutorCoroutineDispatcher`를 반환하는데, 이 디스패처는 `Closeable` 인스턴스도 구현한다는 점을 기억하라. 이 디스패처의 바탕이 되는 실행기 서비스를 종료하고 스레드를 유지하기 위해 할당했던 시스템 자원을 해제하려면 `close()` 함수를 직접 호출하거나, 방금 본 코드처럼 `use()` 함수 블럭 안에서 디스패처를 사용해야 한다. 코루틴 라이브러리에는 기본적으로 몇 가지 디스패처 구현을 제공한다. 그 중 일부를 `Dispatchers` 객체를 통해 사용할 수 있다. - `Dispatchers.Default` : 공유 스레드 풀로 풀 크기는 디폴트로 사용 가능 CPU 코어 수이거나 2(둘 중 큰 값)이다. 이 구현은 일반적으로 작업 성능이 주로 CPU 속도에 의해 결정되는 CPU 위주의 작업에 적합하다. - `Dispatchers.IO` : 스레드 풀 기반이며 디폴트 구현과 비슷하지만 파일을 읽고 쓰는 것처럼 잠재적으로 블러킹될 수 있는 I/O를 많이 사용하는 작업에 최적화되어 있다. 이 디스패처는 스레드 풀을 디폴트 구현과 함께 공유하지만, 필요에 따라 스레드를 추가하거나 종료시켜준다. - `Dispatchers.Main` : 사용자 입력이 처리되는 UI 스레드에서만 배타적으로 작동하는 디스패처이다. `newFixedThreadPoolContext()`나 `newSingleThreadPoolContext()`를 사용하면 직접 만든 스레드 풀을 사용하거나 심지어는 스레드를 하나만 사용하는 디스패처도 만들 수 있다. 예를 들어, `Executor`를 기반으로 예제를 다시 작성할 수 있다. ``` import kotlinx.coroutines.* @Suppress("EXPERIMENTAL_API_USAGE") fun main() { newFixedThreadPoolContext(5, "WorkerThread").use { dispatcher -> runBlocking { for (i in 1..3) { launch(dispatcher) { println(Thread.currentThread().name) delay(1000) } } } } } ``` `newFixedThreadPoolContext()`나 `newSingleThreadPoolContext()`가 실험적인 기능으로 표시되어 있고, 향후 공유 스레드 풀을 기반으로 하는 더 새로운 함수로 대치될 예정이기 때문에, 경고를 피하기 위해 `@Suppress` 애너테이션을 사용했다. (이번 장 앞의 예제에서 했던 것처럼) 디스패처를 명시적으로 지정하지 않으면 여러분이 코루틴을 시작한 영역으로부터 디스패처가 자동으로 상속된다. 다음 예제를 생각해 보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { println("Root: ${Thread.currentThread().name}") launch { println("Nested, inherited: ${Thread.currentThread().name}") } launch(Dispatchers.Default) { println("Nested, explicit: ${Thread.currentThread().name}") } } } ``` 이 코드는 메인 스레드에서 실행되는 최상위 코루틴을 시작한다. 이 코루틴은 내부에 두가지 코루틴을 포함한다. 첫번째 코루틴은 문맥(그리고 그에 따라 코루틴 디스패처도)을 부모 코루틴으로부터 물려받고, 두번째 코루틴은 명시적으로 문맥을 전달받는다. 따라서 이 코드는 다음과 같은 출력을 내놓는다. ``` Root: main Nested, explicit: DefaultDispatcher-worker-1 Nested, inherited: main ``` 부모 코루틴이 없으면 암시적으로 `Dispatchers.Default`로 디스패처를 가정한다. 다만 `runBlocking()` 빌더는 현재 스레드를 사용한다. 코루틴이 생명주기 내내 같은 디스패처를 사용할 필요도 없다. 디스패처가 코루틴 문맥의 일부이기 때문에, `withContext()` 함수를 사용해 디스패처를 오버라이드할 수 있다. ``` import kotlinx.coroutines.* @Suppress("EXPERIMENTAL_API_USAGE") fun main() { newSingleThreadContext("Worker").use { worker -> runBlocking { println(Thread.currentThread().name) // main withContext(worker) { println(Thread.currentThread().name) // Worker } println(Thread.currentThread().name) // main } } } ``` 이 기법은 중단가능 루틴의 일부를 한 스레드에서만 실행하고 싶을 때 유용하다. ## 예외 처리 예외 처리의 경우, 코루틴 빌더들은 두가지 기본 전략 중 한가지를 따른다. 첫번째 전략은 `launch()` 같은 빌더가 선택한 전략으로, 예외를 부모 코루틴에게 전달하는 전략이다. 이럴 경우, 예외는 다음과 같이 전파된다. - 부모 코루틴이 (자식에게서 발생한 오류와) 똑같은 오류로 인해 취소된다. 이로 인해 부모의 나머지 자식도 모두 취소된다. - 자식들이 모두 취소되고 나면 부모는 예외를 코루틴 트리의 윗부분으로 전달한다. 전역 영역에 있는 코루틴에 도달할 때까지 이 과정이 반복된다. 그 후 예외가 `CoroutineExceptionHandler.Consider`에 의해 처리된다. 예를 들어 다음 코드를 보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { launch { throw Exception("Error in task A") println("Task A completed") } launch { delay(1000) println("Task B completed") } println("Root") } } ``` 최상위 코루틴은 한쌍의 내부 작업을 시작한다. 그 중 첫번째 코루틴은 예외를 던진다. 이로 인해 최상위 작업이 취소되고, 최상위의 자식인 두 작업도 취소된다. 그리고 최상위에서 아무 커스텀 핸들러도 지정하지 않았기 때문에 프로그램은 `Thread.uncaughtExceptionHandler`에 등록된 디폴트 동작을 실행한다. 그에 따라 다음과 같은 메시지가 표시되고 그 뒤에 예외에 대한 스텍 트레이스(trace)가 출력된다. ``` Root Exception in thread "main" java.lang.Exception: Error in task A ``` `CoroutineExceptionHandler`는 현재 코루틴 문맥과 던져진 예외를 인자로 전달받는다. ``` fun handleException(context: CoroutineContext, exception: Throwable) ``` 핸들러를 만드는 가장 간단한 방법은 인자가 2개인 람다를 받는 `CoroutineExceptionHandler()` 함수를 쓰는 것이다. ``` val handler = CoroutineExceptionHandler{ _, exception -> println("Caught $exception") } ``` 이 핸들러의 인스턴스가 예외를 처리하도록 지정하려면 코루틴 문맥에 인스턴스를 넣어야 한다. 핸들러 자체는 뻔한 문맥이기 때문에, 그냥 코루틴 빌더의 `context` 인자로 핸들러를 넘길 수 있다. ``` import kotlinx.coroutines.* suspend fun main() { val handler = CoroutineExceptionHandler{ _, exception -> println("Caught $exception") } GlobalScope.launch(handler) { launch { throw Exception("Error in task A") println("Task A completed") } launch { delay(1000) println("Task B completed") } println("Root") }.join() } ``` 이제 이 프로그램이 다음 메시지를 출력한다. 이 말은 프로그램이 예외에 대한 디폴트 동작을 오버라이드했다는 뜻이다. ``` Root Caught java.lang.Exception: Error in task A ``` 문맥에 핸들러 인스턴스 정의가 없는 경우, 코루틴 라이브러리는 JVM `ServiceLoader` 장치를 통해 설정된 모든 전역 핸들러를 호출하고 현재 스레드에 대해서는 `uncaughtExceptionHandler`를 발생시킨다. `CoroutineExceptionHandler`는 전역 영역에서 실행된 코루틴에 대해서만 정의할 수 있고, `CoroutineExceptionHandler`이 정의된 코루틴의 자식에 대해서만 적용된다는 점에 유의하라. 그래서 `runBlocking()` 코드를 `GlobalScope.launch()`로 변경하고 `main()` 함수를 `suspend`로 표시하고 `join()` 호출을 사용해야 한다. 원래 예제에서 `runBlocking()`을 그대로 사용하는 대신 핸들러만 추가한다고 해도, 코루틴이 전역 영역에서 실행되지 않기 때문에 프로그램은 여전히 디폴트 핸들러를 사용하게 된다. ``` import kotlinx.coroutines.* fun main() { val handler = ... runBlocking(handler) { ... } } ``` 예외를 처리하는 다른 방법으로 `async()` 빌더에서 사용하고 있는 방법은 던져진 예외를 저장했다가 예외가 발생한 계산에 대한 `await()` 호출을 받았을 때 다시 던지는 것이다. 앞의 예제를 조금 바꿔보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { val deferredA = async { throw Exception("Error in task A") println("Task A completed") } val deferredB = async { println("Task B completed") } deferredA.await() deferredB.await() println("Root") } } ``` 이제 출력은 다음과 같아진다. ``` Exception in thread "main" java.lang.Exception: Error in task A ``` `deferredA.await()`에서 예외가 다시 던져지기 때문에 프로그램이 `println("Root")` 문장을 실행하지 못한다. [runBlocking은 async 와 유사한 방식이 아닙니다. 그냥 디폴트 핸들러가 호출되기 때문에 예로 `runBlocking`을 든건데 오히려 혼동의 여지만 더하는 것 같습니다. 해당 내용을 변경했습니다.] 코루틴 데이터에 접근할 때 예외를 다시 던지는 방식을 채용하는 `async`와 유사한 빌더들의 경우 `CoroutineExceptionHandler`를 사용하지 않는다. 따라서 코루틴 문맥에 `CoroutineExceptionHandler` 인스턴스를 설정했다고 해도 아무 효과가 없다. 그냥 전역 디폴트 핸들러가 호출된다. 내포된 코루틴에서 발생한 예외를 전역 핸들러를 통하지 않고 부모 수준에서 처리하고 싶으면 어떻게 해야 할까? `try-catch` 블럭으로 예외를 처리하려고 시도하면 어떤 일이 벌어지는지 살펴보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { val deferredA = async { throw Exception("Error in task A") println("Task A completed") } val deferredB = async { println("Task B completed") } try { deferredA.await() deferredB.await() } catch (e: Exception) { println("Caught $e") } println("Root") } } ``` 이 코드를 실행하면 핸들러가 실제 호출되는 모습을 볼 수 있다. 하지만 프로그램은 여전히 예외와 함께 중단된다. ``` Caught java.lang.Exception: Error in task A Root Exception in thread "main" java.lang.Exception: Error in task A ``` 이유는 자식(여기서는 `deeferredA`)이 실패한 경우에는 부모를 취소시키기 위해 자동으로 예외를 다시 던지기 때문이다. 이런 동작을 변경하려면 수퍼바이저(supervisor) 잡을 사용해야 한다. 수버파이저 잡이 있으면 취소가 아랫 방향으로만 전달된다. 여러분이 수퍼바이저를 취소하면 수퍼바이저 잡은 자동으로 자신의 모든 자식을 취소한다. 하지만 수퍼바이저가 아니라 자식이 취소된 경우, 수퍼바이저나 수퍼바이저의 다른 자식들은 아무 영향을 받지 않는다. 부모 코루틴을 수퍼바이저로 변환하려면 `coroutineScope()` 대신 `supervisorScope()` 함수를 사용해 새로운 영역을 정의한다. 앞의 예제를 변경해보자. ``` import kotlinx.coroutines.* fun main() { runBlocking { supervisorScope { val deferredA = async { throw Exception("Error in task A") println("Task A completed") } val deferredB = async { println("Task B completed") } try { deferredA.await() } catch (e: Exception) { println("Caught $e") } deferredB.await() println("Root") } } } ``` 이제 예외가 발생하더라도 B 작업과 루트 코루틴이 완료된다. ``` Task B completed Caught java.lang.Exception: Error in task A Root ``` 수퍼바이저의 동작은 일반적인 취소에도 적용된다는 점에 유의하라. 수퍼바이저의 자식 중 하나에 `cancel()`을 호출해도 해당 코루틴의 형제자매나 수퍼바이저 자신에는 아무 영향이 없다. ## 동시성 통신 이번 절에서는 스레드 안전성을 유지하면서 여러 동시성 작업 사이에 데이터를 효율적으로 공유할 수 있게 해주는 코루틴 라이브러리 고급 기능에 대해 이야기한다. 정확히 말해 여기서는 코루틴과 액터 사이에서 동기화나 락을 사용하지 않고도 변경 가능한 상태를 안전하게 공유할 수 있는 데이터 스트림을 제공하는 메커니즘인 채널(channel)에 대해 다룬다. ### 채널 채널은 임의의 데이터 스트림을 코루틴 사이에 공유할 수 있는 편리한 방법이다. `Channel` 인터페이스가 제공하는 채널에 대한 기본 연산은 데이터를 보내는 `send()` 메서드와 데이터를 받는 `receive()` 메서드이다. 이런 메서드는 자신의 작업을 완료할 수 없다. 예를 들어 채널 내부 버퍼가 꽉찼는데 데이터를 채널에 보내려고 하면, 채널은 현재 코루틴을 일시중단시키고 처리가 가능해지면 나중에 재개한다. 이 부분이 자바의 동시성 API에서 채널과 비슷한 역할을 하는 블러킹 큐(queue)와 채널의 가장 큰 차이다. 블러킹 큐는 스레드를 블럭시킨다. 제네릭 `Channel()` 함수를 사용해 채널을 만들 수 있다. 이 함수는 채널의 용량을 지정하는 정수 값을 받는다. 채널 기본 구현은 크기가 정해진 내부 버퍼를 사용한다. 버퍼가 꽉차면 최소 하나 이상의 채널 원소가 상대방에 의해 수신될 때까지 `send()` 호출이 일시중단된다. 비슷하게 버퍼가 비어있으면 누군가 최소 하나 이상의 원소를 채널로 송신할 때까지 `receive()` 호출이 일시중단된다. 예제를 살펴보자. ``` import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.* import kotlin.random.Random fun main() { runBlocking { val streamSize = 5 val channel = Channel<Int>(3) launch { for (n in 1..streamSize) { delay(Random.nextLong(100)) val square = n*n println("Sending: $square") channel.send(square) } } launch { for (i in 1..streamSize) { delay(Random.nextLong(100)) val n = channel.receive() println("Receiving: $n") } } } } ``` 첫번째 코루틴은 정수 제곱 값의 스트림을 만들어내고, 원소를 3개 저장할 수 있는 채널에 이 스트림을 전송한다. 이와 동시에, 두번째 코루틴이 생성된 수를 수신한다. 두 코루틴 중 어느 한쪽이 뒤쳐저서 채널 버퍼가 꽉차거나 비는 경우가 생겨서 일시 중단이 벌어질 수 있게 일부러 지연 시간을 난수로 지정했다. 다양한 출력이 생길 수 있는데, 그 중 하나는 다음과 같다. ``` Sending: 1 Receiving: 1 Sending: 4 Receiving: 4 Sending: 9 Sending: 16 Receiving: 9 Sending: 25 Receiving: 16 Receiving: 25 ``` 출력이 실제 지연시간 값이나 다른 환경에 의해 달라질 수 있음에도 불구하고, 채널은 모든 값이 송신된 순서 그대로 수신되도록 보장한다. `Channel()` 함수는 채널의 동작을 바꿀 수 있는 여러 특별한 값을 받을 수 있다. 이런 값은 `Channel` 인터페이스의 동반 객체에 상수로 정의되어 있다. - `Channel.UNLIMITED` (= `Int.MAX_VALUE`) : 이 경우 채널의 용량이 제한이 없고, 내부 버퍼는 필요에 따라 증가한다. 이런 채널은 `send()`시에는 결코 일시중단되는 일이 없다. 다만 `receive()`를 하는 경우 버퍼가 비어있으면 일시중단될 수 있다. - `Channel.RENDEZVOUS` (= `0`) : 이 경우 채널은 아무 내부 버퍼가 없는 랑데뷰 채널이 된다. `send()` 호출은 다른 어떤 코루틴이 `receive()`를 호출할 때까지 항상 일시중단 된다. 마찬가지로 `receive()` 호출은 다른 어떤 코루틴이 `send()`를 호출할 때까지 일시중단된다. 채널 생성시 `capacity`를 지정하지 않으면 이 방식의 채널이 생성된다. - `Channel.CONFLATED` (= `-1`) : 이 경우에는 송신된 값이 합쳐지는 채널(conflated channel)이다. 이 말은 `send()`로 보낸 원소를 최대 하나만 버퍼에 저장하고 이 값이 누군가에 의해 수신되기 전에 다른 `send()`요청이 오면 기존에 값을 덮어쓴다는 말이다. 따라서 수신되지 못한 원소 값은 소실된다. 이 채널의 경우 `send()` 메서드는 결코 일시중단되지 않는다. - `Channel.UNLIMITED`보다 작은 임의의 양수를 지정하면 버퍼 크기가 일정하게 제한된 채널이 생긴다. 랑데뷰 채널은 생산자와 소비자 코루틴이 교대로 활성화되도록 보장한다. 예를 들어 앞의 예제의 채널 크기를 0으로 바꾸면, 딜레이 시간과 관계 없이 안정적인 동작 순서를 볼 수 있다. ``` Sending: 1 Receiving: 1 Sending: 4 Receiving: 4 Sending: 9 Receiving: 9 Sending: 16 Receiving: 16 Sending: 25 Receiving: 25 ``` 값이 합쳐지는 채널은 스트림에 기록한 모든 원소가 도착할 필요가 없고 소비자 코루틴이 뒤쳐지는 경우 생산자가 만들어낸 값 중 일부를 버려도 되는 경우 쓰인다. 첫번째 예제의 소비자 지연 시간을 생산자 지연 시간의 2배로 설정해보자. ``` import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.* fun main() { runBlocking { val streamSize = 5 val channel = Channel<Int>(Channel.CONFLATED) launch { for (n in 1..streamSize) { delay(100) val square = n*n println("Sending: $square") channel.send(square) } } launch { for (i in 1..streamSize) { delay(200) val n = channel.receive() println("Receiving: $n") } } } } ``` 실행해본 결과, 생산된 값 중 대략 절반만 수신되어 처리됨을 볼 수 있다. 다음과 같은 출력이 나올 수 있다. ``` Sending: 1 Receiving: 1 Sending: 4 Sending: 9 Receiving: 9 Sending: 16 Sending: 25 Receiving: 25 ``` 이 프로그램을 실행할 때는 마지막 줄을 출력한 다음에 프로그램이 끝나지 않는다는 사실을 알 수 있다. 이유는 수신자 코루틴이 `1`부터 `streamSize`까지 이터레이션을 하므로 수신하리라 기대하는 원소 개수가 5개이기 때문이다. 하지만 실제 수신되는 원소는 `streamSize/2` 근처이기 때문에 이 기대는 결코 충족될 수가 없다. 이런 상황에서 필요한 것은 채널이 닫혀서 더 이상 데이터를 보내지 않는다는 사실을 알려주는 어떤 신호이다. `Channel` API는 생산자 쪽에서 `close()` 메서드를 사용해 이런 신호를 보낼 수 있게 해준다. 소비자 쪽에서는 반복 회수를 고정하는 대신 채널에서 들어오는 데이터에 대해 이터레이션을 할 수 있다. ``` import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.* fun main() { runBlocking { val streamSize = 5 val channel = Channel<Int>(Channel.CONFLATED) launch { for (n in 1..streamSize) { delay(100) val square = n*n println("Sending: $square") channel.send(square) } channel.close() } launch { for (n in channel) { println("Receiving: $n") delay(200) } } } } ``` 이제 데이터 교환이 완료된 후 프로그램이 제대로 끝난다. 소비자 쪽에서는 명시적인 이터레이션을 사용하지 않고 `consumeEach()` 함수를 통해 모든 채널 컨텐트를 얻어서 사용할 수 있다. ``` channel.consumeEach { println("Receiving: $n") delay(200) } ``` 채널이 닫힌 후 `send()`를 호출하면 `ClosedSendChannelException` 예외가 발생하며 실패한다. 채널이 닫힌 후 `receive()`를 호출하면 버퍼에 있는 원소가 소진될 때까지 정상적으로 원소가 반환되지만, 그 다음에는 마찬가지로 `ClosedSendChannelException` 예외가 발생한다. 채널 통신에 참여하는 생산자와 소비자가 꼭 하나씩일 필요는 없다. 예를 들어 한 채널을 여러 코루틴이 동시에 읽을 수도 있다. 이런 경우를 팬 아웃(fan out)이라고 한다. ``` import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.* import kotlin.random.Random fun main() { runBlocking { val streamSize = 5 val channel = Channel<Int>(2) launch { for (n in 1..streamSize) { val square = n*n println("Sending: $square") channel.send(square) } channel.close() } for (i in 1..3) { launch { for (n in channel) { println("Receiving by consumer #$i: $n") delay(Random.nextLong(100)) } } } } } ``` 생산자 코루틴이 생성한 데이터 스트림을 세 소비자 코루틴이 나눠 받는다. 가능한 출력을 하나 표시하면 다음과 같다. ``` Sending: 1 Sending: 4 Sending: 9 Receiving by consumer #1: 1 Receiving by consumer #2: 4 Receiving by consumer #3: 9 Sending: 16 Sending: 25 Receiving by consumer #3: 16 Receiving by consumer #1: 25 ``` 비슷하게 여러 생산자 코루틴이 한 채널에 써 넣은 데이터를 한 소비자 코루틴이 읽는 팬 인(fan in)도 있다. 더 일반적인 경우로는 여러 생산자와 여러 소비자가 여러 채널을 공유할수도 있다. 일반적으로 채널의 동작은 공정(fair)하다. 이 말은 어떤 채널에 대해 `receive()`를 맨 처음 호출한 코루틴이 다음 원소를 읽게 된다는 뜻이다. ### 생산자 앞에서 컬렉션 API에 대해 설명할 때 보여준 `sequence()` 함수와 비슷하게 동시성 데이터 스크림을 생성할 수 있는 `producer()`라는 특별한 코루틴 빌더가 있다. 이 빌더는 채널과 비슷한 `send()` 메서드를 제공하는 `ProducerScope` 영역을 도입해준다. ``` import kotlinx.coroutines.channels.* import kotlinx.coroutines.* fun main() { runBlocking { val channel = produce { for (n in 1..5) { val square = n*n println("Sending: $square") send(square) } } launch { channel.consumeEach { println("Receiving: $it") } } } } ``` 이 경우 채널을 명시적으로 닫을 필요가 없다. 코루틴이 종료되면 `producer()` 빌더가 채널을 자동으로 닫아준다. 예외 처리 관점에서 볼 때, `producer()`는 `async()/await()`의 정책을 따른다. `producer()` 안에서 예외가 발생하면 예외를 저장했다가 해당 채널에 대해 `receive()`를 가장 처음 호출한 코루틴쪽에 예외가 다시 던져진다. ### 티커 `coroutines` 라이브러리에는 티커(ticker)라고 하는 특별한 랑데뷰 채널이 있다. 이 채널은 `Unit` 값을 계속 발생시키되 한 원소와 다음 원소의 발생 시점이 주어진 지연 시간만큼 떨어져있는 스트림을 만든다. 이 채널을 만들려면 `ticker()` 함수를 사용해야 한다. 이 함수를 호출할 때 다음을 지정할 수 있다. - `delayMillis` : 티커 원소의 발생 시간 간격을 밀리초 단위로 지정한다 - `initialDelayMillis` : 티커 생성 시점부터 최초 발생하는 원소까지의 시간 간격이다. 디폴트 값은 `delayMillis`와 같다. - `context` : 티커를 실행할 코루틴 문맥이다(디폴트는 빈 문맥이다). - `mode` : 티커의 행동을 결정하는 `TickerMode` 이넘이다. - `TickerMode.FIXED_PERIOD` : 생성되는 원소 사이의 시간 간격을 지정된 지연시간에 최대한 맞추기 위해 실제 지연 시간을 조정한다. - `TickerMode.FIXED_RATE` : 실제 흘러간 시간과 관계 없이 `delayMillis`로 지정한 지연 시간만큼 시간을 지연시킨 후 다음 원소를 송신한다. 티커 모드의 차이를 알아보기 위해 다음 코드를 살펴보자. ``` import kotlinx.coroutines.* import kotlinx.coroutines.channels.* fun main() = runBlocking { val ticker = ticker(100) println(withTimeoutOrNull(50) { ticker.receive() }) println(withTimeoutOrNull(60) { ticker.receive() }) delay(250) println(withTimeoutOrNull(1) { ticker.receive() }) println(withTimeoutOrNull(60) { ticker.receive() }) println(withTimeoutOrNull(60) { ticker.receive() }) } ``` 이 코드를 실행하면 다음 출력을 볼 수 있다. ``` null kotlin.Unit kotlin.Unit kotlin.Unit null ``` 이 코드의 실행 과정을 단계별로 살펴보자. 1. 50밀리초 간격으로 티커 신호를 받으려고 시도한다. 티커 지연 시간이 100밀리초이므로 `withTimeoutOrNull()`은 신호를 받지 못하고 타임아웃이 걸려서 널을 반환한다. 2. 그 후 다음 60밀리초 안에 신호를 받으려고 시도한다. 이번에는 티커가 시작한 지 100밀리초가 확실히 지날 것이기 때문에 널이 아닌 확실히 결과를 얻는다. `receive()`가 호출되면 티커가 재개된다. 3. 그 후 소비자 코루틴이 약 250밀리초 동안 일시중단된다. 한편 100밀리초 후에 티커는 다른 신호를 보내고 신호가 수신될 때까지 일시중단된다. 이후 소비자와 티커 코루틴 모두 150밀리초동안 일시중단 상태로 남는다. 4. 소비자 코루틴이 재개되고 신호를 요청하려고 시도한다. 신호가 이미 보내졌기 때문에 `receive()`는 즉시 결과를 반환한다(그래서 타임아웃을 1밀리초로 작게 잡았다). 이제 티커는 마지막 신호를 보낸 이후 얼마나 시간이 지났는지 검사하고, 250밀리초가 지났다는 사실을 알게 된다. 이는 두번의 완전한 주기(200밀리초)와 50밀리초의 나머지에 해당한다. 티커는 자신의 대기 시간을 조정해서 다음 신호를 보낼 때까지의 지연 시간을 100-50인 50밀리초로 줄인다. 이렇게 줄이는 이유는 전체 지연 시간(100밀리초)을 지난 후 새 신호를 보내기 위해서다. 5. 다음으로 신호를 받으려는 `receive()` 호출은 거의 즉시 응답을 받는다. 따라서 티커는 전체 지연 시간(100밀리초)을 다시 기다린다. 그 결과 마지막 `receive()` 호출은 60밀리초 타임아웃 안에 티커로부터 신호를 받지 못하기 때문에 널을 받는다. 티커 모드를 `FIXED_RATE`로 고정하면 결과가 다음과 같이 바뀐다. ``` null kotlin.Unit kotlin.Unit null kotlin.Unit ``` 초반부는 앞의 예제(디폴트 티커 모드 `FIXED_PERIOD`)와 거의 비슷하게 진행된다. 하지만 250밀리초의 긴 지연 이후 소비자 코루틴이 재개될 때부터는 동작이 달라진다. 티커가 250밀리초 지연 사이에 이미 신호를 보냈기 때문에 세번째 `receive()` 호출은 즉시 반환된다. 하지만 이제 티커는 실제 흐른 시간을 고려하지 않고 그냥 100밀리초를 기다린다. 따라서 네번째 `receive()`는 60밀리초 안에 신호를 받지 못하고 널을 반환한다. 반대로 다섯번째 호출의 경우에는 중간에 신호가 발생하기 때문에 신호를 정상적으로 받는다. 티커 관련 API는 현재 실험단계이며 미래의 코루틴 라이브러리 버전에서는 언제든 다른 내용으로 바뀔 수 있다는 점에 유의하라. ## 액터 가변 상태를 스레드 안전하게 공유하는 방법을 구현하는 일반적인 방법으로 액터 모델이 있다. 액터(actor)는 내부 상태와 다른 액터에게 메시지를 보내서 동시성 통신을 진행할 수 있는 수단을 제공하는 객체다. 액터는 자신에게 들어오는 메시지를 리슨(listen)하고, 자신의 상태를 바꾸면서 메시지에 응답할 수 있으며, 다른 메시지를 (자기 자신이나 다른 액터에게) 보낼 수 있고, 새로운 액터를 시작할 수 있다. 액터의 상태는 액터 내부에 감춰져 있기 때문에 다른 액터가 직접 이 상태에 접근할 수 없다. 다른 액터는 단지 메시지를 보내고 응답을 받아서 상태를 알 수 있을 뿐이다. 따라서 액터 모델은 락 기반의 동기화와 관련한 여러가지 문제로부터 자유로울 수 있다. 코틀린 코루틴 라이브러리에서는 `actor()` 코루틴 빌더를 사용해 액터를 만들 수 있다. 액터는 특별한 영역(`ActorScope`)을 만들며 이 영역은 기본 코루틴 영역에 자신에게 들어오는 메시지에 접근할 수 있는 수신자 채널이 추가된 것이다. `actor()` 빌더는 결과를 생성해내는 것이 목적이 아닌 잡을 시작한다는 점에서는 `launch()`와 비슷하지만 `CoroutineExceptionHandler`에 의존하는 `launch()`와 같은 예외 처리 정책을 따른다. 액터 API의 기본적인 사용법을 보여주기 위해, 은행 계좌 잔고를 유지하고 어떤 금액을 저축하거나 인출할 수 있는 액터를 살펴보자. 첫째로 메시지를 표현하는 클래스를 몇가지 정의해야 한다. ``` sealed class AccountMessage class GetBalance( val amount: CompletableDeferred<Long> ) : AccountMessage() class Deposit(val amount: Long) : AccountMessage() class Withdraw( val amount: Long, val isPermitted: CompletableDeferred<Boolean> ) : AccountMessage() ``` 봉인된 클래스를 사용하면 `AccountMessage` 타입을 처리하는 `when` 식에서 `else`를 쓰지 않아도 된다. `GetBalance` 인스턴스에는 `CompletableDeferred`라는 타입의 프로퍼티가 있다. 액터는 이 프로퍼티를 사용해서 `GetBalance` 메시지를 보낸 코루틴에게 현재 잔고를 돌려준다. 비슷하게 `Withdraw` 클래스에도 인출에 성공하면 `true`를 돌려주고 그렇지 않으면 `flase`를 돌려주기 위한 `isPermitted`이라는 프로퍼티가 있다. 이제 계좌 잔고를 유지하는 액터를 구현할 수 있다. 기본 로직은 단순하다. 메시지가 들어오는 채널을 계속 폴링(polling)하면서 수신한 메시지의 종류에 따라 적절한 동작을 수행한다. ``` fun CoroutineScope.accountManager( initialBalance: Long ) = actor<AccountMessage> { var balance = initialBalance for (message in channel) { when (message) { is GetBalance ->message.amount.complete(balance) is Deposit -> { balance += message.amount println("Deposited ${message.amount}") } is Withdraw -> { val canWithdraw = balance >= message.amount if (canWithdraw) { balance -= message.amount println("Withdrawn ${message.amount}") } message.isPermitted.complete(canWithdraw) } } } } ``` `actor()` 빌더는 `produce()`에 대응한다고 할 수 있다. 두 빌더 모두 통신에 채널을 사용하지만, 액터는 데이터를 받기 위해 채널을 사용하고 생산자는 소비자에게 데이터를 보내기 위해 채널을 생성한다. 디폴트로 액터는 랑데뷰 채널을 사용한다. 하지만 `acotr()` 함수를 호출하면서 `capacity`를 변경하면 채널의 성격을 바꿀 수 있다. `CompletableDeferred`에서 `complete()` 메서드를 사용하는 부분에 유의하라. 액터 클라이언트에게 요청 결과를 돌려줄 때 이 방법을 사용한다. 이제 이 액터와 통신하는 코루틴을 한쌍 만들자. ``` private suspend fun SendChannel<AccountMessage>.deposit( name: String, amount: Long ) { send(Deposit(amount)) println("$name: deposit $amount") } private suspend fun SendChannel<AccountMessage>.tryWithdraw( name: String, amount: Long ) { val status = CompletableDeferred<Boolean>().let { send(Withdraw(amount, it)) if (it.await()) "OK" else "DENIED" } println("$name: withdraw $amount ($status)") } private suspend fun SendChannel<AccountMessage>.printBalance( name: String ) { val balance = CompletableDeferred<Long>().let { send(GetBalance(it)) it.await() } println("$name: balance is $balance") } fun main() { runBlocking { val manager = accountManager(100) withContext(Dispatchers.Default) { launch { manager.deposit("Client #1", 50) manager.printBalance("Client #1") } launch { manager.tryWithdraw("Client #2", 100) manager.printBalance("Client #2") } } manager.tryWithdraw("Client #0", 1000) manager.printBalance("Client #0") manager.close() } } ``` 액터에게 메시지를 보내기 위해서는 액터가 사용하는 채널에 대해 `send()` 메서드를 호출해야 한다. 다음은 가능한 출력을 보여준다. ``` Client #1: deposit 50 Deposited 50 Withdrawn 100 Client #2: withdraw 100 (OK) Client #2: balance is 50 Client #1: balance is 50 Client #0: withdraw 1000 (DENIED) Client #0: balance is 50 ``` 연산 순서는 달라질 수 있지만(특히 병렬 처리가 관련되면 순서가 다를 수 있다), 결과는 일관성이 있다. 공개적으로 접근 가능한 가변 상태가 없기 때문에 락이나 임계 영역 같은 동기화 요소를 사용하지 않아도 된다. 액터 빌더도 현재 실험적인 API이기 때문에 향후 변경될 여지가 있다는 점을 언급해둔다. ## 자바 동시서 사용하기 코틀린에서만 사용할 수 있는 코루틴 라이브러리 외에도 JVM 플랫폼에서는 JDK가 제공하는 동기화 요소를 활용할 수 있다. 이번 절에서는 코틀린 표준 라이브러리가 스레드 생성이나 동기화 등과 관련한 작업을 좀 더 편하게 할 수 있도록 제공하는 여러가지 도우미 함수에 대해 살펴본다. ### 스레드 시작하기 범용 스레드를 시작하려면 스레드에서 실행하려는 실행가능(`Runnable`) 객체에 대응하는 람다와 스레드 프로퍼티들을 지정해서 `thread()` 함수를 사용하면 된다. - `start` : 스레드를 생성하자마자 시작할지 여부(디폴트는 `true`) - `isDaemon` : 스레드를 데몬 모드로 시작할지 여부(디폴트는 `false`). 데몬 스레드는 JVM의 종료를 방해하지 않고 메인 스레드가 종료될 때 자동으로 함께 종료된다. - `contextClassLoader` : 스레드 코드가 클래스와 자원을 적재할 때 사용할 클래스 로더(디폴트는 널) - `name` : 커스텀 스레드 이름. 디폴트는 널인데, 이는 JVM이 이름을 자동으로 지정한다는 뜻이다(`Thread-1`, `Thread-2` 등으로 정해진다). - `priority` : `Thread.MIN_PRIORITY`(=`1`)부터 `Thread.MAX_PRIORITY`(=`10`) 사이의 값으로 정해지는 우선순위로, 어떤 스레드가 다른 스레드에 비해 얼마나 많은 CPU 시간을 배정받는지 결정한다. 디폴트 값은 `-1`이며 이 값은 자동으로 우선순위를 정하라는 뜻이다. - `block` : `() -> Unit` 타입의 함수값으로 새 스레드가 생성되면 실행할 코드이다. 예를 들어, 다음 프로그램은 매 150밀리초마다 메시지를 출력하는 스레드를 시작한다. ``` import kotlin.concurrent.thread fun main() { println("Starting a thread...") thread(name = "Worker", isDaemon = true) { for (i in 1..5) { println("${Thread.currentThread().name}: $i") Thread.sleep(150) } } Thread.sleep(500) println("Shutting down...") } ``` 새 스레드가 데몬 모드로 시작했으므로 메인 스레드가 500밀리초 슬립한 다음 실행을 끝낼 때 이 스레드도 함께 끝나기 때문에 메시지가 4개만 출력되는 모습을 볼 수 있다. 이 프로그램을 실행한 결과는 다음과 같다. ``` Starting a thread... Worker: 1 Worker: 2 Worker: 3 Worker: 4 Shutting down... ``` 다른 함수로는 어떤 지정한 시간 간격으로 동작을 수행하는 자바 타이머 관련 함수가 있다. `timer()` 함수는 어떤 작업을 이전 작업이 끝난 시점을 기준으로 고정된 시간 간격으로 실행하는 타이머를 설정한다. 그 결과 어떤 작업이 시간이 오래 걸리면 그 후의 모든 실행이 연기된다. 따라서 이 타이머는 `FIXED_RATE` 모드로 작동하는 코틀린 티커에 비유할 수 있다. 타이머를 `timer()` 호출로 설정할 때 다음 옵션을 지정할 수 있다. - `name` : 타이머 스레드의 이름(디폴트는 널) - `daemon` : 타이머 스레드를 데몬 스레드로 할지 여부(디폴트는 `false`) - `startAt` : 최초로 타이머 이벤트가 발생하는 시간을 나타내는 `Date` 객체 - `period` : 연속된 타이머 이벤트 사이의 시간 간격(밀리초 단위) - `action` : 타이머 이벤트가 발생할 때마다 실행될 `TimeTask.() -> Unit` 타입의 람다 이 방법을 사용하는 대신, 최초 이벤트가 몇 밀리초 뒤에 시작할지를 나타내는 `initalDelay` 파라미터가 있는(이 값의 디폴트는 0이다) 오버로드된 다른 `timer()`를 사용할 수도 있다. 앞의 예제를 타이머를 써서 재작성해보자. ``` import kotlin.concurrent.timer fun main() { println("Starting a thread...") var counter = 0 timer(period = 150, name = "Worker", daemon = true) { println("${Thread.currentThread().name}: ${++counter}") } Thread.sleep(500) println("Shutting down...") } ``` 비슷하게 두 타이머 이벤트 사이의 시간 간격을 최대한 일정하게 맞춰주는 `fixedRateTimer()` 함수들도 있다. 이런 함수들은 장기적으로 타이머 이벤트 사이의 시간 간격을 일정하게 유지하기 위해 지연 시간을 조정해 준다는 점에서 `FIXED_PERIOD` 모드의 티커에 비유할 수 있다. ### 동기화와 락 동기화는 특정 코드 조각이 한 스레드에서만 실행되도록 보장하기 위한 공통적인 기본 요소이다. 이런 코드 조각을 다른 스레드가 실행하고 있다면 해당 코드에 진입하려고 시도하는 다른 스레드들은 모두 대기해야만 한다. 자바에서는 코드에 동기화를 도입하는 방법이 두가지 있다. 첫번째로, 락(lock)으로 사용하려는 어떤 객체를 지정하는 특별한 동기화 블럭을 사용해 동기화해야 하는 코드를 감쌀 수 있다. 코틀린에서도 이런 동기화 구문은 자바 구문과 상당히 비슷하다. 다만 언어에 내장된 구조를 사용하는 대신, 표준 라이브러리 함수를 사용해야 한다. ``` import kotlin.concurrent.thread fun main() { var counter = 0 val lock = Any() for (i in 1..5) { thread(isDaemon = false) { synchronized(lock) { counter += i println(counter) } } } } ``` 개별 덧셈의 결과는 달라질 수 있어서 중간 결과가 바뀔 수 있지만, 동기화로 인해 전체 합계는 항상 15가 된다. 한가지 가능한 출력은 다음과 같다. ``` 1 4 8 13 15 ``` 일반적으로 `synchronized()` 함수는 람다의 반환값을 반환한다. 예를 들어 호출되는 시점의 중간 카운터 값을 읽을 때 `synchronized()`를 사용할 수도 있다. ``` import kotlin.concurrent.thread fun main() { var counter = 0 val lock = Any() for (i in 1..5) {...} // 앞의 예제에서 본 스레드를 생성하는 부분 val currentCounter = synchronized(lock) { counter } println("Current counter: $currentCounter") } ``` 출력되는 중간 결과는 다를 수 있지만, 이 모든 값은 다섯개의 덧셈 스레드 중 하나가 만들어낸 값에 해당한다. 자바에서 동기화에 사용하는 다른 방법은 메서드에 `synchronized` 변경자를 붙이는 것이다. 이럴 경우 메서드 본문 전체가 현재의 클래스 인스턴스(메서드가 인스턴스 메서드인 경우)나 `Class` 인스턴스 자체(메서드가 정적 메서드인 경우)에 의해 동기화된다. 코틀린에서는 `@Synchronized` 애너테이션을 통해 같은 목적을 달성할 수 있다. ``` import kotlin.concurrent.thread class Counter { private var value = 0 @Synchronized fun addAndPrint(value: Int) { value += value println(value) } } fun main() { val counter = Counter() for (i in 1..5) { thread(isDaemon = false) { counter.addAndPrint(i) } } } ``` 표준 라이브러리에는 동기화 블럭과 비슷하게 어떤 `Lock` 객체(`java.util.concuirrent.locks` 패키지에 있음)를 사용해 주어진 람다를 실행하게 해주는 `withLock()` 함수도 있다. `withLock()`을 사용하면 함수가 알아서 락을 풀어주므로, 예외가 발생할 때 락을 푸는 것에 신경을 쓰지 않아도 된다. 예를 들어, `Counter` 클래스에 이 함수를 적용해보자. ``` class Counter { private var value = 0 private val lock = ReentrantLock() fun addAndPrint(value: Int) { lock.withLock { value += value println(value) } } } ``` 그외에도 `ReentrantReadWriteLock`의 읽기와 쓰기 락을 사용해 주어진 작업을 수행하는 `read()`와 `write()` 함수도 있다. `write()` 함수는 기존 읽기 락을 쓰기 락으로 자동 승격시켜줌으로써 재진입 가능(reentrant[^enshahar0547])한 락의 의미를 유지한다. [^enshahar0547]: 옮긴이 - 락을 이미 획득한 스레드가 다시 같은 락을 요청해도 문제없이 작동할 때 이런 락을 재진입가능하다고 말한다. **자바와 코틀린의 차이**: 자바의 `Object` 클래스에 정의된 `wait()`, `notify()`, `notifyAll()` 메서드는 코틀린 `Any`에 없다. 필요하다면 명시적으로 객체를 `java.lang.Object` 값으로 캐스팅해서 이런 함수를 쓸 수 있다. ``` (obj as Object).wait() ``` 다른 블러킹 메서드와 마찬가지로 `wait()`도 일시중단 함수 안에서 호출하지 말아야 한다는 점에 유의하라. ## 결론 이번 장에서는 코틀린 코루틴 기반의 동시성의 기초를 다뤘다. 일시중단 함수를 통해 동시성 코드를 작성할 수 있는 이유를 살펴보고, 코루틴 빌더와 영역과 문맥을 사용해 코루틴의 생명 주기를 관리하는 방법에 대해 설명했다. 그리고 여러 동시성 작업 사이에 데이터를 효율적으로 공유하기 위해 채널과 액터 기반의 통신을 사용하는 방법도 살펴봤다. 추가로 JVM 플랫폼에서 사용할 수 있는 동시성 API를 코틀린에서 활용할 때 도움이 되는 코틀린 표준 라이브러리 함수에 대해 살펴봤다. 다음 장에서는 테스트에 대해 초점을 맞춘다. 코틀린 테스트 코드를 처리할 수 있는 테스트 프레임워크를 몇가지 살펴보고, 코틀린 언어의 특징과 DSL이 여러가지 테스트케이스를 작성할 때 어떻게 유용한지에 대해 살펴본다. ## 질문 1. 일시중단 함수란 무엇인가? 일시중단 함수의 동작과 일반적인 함수의 동작이 어떻게 다른가? 2. `launch()`와 `async()` 빌더로 코루틴을 만드는 방법은 무엇인가? `launch()`와 `async()`의 차이는 무엇인가? 3. `runBlocking()` 빌더의 목적에 대해 설명하라. 4. 구조적 동시성이란 무엇인가? 5. 동시성 잡의 생명주기를 설명하라. 코루틴 트리에서 잡 취소가 어떻게 전파되는지 설명하라. 6. 코루틴 디스패처란 무엇인가? 코루틴 라이브러리가 제공하는 공통적인 디스패처 구현에 대해 설명하라. 7. 코루틴 내부에서 디스패처를 바꾸는 방법은 무엇인가? 8. 코루틴 라이브러리가 사용하는 예외 처리 메커니즘에 대해 설명하라. `CoroutineExceptionHandler`의 역할은 무엇인가? 9. 수퍼바이저 잡이란 무엇인가? 내포된 코루틴에서 발생한 예외를 처리할 때 어떻게 수퍼바이저 잡을 활용할 수 있는가? 10. 채널이란 무엇인가? 코루틴 라이브러리가 지원하는 채널에는 어떤 종류가 있는가? 11. `produce()` 함수를 사용해 채널을 만드는 방법은 무엇인가? 12. 티커 채널의 동작에 대해 설명하라. 13. 액터 모델의 기본 개념을 설명하라. 액터를 코루틴 동시성 라이브러리에서 활용하는 방법은? 14. 코틀린 표준 라이브러리가 제공하는 스레드 생성 유틸리티 함수에 대해 설명하라. 15. 코틀린 코드에서 스레드간의 동기화와 락을 어떻게 사용하는지 설명하라.
Shell
UTF-8
1,284
4.15625
4
[]
no_license
#!/bin/bash # shellcheck disable=SC1091 set -o errexit # Exit immediately if a pipeline returns a non-zero status (set -e) # Usage: clean [build|install] # $ clean build # only delete the BUILD remnants # $ clean install # only delete the INSTALL remnants # $ clean # no arguments, delete all remnants if [[ -z "${1}" ]]; then scope=(build install) else if [[ "${1}" =~ ^(build|install)$ ]]; then scope=("${1}") else printf "Usage: clean [build|install]\\n" printf "Defaults to clean all remnants with no arguments" fi fi column_width=26 package_name=$(jq -r .name package.json) . .scripts/colors.sh declare good_mark grey magenta red reset function delete_files() { for item in "$@"; do printf "${magenta}%${column_width}s${reset}: " "${item}" rm -rf "${item}" echo "${good_mark} ${red}DELETE${reset} ${grey}${PWD}/${item}${reset}" done } for scope_type in "${scope[@]}"; do printf "\\nCleaning %s remnants for %s\\n" "${scope_type}" "${package_name}" printf "%100s\\n" '' | tr ' ' ─ case "${scope_type}" in build) remnants=( dist/ ) delete_files "${remnants[@]}" ;; install) remnants=( node_modules/ package-lock.json ) delete_files "${remnants[@]}" ;; esac done
Python
UTF-8
2,346
2.65625
3
[]
no_license
import numpy as np import keras,os import cv2 from keras.models import Sequential from keras.callbacks import ModelCheckpoint, EarlyStopping from keras.layers import Dense, Conv2D, MaxPool2D , Flatten, Dropout from sklearn.model_selection import train_test_split from keras.optimizers import Adam from astroNN.datasets import galaxy10 from tensorflow.keras import utils import matplotlib.pyplot as plt import matplotlib.image as mpimg def preprocess(images): """ normalize the images Parameter --------- images : list of images The images to convert to normalize Return ------- normalized Images """ #normalizing the images images = images/255 #loading the dataset images, labels = galaxy10.load_data() # To convert the labels to categorical 10 classes labels = utils.to_categorical(labels, 10) preprocess(images) X = images y = labels #splitting the data into train and test data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42) #printing the shapes of test and train data print('Size of X_train', X_train.shape) print('Size of y_train', y_train.shape) print('Size of X_test', X_test.shape) print('Size of y_test', y_test.shape) #converting the arrays to float type labels = labels.astype(np.float32) images = images.astype(np.float32) model = Sequential() model.add(Conv2D(32, kernel_size=(3,3),activation='relu', input_shape=(69,69,3))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.summary() model.compile( loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy']) model.fit(X_train, y_train, epochs=5, validation_data=(X_test, y_test)) output = model.predict(X_train[0]) print("Model prediction:",output) # model.save("astroNN20.h5") plt.plot(model.history.history['loss'],color='b', label='Training Loss') plt.plot(model.history.history['val_loss'],color='r', label='Validation Loss') plt.legend() plt.show() plt.plot(model.history.history['accuracy'],color='b', label='Training Accuracy') plt.plot(model.history.history['val_accuracy'],color='r', label='Validation Accuracy') plt.legend() plt.show()
Python
UTF-8
29,008
3.234375
3
[]
no_license
import enum import random import copy from chessagents import RandomBot, DepthPruningBot class Side(enum.Enum): white = 0 black = 1 @property def other(self): return Side.black if self == Side.white else Side.white class PieceType(enum.Enum): pawn = 1 bishop = 2 rook = 3, knight = 4, queen = 5, king = 6 class Move: def __init__(self, piece_type, moved_from, moved_to, promoted_to=None): self.piece_type = piece_type self.moved_from = moved_from self.moved_to = moved_to self.promoted_to = promoted_to class Board: def __init__(self): self.game_state = GameState() self.moves_history = [] # def setup(self): # self.game_state = GameState.create_starting_game_state() def print(self): self.game_state.print() def play_game(self): self.game_state = GameState.create_starting_game_state() self.moves_history = [] white_agent = RandomBot() black_agent = DepthPruningBot() while True: current_agent = white_agent if self.game_state.side_to_move == Side.white else black_agent new_game_state, move = current_agent.select_move(self) if not move: if self.game_state.is_king_under_attack(self.game_state.side_to_move.other): print("mate, " + ("white" if self.game_state.side_to_move == Side.black else "black") + " won") else: print("stalemate, " + str(self.game_state.side_to_move) + " to move") return self.game_state = new_game_state self.moves_history.append(move) self.print() if self.game_state.is_it_draw(): print("draw") return class GameState: def __init__(self): self.grid = [] self.side_to_move = Side.white self.white_king_moved = False self.black_king_moved = False self.a1_rook_moved = False self.h1_rook_moved = False self.a8_rook_moved = False self.h8_rook_moved = False self.last_move = None for i in range(8): rank = [None] * 8 self.grid.append(rank) @classmethod def create_starting_game_state(cls): state = GameState() for i in range(8): state.grid[1][i] = Pawn(Side.white) state.grid[6][i] = Pawn(Side.black) state.grid[0][0] = Rook(Side.white) state.grid[0][1] = Knight(Side.white) state.grid[0][2] = Bishop(Side.white) state.grid[0][3] = Queen(Side.white) state.grid[0][4] = King(Side.white) state.grid[0][5] = Bishop(Side.white) state.grid[0][6] = Knight(Side.white) state.grid[0][7] = Rook(Side.white) state.grid[7][0] = Rook(Side.black) state.grid[7][1] = Knight(Side.black) state.grid[7][2] = Bishop(Side.black) state.grid[7][3] = Queen(Side.black) state.grid[7][4] = King(Side.black) state.grid[7][5] = Bishop(Side.black) state.grid[7][6] = Knight(Side.black) state.grid[7][7] = Rook(Side.black) return state def is_square_under_attack(self, attacker_side, rank_idx, file_idx): for i in range(8): for j in range(8): piece = self.grid[i][j] if piece and piece.side == attacker_side: if piece.is_attacking_square(attacker_side, self, i, j, rank_idx, file_idx): #print(piece, i, j, rank_idx, file_idx) return True return False def is_valid(self): return not self.is_king_under_attack(self.side_to_move) def is_it_draw(self): # insufficient material check # todo: for now only two kings check piece_counter = 0 for i in range(8): for j in range(8): piece = self.grid[i][j] if piece: piece_counter += 1 if piece_counter > 2: return False return True def is_king_under_attack(self, attacker_side): for i in range(8): for j in range(8): piece = self.grid[i][j] if piece and piece.side == attacker_side.other and piece.get_piece_type() == PieceType.king: return self.is_square_under_attack(attacker_side, i, j) return False def get_possible_moves(self): result = [] for i in range(8): for j in range(8): piece = self.grid[i][j] if piece and piece.side == self.side_to_move: result += piece.get_possible_moves(self, i, j) return result @classmethod def is_board_position_valid(cls, rank_idx, file_idx): return 0 <= rank_idx < 8 and 0 <= file_idx < 8 def print(self): # print from the whites point of view for i in range(7, -1, -1): rank_str = "" for j in range(8): p = self.grid[i][j] rank_str += str(p) if p else ' - ' print(rank_str) print("========================") class Piece: def __init__(self, side): self.side = side @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): return [] @classmethod def get_piece_type(cls): return None class Pawn(Piece): def __init__(self, side): super().__init__(side) def __str__(self): return ' P ' if self.side == Side.white else '_p_' @classmethod def get_piece_type(cls): return PieceType.pawn @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): result = [] # one rank move/promotion move_direction = 1 if game_state.side_to_move == Side.white else -1 piece_in_front = game_state.grid[rank_idx + move_direction][file_idx] if piece_in_front is None: if (game_state.side_to_move == Side.white and rank_idx < 6) or \ (game_state.side_to_move == Side.black and rank_idx > 1): new_state = copy.deepcopy(game_state) new_state.grid[rank_idx + move_direction][file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (rank_idx + move_direction, file_idx)) result.append((new_state, move)) else: promotion_pieces = [Queen(game_state.side_to_move), Bishop(game_state.side_to_move), Knight(game_state.side_to_move), Rook(game_state.side_to_move)] for piece in promotion_pieces: new_state = copy.deepcopy(game_state) new_state.grid[rank_idx + move_direction][file_idx] = piece new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (rank_idx + move_direction, file_idx), piece.get_piece_type()) result.append((new_state, move)) # captures move_direction = 1 if game_state.side_to_move == Side.white else -1 capture_positions = [(rank_idx + move_direction, file_idx - 1), (rank_idx + move_direction, file_idx + 1)] for new_rank_idx, new_file_idx in capture_positions: if not GameState.is_board_position_valid(new_rank_idx, new_file_idx): continue piece_to_capture = game_state.grid[new_rank_idx][new_file_idx] if piece_to_capture and piece_to_capture.side != game_state.side_to_move: if (game_state.side_to_move == Side.white and rank_idx < 6) or \ (game_state.side_to_move == Side.black and rank_idx > 1): new_state = copy.deepcopy(game_state) new_state.grid[new_rank_idx][new_file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx)) result.append((new_state, move)) else: promotion_pieces = [Queen(game_state.side_to_move), Bishop(game_state.side_to_move), Knight(game_state.side_to_move), Rook(game_state.side_to_move)] for piece in promotion_pieces: new_state = copy.deepcopy(game_state) new_state.grid[new_rank_idx][new_file_idx] = piece new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx), piece.get_piece_type()) result.append((new_state, move)) # two ranks move if (game_state.side_to_move == Side.white and rank_idx == 1) or (game_state.side_to_move == Side.black and rank_idx == 6): move_direction = 1 if game_state.side_to_move == Side.white else -1 if game_state.grid[rank_idx + move_direction][file_idx] is None and game_state.grid[rank_idx + move_direction * 2][file_idx] is None: new_state = copy.deepcopy(game_state) new_state.grid[rank_idx + move_direction * 2][file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (rank_idx + move_direction * 2, file_idx)) result.append((new_state, move)) # en passant if game_state.last_move: if game_state.last_move.piece_type == PieceType.pawn: left_and_right_positions = [(rank_idx, file_idx - 1), (rank_idx, file_idx + 1)] for pos in left_and_right_positions: if game_state.is_board_position_valid(pos[0], pos[1]): if game_state.grid[pos[0]][pos[1]] and game_state.grid[pos[0]][pos[1]].get_piece_type() == PieceType.pawn: move_direction = 1 if game_state.side_to_move == Side.white else -1 if game_state.last_move.moved_to == (pos[0], pos[1]) and game_state.last_move.moved_from == (pos[0] + move_direction * 2, pos[1]): new_state = copy.deepcopy(game_state) new_state.grid[pos[0]][pos[1]] = None new_state.grid[rank_idx][file_idx] = None new_state.grid[pos[0] + move_direction][pos[1]] = Pawn(game_state.side_to_move) new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (pos[0] + move_direction, pos[1])) result.append((new_state, move)) return result @classmethod def is_attacking_square(cls, side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx): move_direction = 1 if side == Side.white else -1 return self_rank_idx + move_direction == square_rank_idx and abs(self_file_idx - square_file_idx) == 1 class Rook(Piece): def __init__(self, side): super().__init__(side) def __str__(self): return ' R ' if self.side == Side.white else ' r ' @classmethod def get_piece_type(cls): return PieceType.rook @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): result = [] movement_directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] for direction in movement_directions: new_rank_idx = rank_idx + direction[0] new_file_idx = file_idx + direction[1] while True: if not game_state.is_board_position_valid(new_rank_idx, new_file_idx): break piece = game_state.grid[new_rank_idx][new_file_idx] if piece: if piece.side == game_state.side_to_move: break new_state = copy.deepcopy(game_state) new_state.grid[new_rank_idx][new_file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if game_state.side_to_move == Side.white: if rank_idx == 0 and file_idx == 0: new_state.a1_rook_moved = True elif rank_idx == 0 and file_idx == 7: new_state.h1_rook_moved = True else: if rank_idx == 7 and file_idx == 0: new_state.a8_rook_moved = True elif rank_idx == 7 and file_idx == 7: new_state.h8_rook_moved = True if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx)) result.append((new_state, move)) if piece: break new_rank_idx += direction[0] new_file_idx += direction[1] return result @classmethod def is_attacking_square(cls, side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx): if self_rank_idx == square_rank_idx: direction = 1 if square_file_idx > self_file_idx else -1 for new_file_idx in range(self_file_idx + direction, square_file_idx, direction): piece = game_state.grid[self_rank_idx][new_file_idx] if piece: return False return True if self_file_idx == square_file_idx: direction = 1 if square_rank_idx > self_rank_idx else -1 for new_rank_idx in range(self_rank_idx + direction, square_rank_idx, direction): piece = game_state.grid[new_rank_idx][self_file_idx] if piece: return False return True return False class Knight(Piece): def __init__(self, side): super().__init__(side) def __str__(self): return ' N ' if self.side == Side.white else ' n ' @classmethod def get_piece_type(cls): return PieceType.knight @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): new_positions = [(rank_idx + 2, file_idx - 1), (rank_idx + 2, file_idx + 1), (rank_idx + 1, file_idx + 2), (rank_idx - 1, file_idx + 2), (rank_idx - 2, file_idx + 1), (rank_idx - 2, file_idx - 1), (rank_idx + 1, file_idx - 2), (rank_idx - 1, file_idx - 2)] result = [] for new_rank_idx, new_file_idx in new_positions: if game_state.is_board_position_valid(new_rank_idx, new_file_idx): piece = game_state.grid[new_rank_idx][new_file_idx] if piece is None or piece.side != game_state.side_to_move: new_game_state = copy.deepcopy(game_state) new_game_state.side_to_move = game_state.side_to_move.other new_game_state.grid[new_rank_idx][new_file_idx] = new_game_state.grid[rank_idx][file_idx] new_game_state.grid[rank_idx][file_idx] = None if new_game_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx)) result.append((new_game_state, move)) return result @classmethod def is_attacking_square(cls, side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx): new_positions = [(self_rank_idx + 2, self_file_idx - 1), (self_rank_idx + 2, self_file_idx + 1), (self_rank_idx + 1, self_file_idx + 2), (self_rank_idx - 1, self_file_idx + 2), (self_rank_idx - 2, self_file_idx + 1), (self_rank_idx - 2, self_file_idx - 1), (self_rank_idx + 1, self_file_idx - 2), (self_rank_idx - 1, self_file_idx - 2)] return (square_rank_idx, square_file_idx) in new_positions class Bishop(Piece): def __init__(self, side): super().__init__(side) def __str__(self): return ' B ' if self.side == Side.white else ' b ' @classmethod def get_piece_type(cls): return PieceType.bishop @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): result = [] movement_directions = [(1, 1), (1, -1), (-1, -1), (-1, 1)] for direction in movement_directions: new_rank_idx = rank_idx + direction[0] new_file_idx = file_idx + direction[1] while True: if not game_state.is_board_position_valid(new_rank_idx, new_file_idx): break piece = game_state.grid[new_rank_idx][new_file_idx] if piece: if piece.side == game_state.side_to_move: break new_state = copy.deepcopy(game_state) new_state.grid[new_rank_idx][new_file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx)) result.append((new_state, move)) if piece: break new_rank_idx += direction[0] new_file_idx += direction[1] return result @classmethod def is_attacking_square(cls, side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx): if square_rank_idx == self_rank_idx or square_file_idx == self_file_idx: return False rank_direction = 1 if square_rank_idx > self_rank_idx else -1 file_direction = 1 if square_file_idx > self_file_idx else -1 if abs(square_rank_idx - self_rank_idx) != abs(square_file_idx - self_file_idx): return False for i in range(abs(square_rank_idx - self_rank_idx) - 1): new_position = (self_rank_idx + rank_direction * (i + 1), self_file_idx + file_direction * (i + 1)) piece = game_state.grid[new_position[0]][new_position[1]] if piece: return False return True class Queen(Piece): def __init__(self, side): super().__init__(side) def __str__(self): return ' Q ' if self.side == Side.white else ' q ' @classmethod def get_piece_type(cls): return PieceType.queen @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): result = [] movement_directions = [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, -1), (-1, 1)] for direction in movement_directions: new_rank_idx = rank_idx + direction[0] new_file_idx = file_idx + direction[1] while True: if not game_state.is_board_position_valid(new_rank_idx, new_file_idx): break piece = game_state.grid[new_rank_idx][new_file_idx] if piece: if piece.side == game_state.side_to_move: break new_state = copy.deepcopy(game_state) new_state.grid[new_rank_idx][new_file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = game_state.side_to_move.other if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx)) result.append((new_state, move)) if piece: break new_rank_idx += direction[0] new_file_idx += direction[1] return result @classmethod def is_attacking_square(cls, side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx): return Bishop.is_attacking_square(side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx)\ or Rook.is_attacking_square(side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx) class King(Piece): def __init__(self, side): super().__init__(side) def __str__(self): return ' K ' if self.side == Side.white else ' k ' @classmethod def get_piece_type(cls): return PieceType.king @classmethod def __is_king_moved__(cls, game_state): if game_state.side_to_move == Side.white: return game_state.white_king_moved else: return game_state.black_king_moved @classmethod def __is_queens_rook_available_for_castling__(cls, game_state): if game_state.side_to_move == Side.white: if game_state.a1_rook_moved: return True piece = game_state.grid[0][0] if piece and piece.side == Side.white: assert (piece.get_piece_type() == PieceType.rook) return False else: # rook captured return True else: if game_state.a8_rook_moved: return True piece = game_state.grid[7][0] if piece and piece.side == Side.black: assert (piece.get_piece_type() == PieceType.rook) return False else: # rook captured return True @classmethod def __is_kings_rook_available_for_castling__(cls, game_state): if game_state.side_to_move == Side.white: if game_state.h1_rook_moved: return True piece = game_state.grid[0][7] if piece and piece.side == Side.white: assert (piece.get_piece_type() == PieceType.rook) return False else: # rook captured return True else: if game_state.h8_rook_moved: return True piece = game_state.grid[7][7] if piece and piece.side == Side.black: assert (piece.get_piece_type() == PieceType.rook) return False else: # rook captured return True @classmethod def __get_castling_moves__(cls, game_state): result = [] rank_idx = 0 if game_state.side_to_move == Side.white else 7 file_idx = 4 if not cls.__is_king_moved__(game_state): # queen side castling if not cls.__is_queens_rook_available_for_castling__(game_state): assert (game_state.grid[rank_idx][4].get_piece_type() == PieceType.king) assert (game_state.grid[rank_idx][0].get_piece_type() == PieceType.rook) squares_between_king_and_rook_are_empty = True for file in range(1, 4): if game_state.grid[rank_idx][file]: squares_between_king_and_rook_are_empty = False break if squares_between_king_and_rook_are_empty: king_or_squares_are_in_check = False for file in range(1, 5): if game_state.is_square_under_attack(Side.black, rank_idx, file): king_or_squares_are_in_check = True break if not king_or_squares_are_in_check: new_state = copy.deepcopy(game_state) new_state.grid[rank_idx][2] = new_state.grid[rank_idx][4] # move king new_state.grid[rank_idx][4] = None new_state.grid[rank_idx][3] = new_state.grid[rank_idx][0] # move rook new_state.grid[rank_idx][0] = None new_state.white_king_moved = True new_state.a1_rook_moved = True move = Move(cls.get_piece_type(), (rank_idx, 4), (rank_idx, 2)) result.append((new_state, move)) # king side castling if not cls.__is_kings_rook_available_for_castling__(game_state): assert (game_state.grid[rank_idx][4].get_piece_type() == PieceType.king) assert (game_state.grid[rank_idx][7].get_piece_type() == PieceType.rook) squares_between_king_and_rook_are_empty = True for file in range(5, 8): if game_state.grid[rank_idx][file]: squares_between_king_and_rook_are_empty = False break if squares_between_king_and_rook_are_empty: king_or_squares_are_in_check = False for file in range(4, 8): if game_state.is_square_under_attack(Side.black, rank_idx, file): king_or_squares_are_in_check = True break if not king_or_squares_are_in_check: new_state = copy.deepcopy(game_state) new_state.grid[rank_idx][6] = new_state.grid[rank_idx][4] # move king new_state.grid[rank_idx][4] = None new_state.grid[rank_idx][7] = new_state.grid[rank_idx][5] # move rook new_state.grid[rank_idx][7] = None new_state.white_king_moved = True new_state.h1_rook_moved = True move = Move(cls.get_piece_type(), (rank_idx, 4), (rank_idx, 6)) result.append((new_state, move)) return result @classmethod def get_possible_moves(cls, game_state, rank_idx, file_idx): side = game_state.side_to_move result = [] directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for i, j in directions: new_rank_idx = rank_idx + i new_file_idx = file_idx + j if game_state.is_board_position_valid(new_rank_idx, new_file_idx): piece = game_state.grid[new_rank_idx][new_file_idx] if piece and side == piece.side: continue new_state = copy.deepcopy(game_state) new_state.grid[new_rank_idx][new_file_idx] = new_state.grid[rank_idx][file_idx] new_state.grid[rank_idx][file_idx] = None new_state.side_to_move = side.other if side == Side.white: new_state.white_king_moved = True else: new_state.black_king_moved = True if new_state.is_valid(): move = Move(cls.get_piece_type(), (rank_idx, file_idx), (new_rank_idx, new_file_idx)) result.append((new_state, move)) # castling result += cls.__get_castling_moves__(game_state) return result @classmethod def is_attacking_square(cls, side, game_state, self_rank_idx, self_file_idx, square_rank_idx, square_file_idx): return abs(self_rank_idx - square_rank_idx) <= 1 and abs(self_file_idx - square_file_idx) <= 1 board = Board() board.play_game()
Java
UTF-8
2,232
2.609375
3
[]
no_license
package br.ufc.ubicomp.promocity.model; import java.util.ArrayList; import java.util.Date; import br.ufc.ubicomp.promocity.model.Cupom; public class Promocao { private int id; private String nome; private String descricao; private String codigo; private Date dataInicio; private Date dataFim; private ArrayList<Cupom> listaDeCupons; private int idEstabelecimento; public Promocao(){ } public Promocao(int id, String nome, String descricao, int idEstabelecimento){ this.id = id; this.nome = nome; this.descricao = descricao; this.idEstabelecimento = idEstabelecimento; this.listaDeCupons = new ArrayList<>(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getIdEstabelecimento() { return idEstabelecimento; } public void setIdEstabelecimento(int idEstabelecimento) { this.idEstabelecimento = idEstabelecimento; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public Date getDataInicio() { return dataInicio; } public void setDataInicio(Date dataInicio) { this.dataInicio = dataInicio; } public Date getDataFim() { return dataFim; } public void setDataFim(Date dataFim) { this.dataFim = dataFim; } public ArrayList<Cupom> getListaDeCupons() { return listaDeCupons; } public void setListaDeCupons(ArrayList<Cupom> listaDeCupons) { this.listaDeCupons = listaDeCupons; } public void addCupom(Cupom cupom) { this.listaDeCupons.add(cupom); } public void removerCupom(Cupom cupom) { this.listaDeCupons.remove(cupom); } public void removerTodosOsCupons() { this.listaDeCupons.clear(); } }
Python
UTF-8
354
3.1875
3
[]
no_license
''' 12. Dictionaries >>> keys : any immutable type >>> values: any type ''' #--------------- method ------------------------------ eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} # d.keys() method returns [ a list of its keys ] # d.values() method returns [ a list of its values ] # d.items() method returns [ a list of tuples of (key,value) ]
JavaScript
UTF-8
468
3.3125
3
[ "MIT", "ISC" ]
permissive
/** * format length output * @param {ol.geom.Polygon} polygon * @return {string} */ 'use strict' module.exports = function (polygon) { var area = polygon.getArea() var output if (area > 1000000) { output = (Math.round(area / 1000000 * 100) / 100) + ' km<sup>2</sup>' } else if (area > 10000) { output = (Math.round(area / 10000 * 100) / 100) + ' ha' } else { output = (Math.round(area * 100) / 100) + ' m<sup>2</sup>' } return output }
Java
UTF-8
1,252
2.546875
3
[]
no_license
package com.dayou.mysocket; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mStartSever; private Button mSendMessege; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initListener(); } private void initView() { mStartSever = (Button) findViewById(R.id.startSever); mSendMessege = (Button) findViewById(R.id.sendMessege); } private void initListener() { mStartSever.setOnClickListener(this); mSendMessege.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.startSever: startServer(); break; case R.id.sendMessege: sendMessage(); break; } } private void sendMessage() { SocketClient.sendMessage(); } private void startServer() { SocketSever.startSever(); } }
PHP
UTF-8
4,738
2.53125
3
[]
no_license
<?php const AVAILABLE_IMAGE_TYPES = [ 'image/jpeg', 'image/png', 'image/gif', ]; const MAX_IMAGE_SIZE = 10 * 1024 * 1024; const IMAGE_DIR1 = 'images'; const IMAGE_DIR = IMAGE_DIR1 . DIRECTORY_SEPARATOR . 'gallery' . DIRECTORY_SEPARATOR; if (!file_exists(IMAGE_DIR)) { mkdir(IMAGE_DIR1); mkdir(IMAGE_DIR); } $message = ""; $image = $_FILES['image']; if ($image['error'] != 0) { $message = "An error happened with file " . $image['name']; } else if (!in_array($image['type'], AVAILABLE_IMAGE_TYPES)) { $message = "unavailable file " . $image['name'] . " type"; } else if ($image['size'] >= MAX_IMAGE_SIZE) { $message = "file " . $image['name'] . " is too large"; } else { $extension = pathinfo($image['name'])['extension']; $fileName = pathinfo($image['name'])['filename'] . uniqid() . '.' . $extension; $filePath = IMAGE_DIR . $fileName; if (move_uploaded_file($image['tmp_name'], $filePath)) { $watermark = imagecreatefrompng('watermark.png'); $destination = 'destination'; $marginLeft = 20; $marginBottom = 20; $sx = imagesx($watermark); $sy = imagesy($watermark); $img = imagecreatefromjpeg($filePath); imagecopy($img, $watermark, $marginLeft, imagesy($img) - $sy - $marginBottom, 0, 0, $sx, $sy); unlink($filePath); $i = imagejpeg($img, $filePath, 100); imagedestroy($img); $message = "file " . $image['name'] . " has been uploaded"; } else { $message = "Couldn't move file " . $image['name'] . " to the directory"; } } $images = scandir(IMAGE_DIR); $images = array_values(array_filter($images, function ($file) { if (strstr($file, ".") === ".jpg" || strstr($file, ".") === ".png" || strstr($file, ".") === ".gif") { return $file; } })); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Gallery</title> <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Merriweather&family=Roboto+Mono:ital@1&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <link rel="stylesheet" href="css/main.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <script src="js/main.js"></script> </head> <body> <header> <h1>Gallery</h1> </header> <main> <form method="post" enctype="multipart/form-data" name="image"> <div class="example-2"> <div class="form-group"> <input type="file" id="file" name="image" class="input-file" accept="image/*"> <label for="file" class="btn btn-tertiary js-labelFile"> <i class="icon fa fa-check"></i> <span class="js-fileName">Upload file</span> </label> </div> </div> <input type="submit" value="Upload"> </form> <p class="max-size">Max image size: <?= MAX_IMAGE_SIZE / 1024 / 1024 ?> MB</p> <div class="container"> <?php foreach ($images as $key => $file) : ?> <div class="image-container" value="<?= $key ?>"> <div class="image"> <i class="fas fa-arrow-left invisible"></i> <i class="fas fa-times invisible"></i> <img src="<?= IMAGE_DIR . $file ?>" alt="<?= $file ?>"> <i class="fas fa-arrow-right invisible"></i> </div> </div> <?php endforeach; ?> </div> <form method="post" enctype="multipart/form-data" name="image"> <div class="example-2"> <div class="form-group"> <input type="file" id="file" name="image" class="input-file" accept="image/*"> <label for="file" class="btn btn-tertiary js-labelFile"> <i class="icon fa fa-check"></i> <span class="js-fileName">Upload file</span> </label> </div> </div> </form> <p class="max-size">Max image size: <?= MAX_IMAGE_SIZE / 1024 / 1024 ?> MB</p> </main> <footer> <p>&copy; junstudio 2020</p> </footer> <script> window.onload = function () { if ("<?= $message ?>" && "<?= $image['name'] ?>") { alert("<?= $message ?>"); } } </script> </body> </html>
Python
UTF-8
78
3.0625
3
[]
no_license
N = int(input()) C = list(input()) Rn = C.count('R') print(C[:Rn].count('W'))
C++
UTF-8
2,921
2.6875
3
[]
no_license
#ifndef BOOST_STATIC_LINK # define BOOST_TEST_DYN_LINK #endif // BOOST_STATIC_LINK #define BOOST_TEST_MODULE CtppHtml #define BOOST_AUTO_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> #include <sstream> #include "Log.hpp" struct LogSequence { struct Head { struct Next { std::stringstream *_stream; Next(const Next &next) : _stream(next._stream) {} template<class Type> explicit Next(std::stringstream *stream, const Type &value) : _stream(stream) { (*_stream) << value; } template<class Type> Next operator << (const Type &value) { return Next(_stream, value); } }; std::shared_ptr<std::stringstream> _stream; std::string _module; Head(const Head &head) : _stream(head._stream) , _module(head._module) {} template<class Type> explicit Head(const std::string& module, const Type &value) : _stream(new std::stringstream) , _module(module) { (*_stream) << value; } ~Head() { base::Singleton<base::Log>::getInstance()->print(DEBUG, _module, _stream->str().c_str()); } template<class Type> Next operator << (const Type &value) { return Next(_stream.get(), value); } }; std::string _module; LogSequence(const std::string &module) : _module(module) {} template<class Type> Head operator << (const Type &value) { return Head(_module, value); } }; //struct TempLog { // std::stringstream _stream; // bool _is_head; // bool _is_complete; // std::string _method; // TempLog *_parent; // // TempLog(const std::string &method) // : _is_head(true) // , _is_complete(false) // , _method(method) // , _parent(this) // {} // // TempLog(const TempLog &log) // : _is_head(false) // , _is_complete(log._is_head) // , _parent(log._parent) // {} // // ~TempLog() { // if (_is_complete) { // base::Singleton<base::Log>::getInstance()->print(DEBUG, _parent->_method, _parent->_stream.str().c_str()); // } // } //}; // // //template<class Type> //TempLog operator << (const TempLog &log, Type type) { // TempLog &l = const_cast<TempLog&>(log); // l._parent->_stream << type; // TempLog _log(log); // return _log; //} BOOST_AUTO_TEST_CASE(TestLogCompleter) { LOG_TO_STDOUT; std::cout << "Begin \n"; LogSequence t("TEST"); t << 1 << "," << 2 << "," << 3; { LogSequence t("test"); t << "a" << "," << "b"; } std::cout << "End \n"; }
Ruby
UTF-8
825
3.046875
3
[]
no_license
require_relative("../db/sql_runner") class Film attr_reader :id attr_accessor :title, :price def initialize(options) @title = options['title'] @price = options['price'].to_i @id = options['id'].to_i if ['id'] end def save() sql = "INSERT INTO films (title, price) VALUES ($1, $2) RETURNING id" values = [@title, @price] films = SqlRunner.run(sql, values).first @id = films['id'].to_i end def customers() sql = "SELECT customers.* FROM customers INNER JOIN tickets ON customers.id = tickets.customer_id WHERE tickets.film_id = $1" values = [@id] customers = SqlRunner.run(sql,values) return customers.map {|customers| Customer.new(customers)} end def self.delete_all() sql = "DELETE FROM films" values = [] SqlRunner.run(sql, values) end end
Markdown
UTF-8
31,202
2.859375
3
[]
no_license
# NDCDevOpsWorkshop ## Summary The purpose of this repository and file is to take you through the "Turbo-charging your Azure DevOps experience with Octopus Deploy" workshop scheduled for the 11th & 12th March in Oslo, Norway. This workshop will be led by Continuous Delivery Architect [Derek Campbell](https://twitter.com/DevOpsDerek) from [Octopus Deploy](https://octopus.com/). ## Agenda This workshop covers core CI/CD concepts and best practices, reviews real-world release management and automation problems, and how to overcome them using Azure, Azure DevOps, and Octopus Deploy. ### What you will learn We will take an existing application and get it building and testing on Azure DevOps, then configure the release, and lastly, pass the artifact through to Octopus Deploy ready for deployment. You will get hands-on access provisioning infrastructure on Azure, building an Azure DevOps pipeline and creating an Octopus Cloud instance. You will use all of these tools to configure and prepare a build, test it, create the release and deployment pipeline of a sample application, and deploy from Dev to Test, and lastly to Production. The list of topics includes: * Creating Octopus Cloud instance. * Creating Azure DevOps project. * Integrating Azure DevOps & Octopus Deploy. * Set up Azure Service Principal. * Creating Azure Web Apps & VMs in Azure. * Adding infrastructure in Octopus Deploy. * Creating the deployment process in Octopus Deploy. * Creating build in Azure Pipelines & test plans in Azure Test Plans. * Packaging applications. * Administration of Azure DevOps & Octopus. * Runbooks, Multi-Tenancy, Workers, Channels, Lifecycles, & Spaces. * Common Deployment patterns such as Canary, Blue/Green, & Red/Black. ### Who should attend This workshop is for Developers, Ops, and DevOp Engineers starting on their CI/CD journey or for engineers looking for some fresh ideas. This is also ideal for anybody using an older version of Octopus who wants a refresher. ## Wednesday 11th March Morning Session Welcome to "Turbo-charging your Azure DevOps experience with Octopus Deploy." Over the next two days, we will setup Azure DevOps, Azure infrastructure, and Octopus Cloud to deploy OctoFX. The first thing we will do this morning is to go through the pre-requisites and ensure you have these setup. ### Pre-Requisites * Free Azure/MSDN subscription with access to create an Azure Service Principal. A Corporate subscription is best avoided. * Email address to spin up free Azure DevOps & Octopus instances. (We have some available if you have already used your email for Azure and Azure DevOps, ask for access to email). ### Computer Setup Attendees will need a laptop with Windows and the following software: * Visual Studio Code * MSBuild * NET Framework 4.6.1+ * GIT * Remote Desktop Software like [Microsoft's Remote Desktop Connection Manager](https://www.microsoft.com/en-gb/download/details.aspx?id=44989) ### What is Continuous Integration "[Continuous integration](https://en.wikipedia.org/wiki/Continuous_integration) (CI) is the practice of merging all developers' working copies to a shared mainline several times a day." ### What is Continuous Delivery "[Continuous delivery](https://en.wikipedia.org/wiki/Continuous_delivery) is a software engineering approach in which teams produce software in short cycles, ensuring that the software can be reliably released and deployed at any time. It aims at building, testing, and releasing software with greater speed and frequency." ### What is Continuous Deployment "[Continuous deployment](https://en.wikipedia.org/wiki/Continuous_deployment) (CD) is a software engineering approach in which software functionalities are delivered frequently through automated deployments. Continuous deployment contrasts with continuous delivery, a similar approach in which software functionalities are also regularly delivered and deemed to be capable of being deployed but are not deployed. ### Octopus Cloud Sign-up The first thing we will do is sign-up for the free Cloud Starter edition for each attendee. You can get more details on [Octopus.com](https://octopus.com/docs/octopus-cloud). * Browse to <https://octopus.com/> * Click Get Started * Register * Input URL, Select the "West Europe" Region, Company, Name, Email & Password * Wait for it to spin-up & sign in. * Take note of URL ### Azure DevOps Sign-up We will now sign up for an Azure DevOps account, Organization & Project. You can get more details at [Microsoft Docs](https://docs.microsoft.com/en-us/azure/devops/user-guide/sign-up-invite-teammates?view=azure-devops). * Browse to <http://dev.azure.com/> * Select Start Free * Sign-in with an account that has no Azure DevOps Organizations (You will need to set up a Microsoft account for this) * Create Organization, Select Organization Name & Select West Europe * Create OctoFX Project and leave blank * Take note of the URL ### Integrating Azure DevOps & Octopus Deploy * [Generate an Octopus API Key](https://octopus.com/docs/octopus-rest-api/how-to-create-an-api-key) (Class led instructions provided). * Note the API Key * Install [Octopus Deploy's Azure DevOps extension](https://octopus.com/downloads) in Azure DevOps (Class led instructions provided). * Set up Service Connection to your Octopus Cloud instance (Class led instructions provided). ### OctoFX Background [OctoFX](https://github.com/OctopusSamples/OctoFX) is a sample application built to demonstrate how a multi-tier application is deployed using Octopus Deploy. The application consists of three major components: * Trading Website - A customer-facing ASP.NET MVC website, where customers trade currencies. Customers can register, login, manage their beneficiary account details, get quotes, and book deals. * Deal Settlement Service - A .NET Windows Service that simulates the bank reconciliation and deals settlement process. It checks whether the OctoFX clearing accounts have received funds for any pending deals, and then initiates the transfer when deals are ready to be settled. * A SQL Server database underpins the system. ## Wednesday 11th March Afternoon Session ### Pipeline We will set up the following pipeline for OctoFX, using Octopus Deploy & Azure DevOps, deploying to Azure Infrastructure. ![CI/CD Pipeline](/Images/pipeline.png) ### Infrastructure Overview As a summary, we will deploy: * 4 x Azure Web Apps (1 for Development, 1 for Test, and 2 for Production). * 1 x SQL Server for all environments. * 1 x Jump Box for all environments. * 1 x Windows Server for OctoFX Window Services for all environments. The SQL Server, Jump Box, & Windows Services Server are all shared between environments to keep the hosting costs low. ### Development For the development environment, we will deploy: * 1 x Azure Web App for Development. * 1 x SQL Database for Development. * 1 x Windows Service for Development. * 1 x Jump Box (For security & SQL Deployments). ![Development Infrastructure](/Images/dev.png) ### Test For the test environment, we will deploy: * 1 x Azure Web App for Test. * 1 x SQL Database for Test. * 1 x Windows Service for Test. * 1 x Jump Box (For security & SQL Deployments). ![Test Infrastructure](/Images/test.png) ### Production For the development environment, we will deploy: * 2 x Azure Web Apps for Production. * 1 x SQL Database for Production. * 1 x Windows Service for Production. * 1 x Jump Box (For security & SQL Deployments). ![Production Infrastructure](/Images/prod.png) ### Azure Sign-up You will need an email address that is not tied to an existing Azure subscription. If you need an email address to sign up, you can create one on gmail.com, outlook.com, or if you ask the workshop host, they can provide you with one. * Browse to <https://azure.microsoft.com/en-gb/free/>. * Go through the sign-up process. * You should have access to 12 months of free services, £150 credit to use in 30 days, and access to 25+ free Services. * Save the details. * [Generate Azure Service Principal](https://octopus.com/docs/infrastructure/deployment-targets/azure#create-service-principal-account-in-azure) (Class led instructions provided). * Note the API Key & Azure Service Principal details. * Set up Azure Service Principal in Octopus (Class led instructions provided. It will likely fail validation if created less than 15 minutes ago - Try again at least 15 minutes after you created it). ### Deploying Azure Infrastructure (Class led instructions provided) This section will be carried out as Instructor-led training. #### What are ARM Templates An Azure Resource Manager(ARM) template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. With more companies moving to the cloud, many teams have adopted agile development methods. These teams iterate quickly. They need to deploy their solutions to the cloud repeatedly and know their infrastructure is in a reliable state. As infrastructure has become part of the iterative process, the division between operations and development has disappeared. Teams need to manage infrastructure and application code through a unified process. To meet these challenges, you can automate deployments and adopt the practice of infrastructure as code. In code, you define the infrastructure that needs to be deployed. The infrastructure code becomes part of your project. Just like the application code, you store the infrastructure code in a source repository and version it, and anyone on your team can run the code and deploy similar environments. To implement infrastructure as code for your Azure solutions, use Azure Resource Manager templates. The template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it. In the template, you specify the resources to deploy and the properties for those resources. ### Adding Infrastructure to Octopus Deploy This section of the workshop will be led by a presentation, so please follow on-screen. * Create 4 Web Apps using ARM Template. (1 x Development, 1 x Test & 2 x Production). * Create 1 Bastion box using Server ARM Template. * Create 1 SQL Server using SQL ARM Template. * Create 1 Windows Service Server with Server ARM Template. ### Infrastructure Tips & Instructions All of the following will be carried out by class led instructions: * Turn on auto-shutdown on Azure VM's to reduce costs. * Get Web Apps IP addresses in properties, and add this and the IP from Windows Service Server to be allowed to connect to port 1433 on the SQL Server. * Turn on Windows & SQL Authentication on SQL Server. * Allow RDP on SQL Server to just the Bastion Box, and connect into SQL Server. * Install [Tentacles](https://octopus.com/downloads) on Bastion box and Windows Services Server, and add to Octopus Cloud. * Add the environments Development, Test, & Production to Octopus Cloud. * Add infrastructure to Octopus Cloud instance. * Tag Azure Web Apps with `OctoFX-Web`. * Tag Bastion Box with `OctoFX-Bastion`. * Tag Windows Service Server with `OctoFX-RateSvc`. ### Create the Deployment Process in Octopus Deploy This section of the workshop will be led by a presentation, so please follow on-screen. You can also see OctoFX being configured in Octopus Deploy on [YouTube](https://www.youtube.com/watch?v=6DsJvtTcGMc). * Create Development, Test, & Production environments (if not already done). * Create OctoFX project. * Create OctoFX variables. * Create OctoFX variable for connection string (Server=#{OctoFX.Database.Server};Database=#{OctoFX.Database.Name};User ID=#{OctoFX.Database.User};Password=#{OctoFx.Database.Password};). * Create OctoFX deployment process. Your OctoFX deployment process should look something like: ![It should look something like](/Images/octopusoctofx.png) ### Thursday 12th March Morning Session * Turn on infrastructure if you have shutdown enabled, and run Octopus health check and confirm all are available. ### Create Build & Release in Azure DevOps This section of the workshop will be led by a presentation. We have a recording available on [YouTube](https://www.youtube.com/watch?v=36DLmkQ6Gs4) which you can use to configure Azure DevOps. You should already have Azure DevOps, with an organization and the OctoFX project from yesterday. * Browse to <https://dev.azure.com/> and login with details used yesterday. * Go to Azure Repos and import <https://github.com/OctopusSamples/OctoFX/> into Azure Repos. * Create Azure Pipeline for OctoFX. Your Azure Pipeline should look something like: ![It should look something like](/Images/azurepipelinesoctofx.png) * Create Azure Release pipeline Azure Release pipeline should look something like: ![Azure Release pipeline should look something like](/Images/azurereleasecreatereleasepipelinesoctofx.png) Azure Release Dev pipeline should look something like: ![Azure Dev Release pipeline should look something like](/Images/azurereleasedevpipelinesoctofx.png) Azure Release Test pipeline should look something like: ![Azure Test Release pipeline should look something like](/Images/azurereleasetestpipelinesoctofx.png) Azure Release Production pipeline should look something like: ![Azure Production Release pipeline should look something like](/Images/azurereleaseprodpipelinesoctofx.png) ### Packaging Applications There are a variety of tools you can use to package your applications, and as long as you can create supported packages, you can deploy your applications with Octopus Deploy. We've created the following tools to help you package your applications: * The [Octopus CLI](https://octopus.com/docs/packaging-applications/create-packages/octopus-cli) to create Zip Archives and NuGet packages for .NET Core apps and full .NET framework applications. * [OctoPack](https://octopus.com/docs/packaging-applications/create-packages/octopack) to create NuGet packages for ASP.NET apps (.NET Framework) and Windows Services (.NET Framework). * The [TeamCity](https://octopus.com/docs/packaging-applications/build-servers/teamcity) plugin. * The [Azure DevOps](https://octopus.com/docs/packaging-applications/build-servers/tfs-azure-devops/using-octopus-extension) plugin. In addition to these tools, you can use other tools to create your packages; for instance, you might use the following: * The built-in tools for [TeamCity](https://blog.jetbrains.com/teamcity/2010/02/artifact-packaging-with-teamcity/). * [NuGet.exe](https://docs.microsoft.com/en-us/nuget/tools/nuget-exe-cli-reference) to create NuGet packages. * [NuGet Package Explorer.](https://github.com/NuGetPackageExplorer/NuGetPackageExplorer) * [Grunt, gulp, or octojs](https://octopus.com/docs/deployment-examples/node-deployments/node-on-linux#create-and-push-node.js-project) for JavaScript apps. In OctoFX, we are using nuspec files, so our files will be generated for us and you won't need to use the package step from the Octopus Azure DevOps plugin. Read more about [OctoPack](https://octopus.com/docs/packaging-applications/create-packages/octopack). ### Full Deployment This section of the workshop will be led by a presentation, so please follow on-screen. ### Troubleshoot Full Deployment In this section, we will troubleshoot any issues you're seeing (more often than not, it's the SQL user having problems). * Check SQL Credentials. * Check any Transformations. * Check Azure Firewall. ## Thursday 12th March Afternoon Session ### Channels You can watch a webinar about channels and lifecycles on [YouTube](https://www.youtube.com/watch?v=y_cS_DL4CcY). As you deploy your projects, you can assign releases of projects to specific channels. This is useful when you want releases of a project to be treated differently depending on the criteria you've set. Without channels, you could find yourself duplicating projects to implement multiple release strategies. This would, of course, leave you trying to manage various duplicated projects. Channels let you use one project with multiple release strategies. Channels can be useful in the following scenarios: * Feature branches (or experimental branches) are deployed to test environments but not Production. * Early access versions of the software are released to members of your early access program. * Hot-fixes are deployed straight to Production and then deployed through the rest of your infrastructure after the fix has been released. When you are implementing a deployment process that uses channels, you can scope the following to specific channels: * Lifecycles * Steps * Variables * Tenants You can also define versioning rules per channel to ensure that only versions that meet specific criteria are deployed to particular channels. Read more about [channels](https://octopus.com/docs/deployment-process/channels). ### Lifecycles You can watch a webinar about channels and lifecycles on [YouTube](https://www.youtube.com/watch?v=y_cS_DL4CcY) Lifecycles give you control over the way releases of your software are promoted between your environments. Lifecycles enable several advanced deployment workflow features: * Control the order of promotion: for example, to prevent a release being deployed to Production if it hasn't been deployed to staging. * Automate deployment to specific environments: for example, automatically deploy to test as soon as a release is created. * Retention policies: specify the number of releases to keep depending on how far they have progressed through the lifecycle. Phases define lifecycles. A lifecycle can have one or many phases. * Phases occur in order. One phase must have a complete, successful deployment before the release is deployed to the next phase. * Phases have one or more environments. * Environments in a phase can be defined as automatic deployment environments or manual deployment environments. * Phases can have a set number of environments that must be released before the next phase is available for deployment. You can specify multiple lifecycles to control which projects are deployed to which environments. Lifecycles are managed from the library page by navigating to Library ➜ Lifecycles: Lifecycles are a crucial component of channels that give you even greater control over how your software is deployed. Channels let you use multiple lifecycles for a project and then automatically deploy to specific channels, using the defined lifecycle, based on the version of the software being deployed. You can read more [lifecycles](https://octopus.com/docs/deployment-process/lifecycles) ### Multi-Tenancy You can watch a webinar about Multi-Tenanted deployments with Octopus Deploy on [YouTube](https://www.youtube.com/watch?v=qsHSosC3GmA). This section describes how to use Octopus to manage deployments of your applications to multiple end-customers. Consider the following scenario: NameBadge makes HR software for large corporate customers. They provide the software as a SaaS offering to their customers and host the website and associated services for them. Due to how the application is structured, for each customer, they deploy: * A different SQL database. * A copy of an ASP.NET website. * A copy of a Windows Service. The critical issue in this scenario is that the same components need to be deployed multiple times; once for each end-customer. 1. Deploy multiple instances of your project into the same [environment](/docs/infrastructure/environments/index.md); * Tenant-per-customer * Tenant-per-tester * Tenant-per-feature/tenant-per-branch * Tenant-per-geographical-region * Tenant-per-datacenter 2. Easily manage unique configuration settings using variables defined on the tenant. 3. Promote releases to your tenants using safe customer-aware lifecycles, potentially through multiple environments: * Tenant-specific UAT and Production environments. 4. Tailor the deployment process of your projects per-tenant as necessary. 5. Implement dedicated or shared hosting models for your tenants. 6. Employ tenant-aware security for managing tenants and deploying projects, including 3rd-party self-service sign in. 7. Implement early access or pre-release test programs incorporating 1st-party or 3rd-party testers. 8. Easily scale to large numbers of tenants using tags to manage tenants as groups instead of individuals. 9. Easily implement simple multi-tenant deployment scenarios and scale to support complex scenarios as your needs require. Read more about [multi-tenancy](https://octopus.com/docs/deployment-patterns/multi-tenant-deployments). ### Runbooks You can watch a full webinar on Runbooks on [YouTube](https://www.youtube.com/watch?v=aK1-pFe5dYM). A deployment is only one phase in the life of an application. There are typically many other tasks that are performed to keep an application operating. A large part of DevOps is running operations separate from deploying applications, and this is where runbooks helps. Runbooks are used to automate routine maintenance and emergency operations tasks like infrastructure provisioning, database management, and website failover and restoration. Read more about [Runbooks](https://octopus.com/docs/operations-runbooks). ### Spaces You can watch a webinar about Spaces on [YouTube](https://youtu.be/EJgM0r58VDc?t=278) With Spaces, you can partition your Octopus Deploy Server so that each of your teams can only access the projects, environments, and infrastructure they work with from the spaces they are members of. Users can be members of multiple teams and have access to various spaces, but the entities and infrastructure they work with will only be available in the space it is assigned to. Read more about [Spaces](https://octopus.com/docs/administration/spaces) ### Workers You can watch a webinar about Workers on [YouTube](https://youtu.be/EJgM0r58VDc?t=1697) Workers are machines that can execute tasks that don't need to be run on the Octopus Server or individual deployment targets. You can manage your Workers by navigating to Infrastructure ➜ Worker Pools in the Octopus Web Portal. Workers are useful for the following scenarios: * Publishing to Azure websites. * Deploying AWS CloudFormation templates. * Deploying to AWS Elastic Beanstalk. * Uploading files to Amazon S3. * Backing up databases. * Performing database schema migrations * Configuring load balancers. Read more about [Workers](https://octopus.com/docs/infrastructure/workers). ### Common Deployment Patterns #### Blue/Green Blue-green deployments are a pattern that reduces downtime during production deployments by having two production environments ("blue" and "green"). > One of the challenges with automating deployment is the cut-over itself, taking software from the final stage of testing to live Production. You usually need to do this quickly to minimize downtime. The **blue-green deployment** approach does this by ensuring you have two production environments, as identical as possible. At any time one of them, let's say blue for the example, is live. As you prepare a new release of your software, you do your final stage of testing in the green environment. Once the software is working in the green environment, you switch the router so that all incoming requests go to the green environment - the blue one is now idle. > > * [Martin Fowler](http://martinfowler.com/bliki/BlueGreenDeployment.html) As well as reducing downtime, Blue/Green can be a powerful way to use extra hardware compared to having a dedicated staging environment: * Staging: When blue is active, green becomes the staging environment for the next deployment. * Rollback: We deploy to blue and make it active. Then a problem is discovered. Since green still runs the old code, we can roll back easily. * Disaster recovery: After deploying to blue and we're satisfied that it is stable, we can deploy the new release to green too. This gives us a standby environment ready in case of disaster. Read more about [blue/green deployments](https://octopus.com/docs/deployment-patterns/blue-green-deployments). #### Red/Black When deploying new versions of a centralized application like a web service, there is a strategy you can use to direct production traffic to the latest version only after it has been successfully deployed and optionally tested. This strategy goes by the name blue/green or red/black, with each color representing a copy of the target environment. Traffic is routed to one color or the other (or potentially both in a canary deployment or during A/B testing, but that's a story for another time). Having two environments running side by side hosting different versions of an application means traffic can be switched over, and back again if an issue is found, with little to no downtime. So why is this strategy referred to as both green/blue and red/black? Do these colors imply technical differences? StackOverflow says Our first stop is to StackOverflow, where we find the question [What's the difference between Red/Black deployment and Blue/Green Deployment?](https://stackoverflow.com/questions/45259589/whats-the-difference-between-red-black-deployment-and-blue-green-deployment). The highest voted answer indicates that there is indeed a difference between these two terms: > in blue-green deployment, both versions may be getting requests at the same time temporarily, while in red-black only one of the versions is getting traffic at any point in time The answer then goes on to say that: > But red-black deployment is a newer term being used by Netflix, Istio, and other frameworks/platforms that support container orchestration I've frequently seen the term red/black being attributed to tools created by Netflix and container platforms in general, so let's go to their documentation to see how they define these strategies. Read more about [Red/Black(<https://octopus.com/blog/blue-green-red-black).> #### Canary Deployments Canary deployments are a pattern for rolling out releases to a subset of users or servers. The idea is first to deploy the change to a small subset of servers, test it, and then roll the change out to the rest of the servers. The canary deployment serves as an early warning indicator with less impact on downtime; if the canary deployment fails, the rest of the servers aren't impacted. > Canaries were once regularly used in [coal mining](http://en.wikipedia.org/wiki/Coal_mining "Coal mining") as an early warning system. [Toxic](http://en.wikipedia.org/wiki/Toxic "Toxic") [gases](http://en.wikipedia.org/wiki/Gas "Gas") such as [carbon monoxide](http://en.wikipedia.org/wiki/Carbon_monoxide "Carbon monoxide"), [methane](http://en.wikipedia.org/wiki/Methane "Methane") or [carbon dioxide](http://en.wikipedia.org/wiki/Carbon_dioxide "Carbon dioxide") in the mine would kill the bird before affecting the miners. Signs of distress from the bird indicated to the miners that conditions were unsafe. The use of miners' canaries in [British](http://en.wikipedia.org/wiki/Great_Britain "Great Britain") mines was phased out in 1987. > > * [Wikipedia](http://en.wikipedia.org/wiki/Domestic_Canary#Miner.27s_canary) The necessary steps of a canary deployment are: 1. Deploy to one or more canary servers. 2. Test, or wait until satisfied. 3. Deploy to the remaining servers. The test phase of the canary deployment can work in many ways. You could run some automated tests, perform manual testing yourself, or even leave the server live and wait to see if end-users encounter problems. All three of these approaches might be used. Depending on how you plan to test, you might decide to remove the canary server from the production load balancer and return it only when rolling out the change to the rest of the servers. :::hint **Similar to staging** Canary deployments are similar to using a staging environment. The difference is that staging environments are usually dedicated to the task; a staging web server doesn't become a production server. By contrast, in a canary deployment, the canary server remains part of the production fleet when the deployment is complete. Canary deployments may be worth considering if you do not have the resources for a dedicated staging environment. ::: Read more about [Canary Deployments](https://octopus.com/docs/deployment-patterns/canary-deployments). ### Octopus & Azure DevOps Administration * [Auditing](https://octopus.com/docs/administration/managing-users-and-teams/auditing). * [External Authentication Providers](https://octopus.com/docs/administration/authentication). * [Users/Teams/Permissions](https://octopus.com/docs/administration/managing-users-and-teams). * [Upgrading Octopus](https://octopus.com/docs/administration/upgrading). * [Retention Policies](https://octopus.com/docs/administration/retention-policies). * [Cloud vs On-Premise](https://octopus.com/docs/octopus-cloud). ## Wrap-up & Feedback, and Resources Thanks for spending the last two days with us. We hope you enjoyed the workshop and learned a lot! ### Recommendations * Destroy your infrastructure, as this will continue charging you. * Keep Azure DevOps, as there should be no cost. * Octopus Cloud will remain free for as long as you have no more than ten targets. ### Octopus Resources * For more information on Octopus, check out the [Optimum Setup Guide](https://github.com/OctopusDeploy/OptimumSetupBook). * [Octopus documentation](http://octopus.com/docs/). * [Octopus Guides](https://octopus.com/docs/guides) where you can select your own CI/CD pipeline to generate a video, documentation, and a TestDrive VM that walks you through a complete CI/CD setup. * [Octopus YouTube channel](http://octopus.com/videos). * [Octopus Events Page](https://octopus.com/events) for upcoming webinars & events, and for previously recorded webinars. * [Sample Octopus instance](http://samples.octopus.app/). * [Octopus Jenkins sample](https://jenkinssample.octopus.com/). * [Octopus TeamCity sample](https://teamcitysample.octopus.com/). * [Azure DevOps OctoFX sample](https://dev.azure.com/octopussamples/OctoFX). * [Octopus Twitter](https://twitter.com/OctopusDeploy). ### Azure DevOps Resources * [Microsoft Learn](https://docs.microsoft.com/en-us/learn/) has some great resources for Azure DevOps & Azure. * [Azure Quickstart Templates](https://azure.microsoft.com/en-gb/resources/templates/) and [Github](https://github.com/Azure/azure-quickstart-templates) are great resources for Quickstart ARM Templates. * Azure DevOps certification [exam detail page](https://docs.microsoft.com/en-us/learn/certifications/azure-devops). * Azure Administrator exam details on this [page](https://docs.microsoft.com/en-gb/learn/certifications/azure-administrator). * [Azure Docs](https://docs.microsoft.com/en-gb/azure/). * [Azure DevOps Docs](https://docs.microsoft.com/en-gb/azure/devops/). * [Channel 9 video content](https://channel9.msdn.com/). Please take 5 minutes and help us by filling out this anonymous [feedback form](https://forms.gle/tXi3Vn9n4kPKT5ai7).
C#
UTF-8
682
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using RepositoryPattern.Models.CoreLayer; namespace RepositoryPattern.Models.PersistenceLayer { public class StudentRepository : Repository<Student>, IStudentRepository { public StudentRepository(AppContext context) :base(context) { } public IEnumerable<Student> GetStudentsByDesendingOrder() { return AppContext.Students.OrderByDescending(s => s.Id).ToList(); } public AppContext AppContext { get { return Context as AppContext; } // Context is inherited from Repository class } } }
Python
UTF-8
2,607
2.765625
3
[]
no_license
import numpy as np import cv2 # print(cv2.__version__) # x = int(input("Number of ryws:")) class Minerator: def __init__(self, x = 5): self.x = x self.step = int(512/(x+1)) self.img = np.full((512,512,3), 255, dtype=np.uint8) self.font = cv2.FONT_HERSHEY_SIMPLEX def draw_cells(self): color = (0,0,255) #cv2.putText(img,'0',(int(512 / x + 10), int(512 / x - 10)), font, 3,(0,0,0),2,cv2.LINE_AA) for i in range(1, self.x+1): coord = self.step*i cv2.line(self.img,(0,coord),(511,coord),color,1) cv2.line(self.img,(self.step * i,0),(self.step * i, 511),color,1) cv2.putText(self.img,str(i),(int(50 / self.x) + coord, int(512 / (self.x+1) - int(50 / self.x))), self.font, 10 / self.x,(0,0,0),2,cv2.LINE_AA) cv2.putText(self.img,str(i),(int(50 / self.x), int(512 / (self.x+1) - int(50 / self.x)) + coord), self.font, 10 / self.x,(0,0,0),2,cv2.LINE_AA) def draw_mask(self,mask): color = (200,200,200) for i in range (len(mask)): for j in range(len(mask[0])): if mask[i][j] == 0: cv2.rectangle(self.img, (self.step * (j+1), self.step * (i+1)), (self.step * (j+2), self.step * (i+2)), color, thickness=-1) if type(mask[i][j]) is int and 0 < mask[i][j] < 9: cv2.rectangle(self.img, (self.step * (j+1), self.step * (i+1)), (self.step * (j+2), self.step * (i+2)), color, thickness=-1) cv2.putText(self.img,str(mask[i][j]),(int(50 / self.x) + self.step * (j+1), int(512 / (self.x+1) - int(50 / self.x)) + self.step * (i+1)), self.font, 10 / self.x,(0,0,0),2,cv2.LINE_AA) if type(mask[i][j]) is int and mask[i][j] == 9: cv2.rectangle(self.img, (self.step * (j+1), self.step * (i+1)), (self.step * (j+2), self.step * (i+2)), color, thickness=-1) cv2.putText(self.img,'*',(int(50 / self.x) + self.step * (j+1), int(512 / (self.x+1) - int(50 / self.x)) + self.step * (i+1)), self.font, 10 / self.x,(0,0,0),2,cv2.LINE_AA) def get_image(self, mask): self.img = np.full((512,512,3), 255, dtype=np.uint8) self.x = len(mask) self.step = int(512/(self.x+1)) self.draw_mask(mask) self.draw_cells() return self.img # mask = [[0,0,0,0,0], # [0,0,0,'#',0], # [0,0,2,0,0], # [0,0,0,0,0], # [0,0,0,4,0]] # imager = Minerator() # cv2.imshow('Dimas', imager.get_image(mask)) # cv2.waitKey(0) # cv2.destroyAllWindows()
Java
UTF-8
584
2.09375
2
[]
no_license
package com.hypo.test; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.hypo.array.GasStation_187; public class GasStation_187Test { GasStation_187 t187; @Before public void setUp() throws Exception { t187 = new GasStation_187(); } @After public void tearDown() throws Exception { } @Test public void testCanCompleteCircuit() { int[] gas1 = {1, 1, 3, 1}; int[] cost1 = {2, 2, 1, 1}; int expt1 = 2; org.junit.Assert.assertEquals("Wrong1", expt1, t187.canCompleteCircuit(gas1,cost1)); } }
Markdown
UTF-8
6,143
3.125
3
[]
no_license
--- title: "Trabajando con Pods" permalink: /cursos/osv4_k8s/modulo4/pods.html --- ## Creación de un proyecto Vamos a trabajar en CRC con el usuario `developer`: oc login -u developer -p developer https://api.crc.testing:6443 ... Using project "developer". ## Creación de Pods OpenShift configura por defecto una política de seguridad que sólo nos permite ejecutar contenedores no privilegiados, es decir, donde no se ejecuten procesos o acciones por el usuario con privilegio `root` (por ejemplo, no utilizan puertos no privilegiados, puertos menores a 1024, o no ejecuta operaciones con el usuario `root`). Por esta razón, la mayoría de las imágenes que encontramos en el registro Docker Hub no funcionarán en OpenShift. Es por ello que es necesario usar imágenes de contenedores no privilegiados, por ejemplo creadas con imágenes constructoras (images builder) del propio OpenShift. En nuestro caso, en estos primeros ejemplos, vamos a usar imágenes generadas por la empresa Bitnami, que ya están preparadas para su ejecución en OpenShift. De forma **imperativa** podríamos crear un Pod, ejecutando: oc run pod-nginx --image=bitnami/nginx Pero, normalmente necesitamos indicar más parámetros en la definición de los recursos. Además, sería deseable crear el Pod de forma **declarativa**, es decir indicando el estado del recurso que queremos obtener. Para ello, definiremos el recurso, en nuestro caso el Pod, en un fichero de texto en formato **YAML**. Por ejemplo, podemos tener el fichero `pod.yaml`: ```yaml apiVersion: v1 kind: Pod metadata: name: pod2-nginx labels: app: nginx service: web spec: containers: - image: bitnami/nginx name: contenedor-nginx imagePullPolicy: Always ``` Veamos cada uno de los parámetros que hemos definido: * `apiVersion: v1`: La versión de la API que vamos a usar. * `kind: Pod`: La clase de recurso que estamos definiendo. * `metadata`: Información que nos permite identificar unívocamente el recurso: * `name`: Nombre del pod. * `labels`: Las [Labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) nos permiten etiquetar los recursos de OpenShift (por ejemplo un pod) con información del tipo clave/valor. * `spec`: Definimos las características del recurso. En el caso de un Pod indicamos los contenedores que van a formar el Pod (sección `containers`), en este caso sólo uno. * `image`: La imagen desde la que se va a crear el contenedor * `name`: Nombre del contenedor. * `imagePullPolicy`: Si creamos un contenedor, necesitamos tener descargada en un registro interno la imagen. Existe una política de descarga de estas imágenes: * La política por defecto es `IfNotPresent`, que se baja la imagen si no está en el registro interno. * Si queremos forzar la descarga desde el repositorio externo, indicaremos el valor `Always`. * Si estamos seguro que la imagen esta en el registro interno, y no queremos bajar la imagen del registro externo, indicamos el valor `Never`. Ahora para crear el Pod a partir del fichero YAML, podemos usar dos subcomandos: * `create`: **Configuración imperativa de objetos**, creamos el objeto (en nuestro caso el pod) pero si necesitamos modificarlo tendremos que eliminarlo y volver a crearlo después de modificar el fichero de definición. oc create -f pod.yaml * `apply`: **Configuración declarativa de objetos**, el fichero indica el estado del recurso que queremos tener. Al aplicar los cambios, se realizarán todas las acciones necesarias para llegar al estado indicado. Por ejemplo, si no existe el objeto se creará, pero si existe el objeto, se modificará. oc apply -f pod.yaml ## Otras operaciones con Pods Podemos ver el estado en el que se encuentra y si está o no listo: oc get pod **Nota:** Sería equivalente usar po, pod o pods. Si queremos ver más información sobre los Pods, como por ejemplo, saber en qué nodo del cluster se está ejecutando: oc get pod -o wide Para obtener información más detallada del Pod: oc describe pod pod-nginx Podríamos editar el Pod y ver todos los atributos que definen el objeto, la mayoría de ellos con valores asignados automáticamente por el propio OpenShift y podremos actualizar ciertos valores: oc edit pod pod-nginx Normalmente no se interactúa directamente con el Pod a través de una shell, pero sí se obtienen directamente los logs al igual que se hace en docker: oc logs pod/pod-nginx En el caso poco habitual de que queramos ejecutar alguna orden adicional en el Pod, podemos utilizar el comando `exec`, por ejemplo, en el caso particular de que queremos abrir una shell de forma interactiva: oc exec -it pod-nginx -- /bin/bash Otra manera de acceder al pod: oc rsh pod-nginx Podemos acceder a la aplicación, redirigiendo un puerto de localhost al puerto de la aplicación: oc port-forward pod-nginx 8080:8080 Y accedemos al servidor web en la url http://localhost:8080. **NOTA**: Esta no es la forma con la que accedemos a las aplicaciones en OpenShift. Para el acceso a las aplicaciones usaremos un recurso llamado Service. Con la anterior instrucción lo que estamos haciendo es una redirección desde localhost el puerto 8080 al puerto 8080 del Pod y es útil para pequeñas pruebas de funcionamiento, nunca para acceso real a un servicio. Para obtener las etiquetas de los Pods que hemos creado: oc get pod --show-labels Las etiquetas las hemos definido en la sección metadata del fichero YAML, pero también podemos añadirlos a los Pods ya creados: oc label pod pod-nginx service=web --overwrite=true Las etiquetas son muy útiles, ya que permiten seleccionar un recurso determinado (en el clúster puede haber cientos o miles de objetos). Por ejemplo para visualizar los Pods que tienen una etiqueta con un determinado valor: oc get pod -l service=web También podemos visualizar los valores de las etiquetas como una nueva columna: oc get pod -Lservice Y por último, eliminamos el Pod mediante: oc delete pod pod-nginx
Python
UTF-8
342
3.5
4
[ "MIT" ]
permissive
hex = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] num0 = '' num1 = '' pair = '' line = '' body = '' for i in hex: for j in hex: num0 = r'"\\x' + i + j + r'"' num1 = r'"\x' + i + j + r'"' pair = num0 + ' : ' + num1 line = pair + "," + '\n' body += line print(body)
SQL
UTF-8
530
3.078125
3
[]
no_license
CREATE TABLE phenix.application_role_features ( arfe_arol_id NUMBER(15) NOT NULL, arfe_afea_id NUMBER(15) NOT NULL, arfe_creation_date DATE DEFAULT sysdate NOT NULL, arfe_modification_date DATE DEFAULT sysdate NOT NULL, CONSTRAINT arfe_pk PRIMARY KEY (arfe_arol_id,arfe_afea_id), CONSTRAINT arfe_afea_fk FOREIGN KEY (arfe_afea_id) REFERENCES phenix.application_features (afea_id) ON DELETE CASCADE, CONSTRAINT arfe_arol_fk FOREIGN KEY (arfe_arol_id) REFERENCES phenix.application_roles (arol_id) ON DELETE CASCADE );
JavaScript
UTF-8
1,531
4.03125
4
[ "MIT" ]
permissive
'use strict'; // 实时:new Date() let now = new Date(); console.log(now); // Wed Oct 23 2019 16:24:20 GMT+0800 (GMT+08:00) // 微秒,表示从 1970 年 1 月 1 日开始经过的描述:new Date(milliseconds) let time = new Date(1000); console.log(time); // Thu Jan 01 1970 08:00:01 GMT+0800 (GMT+08:00) // 日期字符串: new Date("yy-mm-dd") time = new Date('2017-01-26'); console.log(time); // Thu Jan 26 2017 08:00:00 GMT+0800 (GMT+08:00) time = new Date('adsfa'); console.log(time); // Invalid Date // new Date(year, month, date, hours, minutes, seconds, ms) time = new Date(1999, 2, 31, 0, 0, 0, 314); // 年份必须是4位;月份从 0 计数,2 表示三月,范围是 0-11 ;日期默认 1 日;之后单位默认为 0;可以精确到毫秒 console.log(time); // Wed Mar 31 1999 00:00:00.314 GMT+0800 (GMT+08:00) // 参数超出范围会自动累加跟进 time = new Date(2013, 0, 32); // 一月 32 号? console.log(time); // Fri Feb 01 2013 00:00:00 GMT+0800 (GMT+08:00),自动更正为二月 1 号 // 仅供了解 time = new Date(0); console.log(time); time = new Date(0, 0, 0); console.log(time); // Sun Dec 31 1899 00:00:00 GMT+0805 (GMT+08:00) // 类型转换 time = new Date(); console.log(+time); // 1571906220798,转换成毫秒时间戳,相当于 time.getTime() // 相减可得时间差,单位为毫秒 let timeDiff = new Date() - new Date(0); console.log(timeDiff); // 1571906210180,毫秒时间戳 time = Date.now(); console.log(time); // == time.getTime(),毫秒时间戳
C++
UTF-8
5,924
2.859375
3
[]
no_license
/* * ColorScale.cpp * * Created by mooglwy on 31/10/10. * * This software is provided 'as-is', without any express or * implied warranty. In no event will the authors be held * liable for any damages arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute * it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; * you must not claim that you wrote the original software. * If you use this software in a product, an acknowledgment * in the product documentation would be appreciated but * is not required. * * 2. Altered source versions must be plainly marked as such, * and must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any * source distribution. * */ #include "ColorScale.h" #include <cmath> #include <algorithm> const double PI = 3.1415926535; double linearInterpolation(double v1, double v2, double mu) { return v1*(1-mu)+v2*mu; } double interpolateCosinus(double y1, double y2, double mu) { double mu2; mu2 = (1-cos(mu*PI))/2; return y1*(1-mu2)+y2*mu2; } sf::Color GradientLinear(sf::Color* colorTab,int size,const sf::Vector2f& start,const sf::Vector2f& end,int x,int y) { sf::Vector2f dir = end-start; sf::Vector2f pix = sf::Vector2f(x,y)-start; double dotProduct = pix.x*dir.x+pix.y*dir.y; dotProduct *= (size-1)/(dir.x*dir.x+dir.y*dir.y); if((int)dotProduct < 0.0 ) return colorTab[0]; if((int)dotProduct > (size-1) ) return colorTab[size-1]; return colorTab[(int)dotProduct]; } sf::Color GradientCircle(sf::Color* colorTab,int size,const sf::Vector2f& start,const sf::Vector2f& end,int x,int y) { sf::Vector2f v_radius = end-start; double radius = std::sqrt(v_radius.x*v_radius.x+v_radius.y*v_radius.y); sf::Vector2f pix = sf::Vector2f(x,y)-start; double dist = std::sqrt(pix.x*pix.x+pix.y*pix.y); dist *= (size-1)/radius; if((int)dist < 0.0 ) return colorTab[0]; if((int)dist > (size-1) ) return colorTab[size-1]; return colorTab[(int)dist]; } sf::Color GradientRadial(sf::Color* colorTab,int size,const sf::Vector2f& start,const sf::Vector2f& end,int x,int y) { sf::Vector2f base = end-start; base /= (float)std::sqrt(base.x*base.x+base.y*base.y); sf::Vector2f pix = sf::Vector2f(x,y)-start; pix /= (float)std::sqrt(pix.x*pix.x+pix.y*pix.y); double angle = std::acos(pix.x*base.x+pix.y*base.y); double aSin = pix.x*base.y-pix.y*base.x; if( aSin < 0) angle = 2*PI-angle; angle *= (size-1)/(2*PI); if((int)angle < 0.0 ) return colorTab[0]; if((int)angle > (size-1) ) return colorTab[size-1]; return colorTab[(int)angle]; } sf::Color GradientReflex(sf::Color* colorTab,int size,const sf::Vector2f& start,const sf::Vector2f& end,int x,int y) { sf::Vector2f dir = end-start; sf::Vector2f pix = sf::Vector2f(x,y)-start; double dotProduct = pix.x*dir.x+pix.y*dir.y; dotProduct *= (size-1)/(dir.x*dir.x+dir.y*dir.y); dotProduct = std::abs(dotProduct); if((int)dotProduct < 0.0 ) return colorTab[0]; if((int)dotProduct > (size-1) ) return colorTab[size-1]; return colorTab[(int)dotProduct]; } ColorScale::ColorScale() { } bool ColorScale::insert(double position, sf::Color color) { std::pair< ColorScale::iterator,bool > ret = std::map<double,sf::Color>::insert(std::make_pair(position,color)); return ret.second; } #define ABS(a) (std::max(a, 0)) void ColorScale::fillTab(sf::Color* colorTab, int size,InterpolationFunction::InterpolationFunction function) const { ColorScale::const_iterator start = std::map<double,sf::Color>::begin(); ColorScale::const_iterator last = std::map<double,sf::Color>::end(); last--; double pos = 0.0; double distance = last->first - start->first; ColorScale::const_iterator it = start; double(*pFunction)(double,double,double); switch (function) { case InterpolationFunction::Cosinus: pFunction = interpolateCosinus; break; case InterpolationFunction::Linear : pFunction = linearInterpolation; break; default: pFunction = interpolateCosinus; break; } while(it!=last) { sf::Color startColor = it->second; double startPos = it->first; it++; sf::Color endColor = it->second; double endPos = it->first; double nb_color = ((endPos-startPos)*(double)size/distance); for(int i = (int)pos;i<=(int)(pos+nb_color);i++) { colorTab[i].r = (unsigned char)pFunction(startColor.r,endColor.r,ABS((double)i-pos)/(nb_color-1.0)); colorTab[i].g = (unsigned char)pFunction(startColor.g,endColor.g,ABS((double)i-pos)/(nb_color-1.0)); colorTab[i].b = (unsigned char)pFunction(startColor.b,endColor.b,ABS((double)i-pos)/(nb_color-1.0)); colorTab[i].a = (unsigned char)pFunction(startColor.a,endColor.a,ABS((double)i-pos)/(nb_color-1.0)); } pos+=nb_color; } } #undef ABS void ColorScale::draw(sf::Image& img,const sf::Vector2f& start,const sf::Vector2f& end,GradientStyle::GradientStyle style, int size) const { sf::Color (*pFunction)(sf::Color*,int,const sf::Vector2f&,const sf::Vector2f&,int,int); sf::Color* tab =new sf::Color[size]; fillTab(tab,size); switch (style) { case GradientStyle::Linear : pFunction = GradientLinear; break; case GradientStyle::Circle : pFunction = GradientCircle; break; case GradientStyle::Radial : pFunction = GradientRadial; break; case GradientStyle::Reflex : pFunction = GradientReflex; break; default: pFunction = GradientLinear; break; } for(int i=0;i<img.GetWidth();i++) { for(int j=0;j<img.GetHeight();j++) { img.SetPixel(i,j,pFunction(tab,size,start,end,i,j)); } } delete[] tab; }
C
UTF-8
2,653
3.9375
4
[ "MIT" ]
permissive
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "list.h" // Creates a new list with a given initial capacity struct List *initList(int initialSize) { List *list = malloc(sizeof(List)); if (list == NULL) { printf("\nFAILED TO ALLOCATE LIST MEMORY!\n\n"); exit(EXIT_FAILURE); } list -> size = initialSize; list -> items = 0; list -> data = malloc(sizeof(void*) * initialSize); if (list -> data == NULL) { printf("\nFAILED TO ALLOCATE LIST DATA MEMORY!\n\n"); exit(EXIT_FAILURE); } return list; } // Returns an item of the given index from the given list void *getFromList(List *list, int index) { if (index >= list -> items) { return NULL; } return list -> data[index]; } // Add an item to the given list void addToList(List *list, void *item) { if (list -> items == list -> size) { void **newData = malloc(sizeof(void*) * list -> size * 2); if (newData == NULL) { printf("\nFAILED TO REALLOCATE LIST DATA MEMORY!\n\n"); exit(EXIT_FAILURE); } memcpy(newData, list -> data, sizeof(void*) * list -> size); free(list -> data); list -> data = newData; list -> size *= 2; } list -> data[list -> items] = item; list -> items += 1; } // Removes given item (once or all occurrences) from the given list void removeFromList(List *list, void *item, int removeAll) { int i = 0; for (; i < list -> items; i++) { if (list -> data[i] == item) { removeFromListByIndex(list, i--); if (!removeAll) { return; } } } } // Removes an item of the given index from the given list void removeFromListByIndex(List *list, int index) { if (index >= list -> items) { return; } int i = index; for (; i < list -> items - 1; i++) { list -> data[i] = list -> data[i + 1]; } list -> items -= 1; } // Sets an item under the given index in the given list void setInListByIndex(List *list, int index, void *item) { if (index >= list -> items) { return; } list -> data[index] = item; } // Clears the given list, could also free the items memory void clearList(List *list, int freeData) { if (freeData) { int i = 0; for (; i < list -> items; i++) { free((list -> data)[i]); } } list -> items = 0; } // Frees the given list memory, could also free the items memory void freeList(List *list, int freeData) { if (freeData) { clearList(list, 1); } free(list); }
C#
UTF-8
897
3.3125
3
[]
no_license
using System; namespace toy_robot { class Program { static void Main(string[] args) { Console.WriteLine("**Toy Robot**"); Command command = new Command(new Robot()); while (true) { Console.WriteLine("Please Enter A Command:"); try{ string result = command.Execute(Console.ReadLine()); if(result != null) { Console.ForegroundColor = ConsoleColor.Green; Console.Write(result + "\n"); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); } Console.ResetColor(); } } } }
Java
UTF-8
15,577
3.09375
3
[]
permissive
package ch.jalu.typeresolver.typeimpl; import ch.jalu.typeresolver.CommonTypeUtils; import ch.jalu.typeresolver.TypeInfo; import javax.annotation.Nullable; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.function.Supplier; /** * Builder to create parameterized types programmatically. * <p> * Example:<pre>{@code * ParameterizedType pt = newTypeFromClass(Optional.class) * .withTypeArg(0, String.class) * .build(); * // pt = Optional<String> * }</pre> * You can also start with the existing values of a parameterized type using the constructor * {@link ParameterizedTypeBuilder#ParameterizedTypeBuilder(ParameterizedType)}. */ public class ParameterizedTypeBuilder { private final Class<?> rawType; @Nullable private final Type ownerType; private final TypeVariable<?>[] typeParameters; private final Type[] newTypeArguments; /** * Creates a builder with the given parameterized type as initial values. * * @param parameterizedType the parameterized type to start the builder off with */ public ParameterizedTypeBuilder(ParameterizedType parameterizedType) { this.rawType = CommonTypeUtils.getRawType(parameterizedType); this.ownerType = parameterizedType.getOwnerType(); this.typeParameters = rawType.getTypeParameters(); this.newTypeArguments = parameterizedType.getActualTypeArguments().clone(); } private ParameterizedTypeBuilder(Class<?> rawType) { TypeVariable<?>[] typeParams = rawType.getTypeParameters(); if (typeParams.length == 0) { throw new IllegalArgumentException("Class '" + rawType + "' has no type arguments"); } this.rawType = rawType; this.ownerType = createOwnerType(rawType); this.typeParameters = typeParams; this.newTypeArguments = new Type[typeParameters.length]; } /** * Creates a builder with the given Class as its base type. * * @param clazz the raw type of the parameterized type that will be created * @return new builder with the given class as the raw type * @throws IllegalArgumentException if the class has no type parameters */ public static ParameterizedTypeBuilder parameterizedTypeBuilder(Class<?> clazz) { return new ParameterizedTypeBuilder(clazz); } /** * Creates a new parameterized type representing the given Collection type and the provided type argument. * Throws an exception if the given base type does not have at least one type parameter. * <p> * Example: * <pre>{@code newCollectionType(ArrayList.class, Double.class) // ArrayList<Double>}</pre> * <p> * If you know the base type and argument at compile time, consider using * {@link ch.jalu.typeresolver.reference.TypeReference TypeReference} instead:<br> * {@code Type type = new TypeReference<ArrayList<String>>(){ }.getType()}. * * @param baseType the collection type to use as raw type * @param typeArgument the type argument of the collection * @return parameterized type * @throws IllegalArgumentException if the base type does not have at least one type parameter */ public static ParameterizedTypeImpl newCollectionType(Class<? extends Collection> baseType, @Nullable Type typeArgument) { return new ParameterizedTypeBuilder(baseType) .withTypeArg(0, typeArgument) .build(); } /** * Creates a new parameterized type representing the given Map type and the provided key and value arguments. * Throws an exception if the given map type does not have at least two type parameters. * <p> * Example: * <pre>{@code newMapType(HashMap.class, String.class, Double.class) // Map<String, Double>}</pre> * <p> * If you know the base type and arguments at compile time, consider using * {@link ch.jalu.typeresolver.reference.TypeReference TypeReference} instead:<br> * {@code Type type = new TypeReference<HashMap<String, Double>>(){ }.getType()}. * * @param baseType the map implementation type to use as raw type * @param keyType the key type argument * @param valueType the value type argument * @return parameterized type * @throws IllegalArgumentException if the base type does not have at least two type parameters */ public static ParameterizedTypeImpl newMapType(Class<? extends Map> baseType, @Nullable Type keyType, @Nullable Type valueType) { return new ParameterizedTypeBuilder(baseType) .withTypeArg(0, keyType) .withTypeArg(1, valueType) .build(); } /** * Sets the type argument to the given index. Equivalent to {@link #withTypeArg(int, Type)}. * * @param typeParameterIndex the index of the parameter to set (0-based) * @param typeInfo type info whose type should be set as argument * @return this builder */ public ParameterizedTypeBuilder withTypeArg(int typeParameterIndex, TypeInfo typeInfo) { return withTypeArg(typeParameterIndex, typeInfo.getType()); } /** * Sets the type parameter at the given index to the provided type. Null can be provided to reset the * type parameter at the given index back to the class's type variable. Throws an exception if the parameter * index is invalid. * <p> * Example: <pre>{@code newTypeFromClass(Optional.class).withTypeArg(0, Double.class).build();}</pre> * * @param typeParameterIndex the index of the parameter to set (0-based) * @param type the type to set (or null to reset to the type variable) * @return this builder * @throws IllegalArgumentException if the type parameter index is out of bounds */ public ParameterizedTypeBuilder withTypeArg(int typeParameterIndex, @Nullable Type type) { if (typeParameterIndex < 0 || typeParameterIndex >= typeParameters.length) { throw new IllegalArgumentException("Type parameter index " + typeParameterIndex + " is out of bounds for " + rawType); } updateNewTypeArgumentEntry(typeParameterIndex, type); return this; } /** * Sets the type argument for the parameter with the given name. Equivalent to {@link #withTypeArg(int, Type)}. * * @param typeParameterName the name of the type parameter to set * @param typeInfo type info whose type should be set as argument * @return this builder * @throws IllegalArgumentException if the raw type does not have a type parameter matching the name */ public ParameterizedTypeBuilder withTypeArg(String typeParameterName, TypeInfo typeInfo) { return withTypeArg(typeParameterName, typeInfo.getType()); } /** * Sets the type parameter with the given name to the provided type. Null can be provided to reset the * type parameter back to the class's type variable. Throws an exception if the parameter name could not be found. * <p> * Example: <pre>{@code newTypeFromClass(Optional.class).withTypeArg("T", Double.class).build();}</pre> * * @param typeParameterName the name of the type parameter to set * @param type the type to set (or null to reset to the type variable) * @return this builder * @throws IllegalArgumentException if the raw type does not have a type parameter matching the name */ public ParameterizedTypeBuilder withTypeArg(String typeParameterName, @Nullable Type type) { int index = findIndexOfMatchingTypeParam(p -> p.getName().equals(typeParameterName), () -> "No type parameter '" + typeParameterName + "' on " + rawType); updateNewTypeArgumentEntry(index, type); return this; } /** * Sets the given type variable to the provided type. Equivalent to {@link #withTypeArg(TypeVariable, Type)}. * * @param typeVariable the type variable to match * @param typeInfo type info whose type should be set as argument * @return this builder * @throws IllegalArgumentException if the type variable does not belong to the raw type */ public ParameterizedTypeBuilder withTypeArg(TypeVariable<?> typeVariable, TypeInfo typeInfo) { return withTypeArg(typeVariable, typeInfo.getType()); } /** * Sets the type parameter identified by the given type variable to the provided type. Null can be provided to * reset the type parameter back to the class's type variable. Throws an exception if the type variable could not * be matched. * <p> * Example:<pre>{@code * TypeVariable<?> tv = Optional.class.getTypeParameters()[0]; * newTypeFromClass(Optional.class).withTypeArg(tv, Integer.class); * }</pre> * * @param typeVariable the type variable to match * @param type the type to set (or null to reset to the type variable) * @return this builder * @throws IllegalArgumentException if the type variable does not belong to the raw type */ public ParameterizedTypeBuilder withTypeArg(TypeVariable<?> typeVariable, @Nullable Type type) { Predicate<TypeVariable<?>> filter = curVar -> curVar.getName().equals(typeVariable.getName()) && curVar.getGenericDeclaration().equals(typeVariable.getGenericDeclaration()); int index = findIndexOfMatchingTypeParam(filter, () -> "No type parameter matched '" + typeVariable + "' on " + rawType); updateNewTypeArgumentEntry(index, type); return this; } /** * Resets all type parameters to the type variables of the raw type. * * @return this builder */ public ParameterizedTypeBuilder withTypeVariables() { TypeVariable<? extends Class<?>>[] typeVariables = rawType.getTypeParameters(); System.arraycopy(typeVariables, 0, this.newTypeArguments, 0, typeVariables.length); return this; } /** * Creates a parameterized type with the configured raw type and type arguments. * An exception is thrown if any type argument is missing. * * @return new parameterized type * @throws IllegalStateException if a type parameter has not been associated with a value */ public ParameterizedTypeImpl build() { for (int i = 0; i < typeParameters.length; ++i) { if (newTypeArguments[i] == null) { String typeVariableName = typeParameters[i].getName(); throw new IllegalStateException( "Type parameter '" + typeVariableName + "' at index " + i + " has not been set"); } } return new ParameterizedTypeImpl(rawType, ownerType, newTypeArguments); } /** * Creates the appropriate Type with generic information (if needed) to be used as * {@link ParameterizedType#getOwnerType() owner type} of a parameterized type impl with the given raw type. * * @param rawType the raw type whose owner type should be created with generic information * @return owner type to use for the raw type */ @Nullable public static Type createOwnerType(Class<?> rawType) { Class<?> directDeclaringClass = rawType.getDeclaringClass(); if (directDeclaringClass == null || Modifier.isStatic(rawType.getModifiers())) { return directDeclaringClass; } return createOwnerTypeHierarchyForDeclaredNonStaticClass(rawType); } /** * Creates the appropriate owner type with relevant generic info for use in a ParameterizedType * with the given raw type, which may not be static and which must have a non-null declaring class. * <p> * The returned type is either the class's declaring class as Class object if there are no type parameters in * the declaring classes that are available in the class's scope. Otherwise, a hierarchy of ParameterizedType * is returned up to the last class with type parameters available in the class's scope. * * @param rawType the non-static declared class to inspect * @return the appropriate owner type for a parameterized type with the given raw type */ private static Type createOwnerTypeHierarchyForDeclaredNonStaticClass(Class<?> rawType) { List<Class<?>> declaringClasses = collectRelevantDeclaringClasses(rawType); Type lastOwnerType = null; for (int i = declaringClasses.size() - 1; i >= 0; --i) { Class<?> ownerType = declaringClasses.get(i); if (lastOwnerType == null) { TypeVariable<?>[] typeParams = ownerType.getTypeParameters(); if (typeParams.length > 0) { lastOwnerType = new ParameterizedTypeImpl(ownerType, ownerType.getDeclaringClass(), typeParams); } } else { lastOwnerType = new ParameterizedTypeImpl(ownerType, lastOwnerType, ownerType.getTypeParameters()); } } return lastOwnerType == null ? rawType.getDeclaringClass() : lastOwnerType; } /** * Collects all declaring classes iteratively that are relevant for the raw type's owner type hierarchy. * All declaring classes are collected up to the first static class that is encountered. This represents * the set of classes that might have type parameters which are still accessible in the {@code rawType}. * <p> * The list is inspected afterwards and the last element in the returned list that has type parameters will be * the top-most class to be a ParameterizedType in the owner type hierarchy. * * @implNote * Specifically defined to return {@link ArrayList} to guarantee that access by index is efficient. * * @param rawType the raw type whose declaring classes should be gathered * @return list of relevant declaring classes that need to be processed */ private static ArrayList<Class<?>> collectRelevantDeclaringClasses(Class<?> rawType) { ArrayList<Class<?>> declaringClasses = new ArrayList<>(); Class<?> currentClass = rawType.getDeclaringClass(); while (currentClass != null) { declaringClasses.add(currentClass); // All non-static classes and the first static declaring class are relevant, the rest is not if (Modifier.isStatic(currentClass.getModifiers())) { break; } currentClass = currentClass.getDeclaringClass(); } return declaringClasses; } private void updateNewTypeArgumentEntry(int index, @Nullable Type type) { if (type == null) { newTypeArguments[index] = typeParameters[index]; } else { newTypeArguments[index] = type; } } private int findIndexOfMatchingTypeParam(Predicate<TypeVariable<?>> filter, Supplier<String> exceptionMessage) { int index = 0; for (TypeVariable<?> typeParam : typeParameters) { if (filter.test(typeParam)) { return index; } ++index; } throw new IllegalArgumentException(exceptionMessage.get()); } }
C++
UTF-8
226
2.734375
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; int a; int answer = 0; cin >> n; cin >> a; for (int i = 0; i < n; i++) { answer = answer + a % 10; a = a / 10; } cout << answer << "\n"; return (0); }
Java
UTF-8
1,084
1.765625
2
[]
no_license
package com.googlecode.hotire.base.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.googlecode.hotire.base.service.AccountService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; @ActiveProfiles("product") @Slf4j @WebMvcTest(DevelopController.class) class ProductControllerTest { @Autowired MockMvc mockMvc; @MockBean AccountService accountService; @Test void login() throws Exception { mockMvc.perform(get("/test/login/admin")) .andExpect(status().isNotFound()) .andDo(print()); } }
Java
UTF-8
5,403
3.1875
3
[ "Apache-2.0" ]
permissive
package demo01; import java.util.Scanner; //汽车管理类(测试类) public class Text { public static void main(String[] args) { Scanner input = new Scanner(System.in); //先创建租赁业务类(具体车辆) ZuLin zuLin = new ZuLin(); //给数组赋值(买车放入仓库) zuLin.init(); System.out.println("************欢迎光临租赁公司************"); System.out.println("1.轿车 2.客车 3.卡车"); int xuanZe = 0;//选择 boolean flas = true;//标识 //用户租车条件 String pinpai = " ";//品牌 String xinhao = " ";//型号 int zuoweishu = 0;//座位数 int dun = 0;//自重吨位 System.out.print("请选择您要租赁的车型:"); //判断输入是否正确 do { xuanZe = input.nextInt(); if (xuanZe <= 3 && xuanZe > 0) { flas = false; break; } else { System.out.print("输入错误请重新选择:"); } } while (flas == true); //租赁轿车:收集用户条件 boolean as; if (xuanZe == 1) { do { as = true; System.out.print("请选择您要租赁的轿车品牌:1、宝马 2、别克 3、奥迪 :"); int s = input.nextInt(); switch (s) { case 1://租宝马 pinpai = "宝马"; System.out.print("请选择您要租赁的汽车型号:1、X6 2、550i :"); int s1 = 0; boolean flas1; do { flas1 = true; s1 = input.nextInt(); if (s1 <= 2 && s1 > 0) { flas1 = false; break; } else { System.out.print("输入错误请重新选择:"); } } while (flas1 == true); xinhao = (s1 == 1) ? "X6" : "550i"; break; case 2://租别克 pinpai = "别克"; System.out.print("请选择您要租赁的汽车型号:1、林荫大道 2、GL8 :"); int s2 = 0; boolean flas2 = true; do { s2 = input.nextInt(); if (s2 <= 2 && s2 > 0) { flas = false; break; } else { System.out.print("输入错误请重新选择:"); } } while (flas2 == true); xinhao = (s2 == 1) ? "林荫大道" : "GL8"; break; case 3://租奥迪 pinpai = "奥迪"; System.out.print("请选择您要租赁的汽车型号:1、A6 2、Q5 :"); int s3 = 0; boolean flas3 = true; do { s3 = input.nextInt(); if (s3 <= 2 && s3 > 0) { flas = false; break; } else { System.out.print("输入错误请重新选择:"); } } while (flas3 == true); xinhao = (s3 == 1) ? "A6" : "Q5"; break; default: as = false; System.out.println("输入错误,请重新输入!"); break; } } while (as == false); } //租赁客车 else if (xuanZe == 2) { System.out.print("请选择您要租赁的客车品牌:1、金杯 2、金龙 :"); pinpai = (input.nextInt() == 1) ? "金杯" : "金龙"; System.out.print("请选择您要租赁的客车座位数:1、16座 2、34座:"); zuoweishu = (input.nextInt() == 1) ? 16 : 34; } else if (xuanZe == 3) { pinpai = "东风"; System.out.print("请选择您要租赁的卡车自重吨位:1、5吨 2、10吨"); dun = (input.nextInt()==1)?5:10; } //根据用户租车条件 来租车 QiChe qiChe1 = zuLin.che1(pinpai, xinhao, zuoweishu, dun); System.out.print("请输入你的租赁天数:"); int days = input.nextInt(); float money = qiChe1.zongZuJin(days); System.out.print("您需要支付:" + money + "元:"); int moneys = input.nextInt(); System.out.println("已支付:" + moneys + "元"); if (moneys >= money) { System.out.println("租车成功,请按照如下车牌号去提车:" + qiChe1.getChePaiHao()); } else { System.out.println("对不起,支付金额不对!"); } } }
Python
UTF-8
2,190
2.5625
3
[ "Apache-2.0" ]
permissive
import logging from globus_compute_sdk.sdk.login_manager import LoginManager from globus_compute_sdk.sdk.utils.printing import print_table from globus_sdk import AuthAPIError NOT_LOGGED_IN_MSG = "Unable to retrieve user information. Please log in again." logger = logging.getLogger(__name__) def get_user_info(auth_client, user_id): """ Parse username, name, email from auth response and return a list of info """ user_info = auth_client.get_identities(ids=user_id) return [ user_info["identities"][0]["username"], user_info["identities"][0]["name"], user_id, user_info["identities"][0]["email"], ] def print_whoami_info(linked_identities: bool = False) -> None: """ Display information for the currently logged-in user. """ try: auth_client = LoginManager().get_auth_client() except LookupError: logger.debug(NOT_LOGGED_IN_MSG, exc_info=True) raise ValueError(NOT_LOGGED_IN_MSG) whoami_headers = ["Username", "Name", "ID", "Email"] # get userinfo from auth. # if we get back an error the user likely needs to log in again try: user_info = {} res = auth_client.oauth2_userinfo() main_id = res["sub"] user_info[main_id] = get_user_info(auth_client, main_id) whoami_rows = [] if linked_identities: if "identity_set" not in res: raise ValueError( "Your current login does not have the consents required " "to view your full identity set. Please log in again " "to agree to the required consents.\n\n" " Hint: use the --logout flag" ) for linked in res["identity_set"]: linked_id = linked["sub"] if linked_id not in user_info: user_info[linked_id] = get_user_info(auth_client, linked_id) whoami_rows.append(user_info[linked_id]) else: whoami_rows.append(user_info[main_id]) print_table(whoami_headers, whoami_rows) except AuthAPIError: raise ValueError(NOT_LOGGED_IN_MSG)
Java
UTF-8
852
2.390625
2
[]
no_license
package com.luv2code.springboot.myspringbootapp.controller; import java.time.LocalDateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Value("${coach.name}") private String coachName; @Value("${team.name}") private String teamName; @GetMapping("/") public String helloWorld() { return "Hello World in Spring Boot. Time is: " + LocalDateTime.now(); } @GetMapping("/test") public String testDevtools() { return "Test DevTools"; } @GetMapping("/fortune") public String fortune() { return "Today is a happy day"; } @GetMapping("/property") public String property() { return "Coach name: " + coachName + "; Team name: " + teamName; } }
JavaScript
UTF-8
2,690
2.5625
3
[]
no_license
var ObstacleFactory = require('./obstacleFactory') var Obstacle = require('./obstacle') var ObstacleKind = require('./obstacleKind') var Coords = require('../spacial/coords') var Dimensions = require('../spacial/dimensions') var ObstacleGenerator = function () {} ObstacleGenerator.prototype = { generate: function () { var factory = new ObstacleFactory() var pondOptions = { coords: new Coords({ x: 328, y: 60 }), dimensions: new Dimensions({ width: 125, height: 90 }), kind: ObstacleKind.ICE, } var grassTopLeftOptions = { coords: new Coords({ x: 118, y: 65 }), dimensions: new Dimensions({ width: 48, height: 48 }), kind: ObstacleKind.GRASS, } var grassBottomRightOptions = { coords: new Coords({ x: 404, y: 351 }), dimensions: new Dimensions({ width: 48, height: 48 }), kind: ObstacleKind.GRASS, } var grassLeftBorderOptions = { coords: new Coords({ x: 2, y: 43 }), dimensions: new Dimensions({ width: 26, height: 399 }), kind: ObstacleKind.GRASS, } var grassRightBorderOptions = { coords: new Coords({ x: 490, y: 42 }), dimensions: new Dimensions({ width: 26, height: 399 }), kind: ObstacleKind.GRASS, } var treeRightBunchUpperOptions = { coords: new Coords({ x: 305, y: 204 }), dimensions: new Dimensions({ width: 99, height: 42 }), kind: ObstacleKind.TREE, } var treeRightBunchLowerOptions = { coords: new Coords({ x: 323, y: 245 }), dimensions: new Dimensions({ width: 62, height: 27 }), kind: ObstacleKind.TREE, } var treeLeftBunchUpperOptions = { coords: new Coords({ x: 101, y: 341 }), dimensions: new Dimensions({ width: 64, height: 44 }), kind: ObstacleKind.TREE, } var treeLeftBunchLowerOptions = { coords: new Coords({ x: 115, y: 383 }), dimensions: new Dimensions({ width: 33, height: 27 }), kind: ObstacleKind.TREE, } var options = [pondOptions, grassTopLeftOptions, grassBottomRightOptions, grassLeftBorderOptions, grassRightBorderOptions, treeRightBunchUpperOptions, treeRightBunchLowerOptions, treeLeftBunchUpperOptions, treeLeftBunchLowerOptions] var obstacles = [] for (var option of options) { obstacles.push(factory.create(option)) } return obstacles; } } module.exports = ObstacleGenerator
Python
UTF-8
1,813
3
3
[]
no_license
""" This script takes a CSV file exported from an Excel flight logbook and adds its contents into a sqlite3 database. It expects this format: date,planetype,planename,roleonboard,nature,landings,time,notes e.g. 19/03/2011,DR400-120,F-GKRD,EP,LFPL Local,4,01:04,Some notes It then populates the 'Vols' table with links to the 'Avions' table. Only used once to convert my entire Excel worksheet to the sqlite3 format. (c) 2018 Tal Zana """ import csv import sqlite3 as lite con = lite.connect('logbook.db') cur = con.cursor() # Using 'with', changes are automatically committed. # Otherwise, we would have to commit them manually. with con: with open('logbook.csv', mode='r', encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: elements = row[0].split('/') # print(elements) date = elements[2] + '-' + elements[1] + '-' + elements[0] cur.execute("SELECT Avion_ID FROM Avions WHERE Immat=?", (row[2],)) avion_id = cur.fetchone()[0] if row[3] == 'P': cdb = 1 else: cdb = 0 nature = row[4] if row[5] == '': atterrissages = 0 else: atterrissages = int(row[5]) temps = int(row[6][:2]) * 60 + int(row[6][3:]) notes = row[7] # print('{:15} {:10} {:10} {:4} {:20} {:4} {:8} {:20}'.format(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])) # print('{:15} {:10} {:10} {:5} {:21} {:11} {:11}'.format(date, avion_id, cdb, nature, atterrissages, temps, notes)) cur.execute("INSERT INTO Vols VALUES(Null, ?, ?, ?, ?, ?, ?, ?)", (date, avion_id, cdb, nature, atterrissages, temps, notes))
Java
UTF-8
271
1.953125
2
[]
no_license
package theateam.com.tourmanager.Weather; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Url; /** * Created by Hasibuzzaman on 8/22/2016. */ public interface WeatherServiceAPI { @GET Call<WeatherResponse> getWeather(@Url String url); }
Go
UTF-8
1,843
2.984375
3
[ "MIT" ]
permissive
package rsocket import ( "encoding/binary" "io" "time" ) type FrameLease struct { *Header timeToLive uint32 numberOfRequests uint32 metadata []byte } func (p *FrameLease) WriteTo(w io.Writer) (n int64, err error) { var wrote int wrote, err = w.Write(p.Header.Bytes()) n += int64(wrote) if err != nil { return } b4 := make([]byte, 4) binary.BigEndian.PutUint32(b4, p.timeToLive) wrote, err = w.Write(b4) n += int64(wrote) if err != nil { return } binary.BigEndian.PutUint32(b4, p.numberOfRequests) wrote, err = w.Write(b4) n += int64(wrote) if err != nil { return } if !p.Header.Flags().Check(FlagMetadata) { return } wrote, err = w.Write(p.metadata) n += int64(wrote) return } func (p *FrameLease) Size() int { size := headerLen + 8 if p.Header.Flags().Check(FlagMetadata) { size += len(p.metadata) } return size } func (p *FrameLease) TimeToLive() time.Duration { return time.Millisecond * time.Duration(p.timeToLive) } func (p *FrameLease) NumberOfRequests() uint32 { return p.numberOfRequests } func (p *FrameLease) Metadata() []byte { return p.metadata } func (p *FrameLease) Parse(h *Header, bs []byte) error { p.Header = h t1 := binary.BigEndian.Uint32(bs[headerLen : headerLen+4]) n := binary.BigEndian.Uint32(bs[headerLen+4 : headerLen+8]) var metadata []byte if p.Header.Flags().Check(FlagMetadata) { foo := bs[headerLen+8:] metadata = make([]byte, len(foo)) copy(metadata, foo) } p.timeToLive = t1 p.numberOfRequests = n p.metadata = metadata return nil } func mkLease(sid uint32, ttl time.Duration, requests uint32, meatadata []byte, f ...Flags) *FrameLease { return &FrameLease{ Header: mkHeader(sid, LEASE, f...), timeToLive: uint32(ttl.Nanoseconds() / 1e6), numberOfRequests: requests, metadata: meatadata, } }
Python
UTF-8
1,895
2.765625
3
[]
no_license
import argparse import serial import logging import sys import time parser = argparse.ArgumentParser(description='To test ESP8266 communication') parser.add_argument('-p',action='store', dest='comm_port', help='port',default='/dev/ttyAMA0') parser.add_argument('-b',action='store',dest='baud_rate',help='baudrate',default=9600,type=int) #inititiat logging logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) #--- function --- def enum(**enums): return type('Enum', (), enums) def send_cmd(cmd,timeout=1,retry=5): global esp_ser tick = 0 reply='' logging.info("sending command %s to ESP" % cmd) for t in range(retry): #discard all content esp_ser.flushInput() #send command to ESP esp_ser.write(cmd+'\r\n') #wait for reply from ESP reply=esp_ser.readline() time.sleep(0.2) while (tick < timeout or 'busy' in reply): while(esp_ser.inWaiting()): #get all characters in esp_ser's buffer reply= esp_ser.readline().strip( "\r\n" ) #reply = esp_ser.readline() logging.debug(reply) tick = 0 if reply in status.OK : break if reply in status.ERROR : break if reply in status.PROMPT : break time.sleep(1) tick = tick+1 time.sleep(1) if reply in status.OK : break print "RESULT : %s" % reply #some useful status status = enum(PROMPT='>',ERROR='ERROR', OK=['OK', 'ready', 'no change'], BUSY='busy') #get argument values from user arguments = parser.parse_args() #initiate serial comm. esp_ser = serial.Serial(arguments.comm_port,arguments.baud_rate) #clean up and reopen port if esp_ser.isOpen() : esp_ser.close() esp_ser.open() esp_ser.isOpen() try: print "Ctrl-C to stop" prompt ="?" while True : user_input =raw_input(prompt) send_cmd(user_input) except KeyboardInterrupt : esp_ser.close()
Go
UTF-8
1,131
4.6875
5
[]
no_license
package built_in import "fmt" /* Go语言中比较牛逼的是可以将func作为一个传递参数传给别的func。 还有一个闭包的概念可以了解一下。 多说无益,上例子吧。 */ func Hole6Example1() { fmt.Println("Welcome to hole #6.") // 先说闭包closure吧,就是说可以把一个函数整体直接复制给某个变量,还是举例吧 add := func(x int, y int) int { return x + y } // 整个func其实就是把x和y加了一下; 但是,这里的add这个变量可不是int类型了,而是func(int, int) int 类型了 fmt.Printf("add 的类型是%T \n", add) // 这个时候,你就可以直接调用这个函数add(3, 4)了 fmt.Println(add(3, 4)) // 即使不赋值给某个变量,一样可以调用, 但是感觉这个方法的可读性不是很好,我不太喜欢; addValue := func(x, y int) int { return x + y } (30, 40) fmt.Println(addValue) // OK, 还有一种牛逼的是把这个作为参数传给其它的func fmt.Println(external(add)) } func external(add func(int, int) int) int { fmt.Println("Now, I am in external function.") return add(300, 400) }
Java
UHC
4,892
1.953125
2
[]
no_license
package notice.data; import java.io.File; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.runtime.directive.Parse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.mysql.jdbc.PreparedStatement.ParseInfo; import files.data.FilesDto; import files.data.NoticefilesDao; import files.data.NoticefilesDaoInter; @RestController @CrossOrigin public class NoticeController { @Autowired private NoticeDaoInter ndao; @Autowired private NoticefilesDaoInter fdao; //Ʈ @GetMapping("/notice/noticelist") public List<NoticeDto> listNotice(@RequestParam(name = "field", required=false) String field, @RequestParam(name = "search",required=false) String search) { System.out.println("field"+field); System.out.println("search"+search); List<NoticeDto> list=ndao.allOfNotice(field, search); for(int i=0;i<list.size();i++) { if(list.get(i).getNotice_type()==1) { list.get(i).setNoti_type(""); }else { list.get(i).setNoti_type("Ϲ"); } } return list; } //insert @RequestMapping(value="/notice/noticeadd", consumes= {"multipart/form-data"},method = RequestMethod.POST) public void insertNotice(@ModelAttribute NoticeDto ndto,MultipartHttpServletRequest request) { System.out.println("react>>noticeadd"); System.out.println(ndto.toString()); //notice add ndao.insertNotice(ndto); int maxNum=ndao.maxNumNotice(); System.out.println("maxnum="+maxNum); //file add if(ndto.getNotice_file()!=null) { for(MultipartFile f:ndto.getNotice_file()) { System.out.println(f.getOriginalFilename()); } fdao.insertFile(request, ndto.getNotice_file(), maxNum); } //top System.out.println("add notice_type="+ndto.getNotice_type()); if(ndto.getNotice_type()==1) ndao.updateNoticetype(1,maxNum); } // ȸ- @GetMapping("/notice/noticedetail") public NoticeDto getNotice(@RequestParam int num) { System.out.println("react>>noticedetail"); ndao.readCount(num); NoticeDto dto=ndao.getNotice(num); System.out.println(dto); System.out.println(dto.getNotice_type()); return dto; } // ȸ - @GetMapping("/notice/noticefile") public List<String> getnoticeFile(@RequestParam int num) { List<String> list=fdao.selectnoticeFile(num); return list; } // @GetMapping("/notice/noticedelete") public void deleteNotice(@RequestParam int num, HttpServletRequest request) { System.out.println("react>>noticedelete"); //ε String path=request.getSession().getServletContext().getRealPath("/WEB-INF/uploadfile"); //ε ϸ ϱ List<String> list=fdao.selectnoticeFile(num); System.out.println(list.size()); // if(list!=null) { for(int i=0;i<list.size();i++) { System.out.println(list.get(i)); File file=new File(path+"\\"+list.get(i)); if(file.exists()) file.delete(); } } ndao.deleteNotice(num); } //update @RequestMapping(value="/notice/noticeupdate", consumes= {"multipart/form-data"},method = RequestMethod.POST) public void updateNotice(@ModelAttribute NoticeDto ndto, MultipartHttpServletRequest request) { System.out.println("react>>noticeupdate"); System.out.println(ndto.getNotice_type()); //ε String path=request.getSession().getServletContext().getRealPath("/WEB-INF/uploadfile"); if(ndto.getNotice_file()!=null) { for(MultipartFile f:ndto.getNotice_file()) { System.out.println(f.getOriginalFilename()); } //file add fdao.insertFile(request, ndto.getNotice_file(), ndto.getNotice_num()); }else { } //notice update ndao.updateNotice(ndto); ndao.updateNoticetype(ndto.getNotice_type(),ndto.getNotice_num()); System.out.println("notice_delfile="+ndto.getNotice_delfile()); //delete removed file if(ndto.getNotice_delfile()!=null) { for(int i=0;i<ndto.getNotice_delfile().size();i++) { System.out.println(ndto.getNotice_delfile().get(i)); File file=new File(path+"\\"+ndto.getNotice_delfile().get(i)); if(file.exists()) file.delete(); fdao.deleteFile(ndto.getNotice_delfile().get(i)); } }else { } } }
Python
UTF-8
2,918
2.90625
3
[]
no_license
#!/usr/bin/python # Allow to transcode a SROS config file collected by admin display-config in a flat config file # The only limitation is do not have 4 space characters in your description as indentation is # made of 4 space characters # # Vaersion 1.1 # # Usage # python transcode-sros.sh <your-config-file> # or to save in file # python transcode-sros.sh <your-config-file> > flat-config.txt import sys import fileinput # INIT file path file_cfg = fileinput.input() tab_LINE = [] index =0 last_indentation =0 indentation = 0 exit_found = False for read in file_cfg : # Read an config line line = read # Extract Comment lines isComment = line[0] isEcho = line[0:4] # Exclude comment, echo and empty line if isComment != '#': if isEcho != 'echo': if line.strip()!='' and line.strip() != 'exit all': #SROS indentation is made of 4 space characters indentation = line.count(' ') #Manage line that are not made of an exit if line.strip() != 'exit': #If current line is more specific that previous one add word to the list if ((indentation > last_indentation ) or indentation == 0 ): #Add the / for configure statement if line.strip() == 'configure': line = '/'+ line #manage line with create word differently if 'create' in line.strip(): create_line = ' '.join(tab_LINE) + ' ' + line.strip() print(create_line) line = line.replace(' create','').strip() if index>0 and 'create' in tab_LINE[index-1]: print(' '.join(tab_LINE)) tab_LINE[index-1] = tab_LINE[index-1].replace(' create','') tab_LINE.append(line.strip()) index+=1 exit_found = False #If current line is less specific that previous one remove word to the list if (indentation < last_indentation ): del tab_LINE[index-1] tab_LINE.append(line.strip()) #If current line is same specific that previous and depending on last exit found write config line in file if ((last_indentation == indentation ) and indentation!=0 ): if exit_found: del tab_LINE[index-1] tab_LINE.append(line.strip()) print(' '.join(tab_LINE)) else: print(' '.join(tab_LINE)) del tab_LINE[index-1] tab_LINE.append(line.strip()) last_indentation = indentation #Manage line with an exit statement else: if exit_found != True: if last_indentation != indentation: print(' '.join(tab_LINE)) del tab_LINE[index-1] index-=1 del tab_LINE[index-1] index-=1 last_indentation = indentation - 1 exit_found = True else: exit_found = False else: del tab_LINE[index-1] index-=1 last_indentation = indentation - 1 sys.stdout.close ()
C#
UTF-8
11,289
3.1875
3
[]
no_license
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace HideAndSeekTests { using HideAndSeek; using System; using System.Linq; using System.IO; [TestClass] public class GameControllerTests { GameController gameController; [TestInitialize] public void Initialize() { gameController = new GameController(); } [TestMethod] public void TestMovement() { Assert.AreEqual("Entry", gameController.CurrentLocation.Name); Assert.IsFalse(gameController.Move(Direction.Up)); Assert.AreEqual("Entry", gameController.CurrentLocation.Name); Assert.IsTrue(gameController.Move(Direction.East)); Assert.AreEqual("Hallway", gameController.CurrentLocation.Name); Assert.IsTrue(gameController.Move(Direction.Up)); Assert.AreEqual("Landing", gameController.CurrentLocation.Name); // Add more movement tests to the TestMovement test method } [TestMethod] public void TestParseInput() { var initialStatus = gameController.Status; Assert.AreEqual("That's not a valid direction", gameController.ParseInput("X")); Assert.AreEqual(initialStatus, gameController.Status); Assert.AreEqual("There's no exit in that direction", gameController.ParseInput("Up")); Assert.AreEqual(initialStatus, gameController.Status); Assert.AreEqual("Moving East", gameController.ParseInput("East")); Assert.AreEqual("You are in the Hallway. You see the following exits:" + Environment.NewLine + " - the Bathroom is to the North" + Environment.NewLine + " - the Living Room is to the South" + Environment.NewLine + " - the Entry is to the West" + Environment.NewLine + " - the Kitchen is to the Northwest" + Environment.NewLine + " - the Landing is Up" + Environment.NewLine + "You have not found any opponents", gameController.Status); Assert.AreEqual("Moving South", gameController.ParseInput("South")); Assert.AreEqual("You are in the Living Room. You see the following exits:" + Environment.NewLine + " - the Hallway is to the North" + Environment.NewLine + "Someone could hide behind the sofa" + Environment.NewLine + "You have not found any opponents", gameController.Status); } [TestMethod] public void TestParseCheck() { Assert.IsFalse(gameController.GameOver); // Clear the hiding places and hide the opponents in specific rooms House.ClearHidingPlaces(); var joe = gameController.Opponents.ToList()[0]; (House.GetLocationByName("Garage") as LocationWithHidingPlace).Hide(joe); var bob = gameController.Opponents.ToList()[1]; (House.GetLocationByName("Kitchen") as LocationWithHidingPlace).Hide(bob); var ana = gameController.Opponents.ToList()[2]; (House.GetLocationByName("Attic") as LocationWithHidingPlace).Hide(ana); var owen = gameController.Opponents.ToList()[3]; (House.GetLocationByName("Attic") as LocationWithHidingPlace).Hide(owen); var jimmy = gameController.Opponents.ToList()[4]; (House.GetLocationByName("Kitchen") as LocationWithHidingPlace).Hide(jimmy); // Check the Entry -- there are no players hiding there Assert.AreEqual(1, gameController.MoveNumber); Assert.AreEqual("There is no hiding place in the Entry", gameController.ParseInput("Check")); Assert.AreEqual(2, gameController.MoveNumber); // Move to the Garage gameController.ParseInput("Out"); Assert.AreEqual(3, gameController.MoveNumber); // We hid Joe in the Garage, so validate ParseInput's return value and the properties Assert.AreEqual("You found 1 opponent hiding behind the car", gameController.ParseInput("check")); Assert.AreEqual("You are in the Garage. You see the following exits:" + Environment.NewLine + " - the Entry is In" + Environment.NewLine + "Someone could hide behind the car" + Environment.NewLine + "You have found 1 of 5 opponents: Joe", gameController.Status); Assert.AreEqual("4: Which direction do you want to go (or type 'check'): ", gameController.Prompt); Assert.AreEqual(4, gameController.MoveNumber); // Move to the bathroom, where nobody is hiding gameController.ParseInput("In"); gameController.ParseInput("East"); gameController.ParseInput("North"); // Check the Bathroom to make sure nobody is hiding there Assert.AreEqual("Nobody was hiding behind the door", gameController.ParseInput("check")); Assert.AreEqual(8, gameController.MoveNumber); // Check the Bathroom to make sure nobody is hiding there gameController.ParseInput("South"); gameController.ParseInput("Northwest"); Assert.AreEqual("You found 2 opponents hiding next to the stove", gameController.ParseInput("check")); Assert.AreEqual("You are in the Kitchen. You see the following exits:" + Environment.NewLine + " - the Hallway is to the Southeast" + Environment.NewLine + "Someone could hide next to the stove" + Environment.NewLine + "You have found 3 of 5 opponents: Joe, Bob, Jimmy", gameController.Status); Assert.AreEqual("11: Which direction do you want to go (or type 'check'): ", gameController.Prompt); Assert.AreEqual(11, gameController.MoveNumber); Assert.IsFalse(gameController.GameOver); // Head up to the Landing, then check the Pantry (nobody's hiding there) gameController.ParseInput("Southeast"); gameController.ParseInput("Up"); Assert.AreEqual(13, gameController.MoveNumber); gameController.ParseInput("South"); Assert.AreEqual("Nobody was hiding inside a cabinet", gameController.ParseInput("check")); Assert.AreEqual(15, gameController.MoveNumber); // Check the Attic to find the last two opponents, make sure the game is over gameController.ParseInput("North"); gameController.ParseInput("Up"); Assert.AreEqual(17, gameController.MoveNumber); Assert.AreEqual("You found 2 opponents hiding in a trunk", gameController.ParseInput("check")); Assert.AreEqual("You are in the Attic. You see the following exits:" + Environment.NewLine + " - the Landing is Down" + Environment.NewLine + "Someone could hide in a trunk" + Environment.NewLine + "You have found 5 of 5 opponents: Joe, Bob, Jimmy, Ana, Owen", gameController.Status); Assert.AreEqual("18: Which direction do you want to go (or type 'check'): ", gameController.Prompt); Assert.AreEqual(18, gameController.MoveNumber); Assert.IsTrue(gameController.GameOver); } [TestMethod] public void TestSaveAndLoad() { // Clear the hiding places and hide the opponents in specific rooms House.ClearHidingPlaces(); var joe = gameController.Opponents.ToList()[0]; (House.GetLocationByName("Garage") as LocationWithHidingPlace).Hide(joe); var bob = gameController.Opponents.ToList()[1]; (House.GetLocationByName("Garage") as LocationWithHidingPlace).Hide(bob); var ana = gameController.Opponents.ToList()[2]; (House.GetLocationByName("Attic") as LocationWithHidingPlace).Hide(ana); var owen = gameController.Opponents.ToList()[3]; (House.GetLocationByName("Attic") as LocationWithHidingPlace).Hide(owen); var jimmy = gameController.Opponents.ToList()[4]; (House.GetLocationByName("Kitchen") as LocationWithHidingPlace).Hide(jimmy); // Find three opponents and move to the Hallway gameController.ParseInput("Out"); gameController.ParseInput("Check"); gameController.ParseInput("In"); gameController.ParseInput("East"); gameController.ParseInput("Northwest"); gameController.ParseInput("Check"); gameController.ParseInput("Southeast"); Assert.AreEqual(8, gameController.MoveNumber); Assert.AreEqual("Hallway", gameController.CurrentLocation.Name); string filename; do { filename = $"testsave_{new Random().Next()}"; } while (File.Exists($"{filename}.json")); // Save the game state to a temporary file gameController.ParseInput($"save {filename}"); gameController = new GameController(); Assert.AreEqual(1, gameController.MoveNumber); Assert.AreEqual("Entry", gameController.CurrentLocation.Name); gameController.ParseInput($"load {filename}"); Assert.AreEqual(8, gameController.MoveNumber); Assert.AreEqual("Hallway", gameController.CurrentLocation.Name); Assert.AreEqual("You are in the Hallway. You see the following exits:" + Environment.NewLine + " - the Bathroom is to the North" + Environment.NewLine + " - the Living Room is to the South" + Environment.NewLine + " - the Entry is to the West" + Environment.NewLine + " - the Kitchen is to the Northwest" + Environment.NewLine + " - the Landing is Up" + Environment.NewLine + "You have found 3 of 5 opponents: Joe, Bob, Jimmy", gameController.Status); // Clean up your temporary file File.Delete(filename); Assert.IsTrue(!File.Exists(filename)); } [TestMethod] public void TestInvalidFilenames() { Assert.AreEqual("Please enter a filename without slashes or spaces.", gameController.Save("invalid\\filename")); Assert.AreEqual("Please enter a filename without slashes or spaces.", gameController.Save("invalid/filename")); Assert.AreEqual("Please enter a filename without slashes or spaces.", gameController.Save("invalid filename")); } } }
Python
UTF-8
824
2.515625
3
[]
no_license
from aspect import Aspect from Kaerber.MUD.Entities import Event, EventReturnMethod # See aspect.py for details def construct(): return ManaAspect() class ManaAspect( Aspect ): def __init__( self ): self.Value = 0 self._host = None def Clone( self ): return ManaAspect() @property def Max( self ): e = Event.Create( "query_max_mana", EventReturnMethod.Sum ) self.Host.ReceiveEvent( e ) return( e.ReturnValue ) # Save/Load def Serialize( self ): return { 'Value': self.Value } def Deserialize( self, data ): self.Value = data['Value'] return self def Restore( self ): self.Value = self.Max # Event handlers def tick( self, event ): self.Value = min( self.Value + 1, self.Max )
Ruby
UTF-8
3,224
2.65625
3
[]
no_license
module Kungfuig # Generic helper for massive attaching aspects module Aspector # Helper methods class H def value_to_method_list klazz, values_inc, values_exc # FIXME MOVE JOKER HANDLING INTO PREPENDER !!!! if klazz.is_a?(Module) [values_inc, values_exc].map do |v| v = [*v].map(&:to_sym) case when v.empty? then [] when v.include?('*'), v.include?(:'*') then klazz.instance_methods(false) else klazz.instance_methods & v end end.reduce(&:-) - klazz.instance_methods(false).select { |m| m.to_s.start_with?('to_') } else # NOT YET IMPLEMENTED FIXME MOVE TO PREPENDER [values_inc, values_exc].map do |v| [*v].map(&:to_sym) end.reduce(&:-) - [:'*'] end end def remap_hash_for_easy_iteration hash hash = hash.each_with_object(Hashie::Mash.new) do |(k, v), memo| v.each { |m, c| memo.public_send("#{m}!")[k] = c } end unless (hash.keys - %w(before after exclude)).empty? hash.each_with_object({}) do |(k, v), memo| v.each { |m, h| ((memo[h] ||= {})[k.to_sym] ||= []) << m } end end def proc_instance string m, k = string.split('#').reverse (k ? Kernel.const_get(k).method(m) : method(m)).to_proc end def try_to_class name Kernel.const_defined?(name.to_s) ? Kernel.const_get(name.to_s) : name end end def attach(to, before: nil, after: nil, exclude: nil) fail ArgumentError, "Trying to attach nothing to #{klazz}##{to}. I need a block!" unless block_given? cb = Proc.new klazz = case to when Module then to # got a class! wow, somebody has the documentation read when String, Symbol then H.new.try_to_class(to) # we are ready to get a class name else class << to; self; end # attach to klazz’s eigenclass if object given end { before: before, after: after }.each do |k, var| H.new.value_to_method_list(klazz, var, exclude).each do |m| Kungfuig::Prepender.new(to, m).public_send(k, &cb).hook! end unless var.nil? end klazz.is_a?(Module) ? klazz.aspects : { promise: klazz } end module_function :attach # 'Test': # after: # 'yo': 'YoCalledAsyncHandler#process' # 'yo1' : 'YoCalledAsyncHandler#process' # before: # 'yo': 'YoCalledAsyncHandler#process' def bulk(hos) Kungfuig.load_stuff(hos).map do |klazz, hash| next if hash.empty? [klazz, H.new.remap_hash_for_easy_iteration(hash).map do |handler, methods| begin attach(klazz, **methods, &H.new.proc_instance(handler)) rescue => e raise ArgumentError, [ "Bad input to Kungfuig::Aspector##{__callee__}.", "Args: #{methods.inspect}", "Original exception: #{e.message}.", e.backtrace.unshift("Backtrace:").join("#{$/}⮩ ") ].join($/.to_s) end end] end.compact.to_h end module_function :bulk private_constant :H end end
Markdown
UTF-8
469
2.59375
3
[]
no_license
# Managing flutter Status Application to show how to handle the variety of options that flutter has to manage de application status ## Getting Started This project will help you to understad the next state managment: - Singleton - Provider - Cubit - Bloc A few resources to get you started: - [Lab: State management](https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple) - [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
Python
UTF-8
1,126
3.8125
4
[]
no_license
#--------------------------------------------------------------------- # Title: Assignment 7 # Desc: Script that shows examples of pickling and handling exceptions # Changelog: (Who, Date, info) # BBicksler, 11-30-2020, created file, added pickling example #---------------------------------------------------------------------- # example of using pickle to save a dictionary # Step 1 - import Pickle into your python code import pickle # Step 2 - create my dictionary my_dict = {'Frank': 47, 'Jane': 35, 'Butch': 27, "Linda": 51} # now I have 3 peoples names and ages. # Specify a filename to write to and then open the file for binary writing filename = 'people' outfile = open(filename,'wb') # then use pickle.dump() to write to the file pickle.dump(my_dict,outfile) outfile.close() # Now I will open the file to verify the data was saved correctly infile = open(filename,'rb') new_dict = pickle.load(infile) infile.close() # I will print the new dictionary to validate the data print(new_dict) # I can also compare it to my other dictionary print(new_dict==my_dict)
C#
UTF-8
581
2.78125
3
[]
no_license
public class TestData : INotifyPropertyChanged { public double Test { get { return _test; } set { _test = value; OnPropertyChange("Test"); } } private double _test; private void OnPropertyChange(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChanged; }
Java
UTF-8
454
3.28125
3
[ "MIT" ]
permissive
public class Aluno { String name; int cc; public Aluno(String n, int cc) { name = n; this.cc = cc; } public String getName(){ return name; } public void setName(String n){ name = n; } public int getCC(){ return cc; } public void setCC(int cc){ this.cc = cc; } public String toString(){ return "\nThe Student " + name + " has the cc " + cc + "."; } }
PHP
UTF-8
1,147
2.84375
3
[ "MIT" ]
permissive
<?php namespace Navel\Utils; use \Navel\Core\Singleton; /** * Description of Session * * @author Julien */ class Session extends Singleton implements \ArrayAccess { protected static $_INSTANCE = null; public function keyExists($key) { return $this->offsetExists($key); } public function get($key) { return $this->offsetGet($key); } public function set($key, $value) { $this->offsetSet($key, $value); } public function unsetKey($key) { $this->offsetUnset($key); } public function offsetExists($offset) { return isset($_SESSION[$offset]); } public function offsetGet($offset) { return $_SESSION[$offset]; } public function offsetSet($offset, $value) { $_SESSION[$offset] = $value; } public function offsetUnset($offset) { if($this->offsetExists($offset)) { unset($_SESSION[$offset]); } } protected function __construct() { if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } } }
C++
UTF-8
2,795
2.84375
3
[ "MIT" ]
permissive
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // // Contents: Tells a flow layout where text is allowed to flow. // //---------------------------------------------------------------------------- #include "pch.h" #include "TextAnalysis.h" #include "FlowSource.h" void FlowLayoutSource::Reset() { m_currentV = 0; m_currentU = 0; } void FlowLayoutSource::SetSize( float width, float height ) { m_width = width; m_height = height; } bool FlowLayoutSource::GetNextRect( float fontHeight, ReadingDirection readingDirection, _Out_ RectF* nextRect ) { RectF& rect = *nextRect; // Set defaults. RectF zeroRect = {}; rect = zeroRect; if (m_height <= 0 || m_width <= 0) { return 1; // Do nothing if empty. } bool const isVertical = (readingDirection & ReadingDirectionPrimaryAxis) != 0; bool const isReversedPrimary = (readingDirection & ReadingDirectionPrimaryProgression) != 0; bool const isReversedSecondary = (readingDirection & ReadingDirectionSecondaryProgression) != 0; float const uSize = isVertical ? m_height : m_width; float const vSize = isVertical ? m_width : m_height; float const uSizeHalf = uSize / 2; float const vSizeHalf = vSize / 2; if (m_currentV >= vSize) { return 1; // Crop any further lines. } // Initially set to entire size. rect.left = 0; rect.top = 0; rect.right = uSize; rect.bottom = vSize; // Advance to the next row/column. float u = m_currentU; float v = m_currentV; m_currentV += fontHeight; float minSizeHalf = min(uSizeHalf, vSizeHalf); float adjustedV = (v + fontHeight/2) - vSizeHalf; // Determine x from y using circle formula d^2 = (x^2 + y^2). float d2 = (minSizeHalf * minSizeHalf) - (adjustedV * adjustedV); u = (d2 > 0) ? sqrt(d2) : -1; rect.top = v; rect.bottom = v + fontHeight; rect.left = uSizeHalf - u; rect.right = uSizeHalf + u; // Reorient rect according to reading direction. if (isReversedPrimary) { std::swap(rect.left, rect.right); rect.left = uSize - rect.left; rect.right = uSize - rect.right; } if (isReversedSecondary) { std::swap(rect.top, rect.bottom); rect.top = vSize - rect.top; rect.bottom = vSize - rect.bottom; } if (isVertical) { std::swap(rect.left, rect.top); std::swap(rect.right, rect.bottom); } return 1; }
Java
UTF-8
2,415
2.140625
2
[]
no_license
package com.example.controller; import com.example.bean.Provider; import com.example.service.ProviderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * Create by Administrator on 2020/2/22. */ @Controller public class ProviderController { @Autowired ProviderService providerService; @GetMapping("/list/providers") public String toProvidersList(HttpServletRequest httpServletRequest, Map<String, Object> map){ System.out.println("toProviderList method="+httpServletRequest.getMethod()); List<Provider> providers = providerService.pListAll(); map.put("providers", providers); return "provider/list"; } @GetMapping("/provider/{pid}") public String view(@RequestParam(value="type", defaultValue = "view") String type, HttpServletRequest httpServletRequest, @PathVariable(value = "pid") int pid, Map<String, Object> map){ System.out.println("view method="+httpServletRequest.getMethod()); Provider provider = providerService.getProByPid(pid); map.put("provider", provider); return "provider/"+type; } @PostMapping("/provider") public String update(HttpServletRequest httpServletRequest, Provider provider){ System.out.println("update method="+httpServletRequest.getMethod()); providerService.updateProv(provider); return "redirect:/list/providers"; } @GetMapping("/delete/provider/{pid}") public String delete(HttpServletRequest httpServletRequest, @PathVariable(value = "pid") int pid){ System.out.println("delete method="+httpServletRequest.getMethod()); providerService.deleteProByPid(pid); return "redirect:/list/providers"; } @GetMapping("/provider/add") public String toAdd(HttpServletRequest httpServletRequest){ System.out.println("toAdd method="+httpServletRequest.getMethod()); return "provider/add"; } @PostMapping("/provider/add") public String add(HttpServletRequest httpServletRequest, Provider provider){ System.out.println("add method="+httpServletRequest.getMethod()); providerService.addProv(provider); return "redirect:/list/providers"; } }
Java
UTF-8
2,429
2.515625
3
[]
no_license
package com.br.medialert.util; import android.os.AsyncTask; import android.util.Base64; import android.util.Log; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Igor Costa on 08/10/2016. */ public class HttpCloudant extends AsyncTask<String, Void, String> { private final String userName = "----------" ; private final String password = "---------------" ; @Override protected String doInBackground(String... urls) { HttpURLConnection client; String retorno = ""; try { URL url = new URL(urls[0]); client = (HttpURLConnection) url.openConnection(); client.setRequestProperty("Content-Type", "application/json"); client.setRequestProperty("charset", "utf-8"); client.setRequestMethod(urls[1]); client.setDoOutput(true); client.setDoInput(true); String encodedPassword = userName + ":" + password; String encoded = Base64.encodeToString(encodedPassword.getBytes(), Base64.NO_WRAP); client.setRequestProperty("Authorization", "Basic " + encoded); OutputStreamWriter wr; wr = new OutputStreamWriter(client.getOutputStream()); wr.write(urls[2]); Log.e("Filtro",urls[2]); wr.close(); StringBuilder sb = new StringBuilder(); int statusCodeHTTP = client.getResponseCode(); if (statusCodeHTTP == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); retorno = sb.toString(); } else { Log.e("Erro GET ALL ", "Erro na Requisição! Código do Erro: " + statusCodeHTTP + "\nMensagem de Erro: " + client.getResponseMessage()); } }catch (Exception e){ Log.e("erro", e.getMessage() + e.getCause() ); } return retorno; } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { } }
PHP
UTF-8
2,117
2.71875
3
[]
no_license
<?php namespace Favorite\Commands; class Add extends \AbstractCommand implements \IFrameCommand { private $params; private $id; public function validateData(\IRequestObject $requestObject) { return true; } public function processData(\IRequestObject $requestObject) { $this->params = $requestObject->getParams(); isset($this->params[0]) ? $this->id = $this->params[0]: ""; } public function frameResponse(\FrameResponseObject $frameResponseObject) { $frameResponseObject = $this->execute($frameResponseObject); return $frameResponseObject; } public function execute (\FrameResponseObject $frameResponseObject) { $steam=$GLOBALS["STEAM"]; $id = $this->id; if($this->params[1] == "group" || $this->params[1] == "user" ){ $category = $this->params[1]; } else{ throw new \Exception("category isn't set"); } if ($category == "user" && $id!=0) { $user = \steam_factory::get_object($steam->get_id(), $id); $user_data = $user->get_attributes(array(OBJ_NAME, OBJ_DESC, USER_FIRSTNAME, USER_FULLNAME, USER_EMAIL, USER_ADRESS, OBJ_ICON, "bid:user_callto", "bid:user_im_adress", "bid:user_im_protocol")); // $user_email_forwarding = $user->get_email_forwarding(); } elseif($category == "group" && $id!=0) { $group = \steam_factory::get_object($steam->get_id(), $id); $group_data = $group->get_attributes(array(OBJ_NAME, OBJ_DESC)); } $user_favourites = \lms_steam::get_current_user()->get_buddies(); if (count($user_favourites) == 0) $user_favourites = array(); if ($category=="user") array_push($user_favourites, $user); else if ($category=="group") array_push($user_favourites, $group); \lms_steam::get_current_user()->set_attribute("USER_FAVOURITES", $user_favourites); //$frameResponseObject->setConfirmText(gettext("Favorite added successfully")); $frameResponseObject->setConfirmText("Favorit erfolgreich hinzugefügt!"); $widget = new \Widgets\JSWrapper(); $url = 'self.location.href="'.PATH_URL.'favorite/index'.'"'; $widget->setJs($url); $frameResponseObject->addWidget($widget); return $frameResponseObject; } } ?>
Swift
UTF-8
889
3.34375
3
[]
no_license
// // Person.swift // GroupRandomizer // // Created by Domenic Wüthrich on 15.08.18. // Copyright © 2018 Domenic Wüthrich. All rights reserved. // import Foundation public class Person { // MARK: - Variable /// Name of person public var name: String /// Random double value needed for sorting into groups public var randomToken: Double // MARK: - Initializers /// Initializers a new Person /// - Parameter name: Name of person /// - Note: Sets randomToken to 0 public convenience init(name: String) { self.init(name: name, randomToken: 0) } /// Initializes a new Person /// - Parameters: /// - name: Name of person /// - randomToken: Random double value for sorting public init(name: String, randomToken: Double) { self.name = name self.randomToken = randomToken } }
Java
UTF-8
791
1.953125
2
[]
no_license
package com.ulisses.desafio.service.impl; import com.ulisses.desafio.api.dto.EmailDTO; import com.ulisses.desafio.model.entity.Email; import com.ulisses.desafio.model.repository.EmailRepository; import com.ulisses.desafio.service.EmailService; import org.springframework.stereotype.Service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; @Service public class EmailServiceImpl implements EmailService { @Autowired private EmailRepository repository; @Override public Email salvar(Email email) { return repository.save(email); } @Override public void apagarVinculo(Long clienteId) { repository.apagarVinculo(clienteId); } @Override public List<EmailDTO> lista(Long clienteId) { return repository.lista(clienteId); } }
C++
UTF-8
1,344
3.21875
3
[]
no_license
#include<iostream> #include<vector> #include<map> #include<queue> using namespace std; class Solution { public: class mycompare { public: bool operator()(const pair<int,int> lhs, const pair<int,int> rhs) { return lhs.first >= rhs.first; } }; vector<int> mostFrequent(vector<int>& nums, int k) { map<int, int> freqs; for (int i = 0; i < nums.size(); i++) { auto x = freqs.insert(pair<int,int>(nums[i],1)); if (!x.second) x.first->second++; } priority_queue<pair<int,int>, vector<pair<int,int>>, mycompare>pq; for(auto x = freqs.begin(); x != freqs.end(); x++) { if (pq.size() < k ) pq.emplace(make_pair(x->first, x->second)); else { if (x->second > pq.top().second) { pq.pop(); pq.emplace(make_pair(x->first, x->second)); } } } vector<int> ret; while(!pq.empty()) { ret.push_back(pq.top().first); pq.pop(); } return ret; } }; int main() { Solution s; vector<int> x{3,1,2,3,2,3}; vector<int> out = s.mostFrequent(x,1); for (int i = 0; i < out.size(); i++) { cout<<out[i]<<","; } cout<<endl; }
Go
UTF-8
776
2.671875
3
[]
no_license
package errcmp import ( "go/ast" "go/token" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" ) var Analyzer = &analysis.Analyzer{ Name: "errcmp", Doc: Doc, Run: run, Requires: []*analysis.Analyzer{ inspect.Analyzer, }, } const Doc = "errcmp is ..." func run(pass *analysis.Pass) (interface{}, error) { for _, f := range pass.Files { ast.Inspect(f, func(n ast.Node) bool { if binary, ok := n.(*ast.BinaryExpr); ok { if binary.Op == token.NEQ { switch binary.X.(type) { case *ast.Ident: errName := binary.X.(*ast.Ident).Name if errName == "err" { pass.Reportf(binary.OpPos, "'err != ...' should be 'erros.Is(err, ...)'") } } } } return true }) } return nil, nil }
Markdown
UTF-8
2,434
3.15625
3
[]
no_license
--- layout: post title: "Cohabitating Protocols" date: 2018-04-05 preview: Using nginx +1.13.10, REST and gRPC services can cohabitate behind a single proxy. --- **EDIT Apr 8, 2018:** The notes below may cause trouble if you have a catch-all redirect from http to https in your configuration. I think it wise to use the standard port `50051` as a gateway to your app, proxying with nginx. I wouldn't expose this port externally; rather, constraining it via security group rules is recommended. If you do publish a gRPC service for external ( eg. browser-initiated ) traffic, then you ought to utilize the secure socket at `1443` as the gateway. </hr> Many modern "stacks" (at the time of writing this blog post) will utilizer Docker + Kubernetes to isolate and distribute services of different flavors. If you find yourself in a "legacy" situation where services get deployed to distinct servers, and those servers use nginx as a proxy between the outside and to the deployed services, then you'll be relieved to know that cohabitation is not all that difficult. Here's a (simplified) nginx configuration for a RESTful API upstream restful_app { server unix:/run/puma/restful_app1.socket; server unix:/run/puma/restful_app2.socket; } server { listen 80 default_server; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location @restful_app { proxy_pass http://restful_app; } } Assume the configuration lay in someplace like `/etc/nginx/default.d/restful_app.conf`. The [recently released support for gRPC](https://www.nginx.com/blog/nginx-1-13-10-grpc) makes configuring an accompanying service very easy. upstream grpc_app { server 127.0.0.1:50051 server 127.0.0.1:50052 } server { listen 80 http2; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location /service.Endpoint { grpc_pass grpc://grpc_app; } } We can assume this configuration lay somewhere nearby like `/etc/nginx/default.d/grpc_app.conf`. Both configurations will load into the same nginx server, which will route traffic as expected. As both HTTP and HTTP2 use TCP as the underlying transport layer, nginx can use port 80 to proxy traffic to both applications, even though the higher-level protocol (HTTP vs HTTP2) and the API dialect (REST vs gRPC) differ. Cool, huh?
Markdown
UTF-8
1,781
2.9375
3
[ "MIT" ]
permissive
# React OTP Verification app One top password verification code app made with react.js and textlocal.com api(sms service provider) ## Working * Enter any Indian Phone number you have and click on send otp * You will receive a text message with a unique code. * Enter the code and click on Verify * If you enter the invalid code you will get Invalid OTP Error * if you did not get the OTP check the console log, You will see the OTP and the Json response from the Textlocal api Sms provider ![alt text](https://bharath.fr/reactotp.gif) ## Installation * Clone the GitHub repository [React OTP Verification app](https://github.com/bharath2232/React_Native-France-Shipping/) to local machine or server ```bash git clone https://github.com/bharath2232/React-OTP-Send ``` * Buy some SMS credits from textlocal.com(they provide SMS service for all over the world) * Copy the API key from the dashboard textlocal.com ## Usage * Change the API Key with XXXXXXX in sendOtpHandler() ```javascript sendOtpHandler = () => { console.log('logged', this.state.name) console.log('otp', this.state.otp); const params = { apikey: 'XXXXXXXXXXX', numbers: '91' + this.state.phoneNo, message: 'Your OTP is ' + this.state.otp } axios.get('https://api.textlocal.in/send/', {params: params}) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/)
C++
UTF-8
2,255
2.75
3
[]
no_license
#ifndef BPLUSTREE_H_INCLUDED #define BPLUSTREE_H_INCLUDED #include "BPlusTreeExceptions.h" #include "BPlusBlockBuffer.h" #include <fstream> #include <list> template<class Record,unsigned int leafOrder,unsigned int nonLeafOrder,unsigned int blockSize=512> class BPlusTree{ public: class Node{ protected: BPlusBlockBuffer<Record,typename Record::Key,blockSize> *block; std::fstream & file_; unsigned int pos_; unsigned int count_; unsigned int level_; virtual void updateBlock()=0; public: Node(); Node(std::fstream & file,unsigned int pos); unsigned int level()const; unsigned int count()const; unsigned int pos()const; void level(unsigned int); void count(unsigned int); void file(std::fstream &); void pos(unsigned int); virtual void insert(Record &)=0; virtual void remove(Record &)=0; virtual bool isLeaf()const=0; virtual void read()=0; virtual void write()=0; virtual ~Node(); }; class Leaf: public Node{ unsigned int next_; std::list<Record*> records_; void updateBlock(); public: Leaf(); Leaf(std::fstream & file,unsigned int pos); typename std::list<Record*>::iterator search(Record&); void insert(Record &); void remove(Record &); }; class NonLeaf: public Node{ std::list<uint32_t> childrens_; std::list<typename Record::Key*> keys_; void updateBlock(); public: NonLeaf(std::fstream & file,unsigned int pos); void insert(Record &); void remove(Record &); }; private: Node * root; std::fstream & file_; public: BPlusTree(); BPlusTree(std::fstream & file); void insert(const Record & rec); void remove(const Record & rec); const Record & search(const Record & rec); void update(const Record & rec); }; #endif // BPLUSTREE_H_INCLUDED
Java
UTF-8
400
2.25
2
[]
no_license
package ru.zolax.callapp.database.managers; import java.sql.SQLException; import java.util.List; public interface ManagerInterface <T> { public void add(T entity) throws SQLException; public int update(T entity) throws SQLException; public int deleteById(int id) throws SQLException; public T getById(int id) throws SQLException; public List<T> getAll() throws SQLException; }
Swift
UTF-8
321
2.609375
3
[]
no_license
// // Contact.swift // ggchat // // Created by Gary Chang on 11/25/15. // Copyright © 2015 Blub. All rights reserved. // import Foundation class Contact { var id: String var displayName: String init(id: String, displayName: String) { self.id = id self.displayName = displayName } }
Java
UTF-8
261
2.28125
2
[]
no_license
package com.qqxhb.spi.java; import java.util.ServiceLoader; public class JavaSPI { public static void main(String[] args) { ServiceLoader<IAnimal> serviceLoader = ServiceLoader.load(IAnimal.class); serviceLoader.forEach(IAnimal::say); } }
Java
UTF-8
5,424
2.09375
2
[]
no_license
package com.sjony.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.sjony.base.BaseController; import com.sjony.service.SeckillSkuService; import com.sjony.service.impl.SkuSaleSeckillServiceImpl; import com.sjony.utils.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.util.List; /** * @Description: 秒杀相关 * @Create on: 2017/8/2 上午10:28 * * @author shujiangcheng */ @Controller @RequestMapping("/rest/seckillSku") public class SeckillSkuController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(SeckillSkuController.class); private static int i = 0; @Autowired private SeckillSkuService seckillSkuService; /** * @Description: 新增秒杀商品 * @Create on: 2017/7/24 下午1:39 * * @author shujiangcheng */ @ResponseBody @RequestMapping(value = "/insertCacheSeckillSkuQty", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) public String insertCacheSeckillSkuQty(@RequestParam(value = "data") String data) throws IllegalAccessException, IntrospectionException, InvocationTargetException { /*-----------------------------------------------------------------* 入参处理 *----------------------------------------------------------------*/ if(data == null) { error("data is null"); } List<String> skuList = JSON.parseArray(JSON.parseObject(data).getString("skuCode"), String.class); if(CollectionUtils.isEmpty(skuList)) { error("skuCode is null"); } /*-----------------------------------------------------------------* 逻辑处理 *----------------------------------------------------------------*/ int result = seckillSkuService.insertCacheSeckillSkuQty(skuList); /*-----------------------------------------------------------------* 数据返回 *----------------------------------------------------------------*/ return success(result); } /** * @Description: 秒杀商品扣库存 * @Create on: 2017/7/24 下午1:39 * * @author shujiangcheng */ @ResponseBody @RequestMapping(value = "/updateSeckillSkuQty", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) public String updateSeckillSkuQty(@RequestParam(value = "data") String data) { /*-----------------------------------------------------------------* 入参处理 *----------------------------------------------------------------*/ logger.warn("扣库存" + ++i); if(data == null) { error("data is null"); } List<String> skuList = JSON.parseArray(JSON.parseObject(data).getString("skuCode"), String.class); if(CollectionUtils.isEmpty(skuList)) { error("skuCode is null"); } /*-----------------------------------------------------------------* 逻辑处理 *----------------------------------------------------------------*/ int result = seckillSkuService.updateSeckillSkuQty(skuList); /*-----------------------------------------------------------------* 数据返回 *----------------------------------------------------------------*/ return success(result); } /** * @Description: 秒杀商品扣库存 * @Create on: 2017/7/24 下午1:39 * * @author shujiangcheng */ @ResponseBody @RequestMapping(value = "/updateSeckillSkuQtyWithoutRedis", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) public String updateSeckillSkuQtyWithoutRedis(@RequestParam(value = "data") String data) { /*-----------------------------------------------------------------* 入参处理 *----------------------------------------------------------------*/ if(data == null) { error("data is null"); } List<String> skuList = JSON.parseArray(JSON.parseObject(data).getString("skuCode"), String.class); if(CollectionUtils.isEmpty(skuList)) { error("skuCode is null"); } /*-----------------------------------------------------------------* 逻辑处理 *----------------------------------------------------------------*/ int result = seckillSkuService.updateSeckillSkuQtyTestWithoutRedis(skuList); /*-----------------------------------------------------------------* 数据返回 *----------------------------------------------------------------*/ return success(result); } }
Ruby
UTF-8
2,567
2.546875
3
[ "BSD-3-Clause" ]
permissive
# WSDL4R - Creating class code support from WSDL. # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'soap/mapping' require 'soap/mapping/typeMap' require 'xsd/codegen/gensupport' module WSDL module SOAP module ClassDefCreatorSupport include XSD::CodeGen::GenSupport def create_class_name(qname) if klass = basetype_mapped_class(qname) ::SOAP::Mapping::DefaultRegistry.find_mapped_obj_class(klass).name else safeconstname(qname.name) end end def basetype_mapped_class(name) ::SOAP::TypeMap[name] end def dump_method_signature(operation) name = operation.name.name input = operation.input output = operation.output fault = operation.fault signature = "#{ name }#{ dump_inputparam(input) }" str = <<__EOD__ # SYNOPSIS # #{name}#{dump_inputparam(input)} # # ARGS #{dump_inout_type(input).chomp} # # RETURNS #{dump_inout_type(output).chomp} # __EOD__ unless fault.empty? faultstr = (fault.collect { |f| dump_inout_type(f).chomp }).join(', ') #removed extra << str <<__EOD__ # RAISES # #{faultstr} # __EOD__ end str end def dq(ele) ele.dump end def ndq(ele) ele.nil? ? 'nil' : dq(ele) end def sym(ele) ':' + ele end def dqname(qname) qname.dump end private def dump_inout_type(param) if param message = param.find_message params = "" message.parts.each do |part| name = safevarname(part.name) if part.type typename = safeconstname(part.type.name) params << add_at("# #{name}", "#{typename} - #{part.type}\n", 20) elsif part.element typename = safeconstname(part.element.name) params << add_at("# #{name}", "#{typename} - #{part.element}\n", 20) end end unless params.empty? return params end end "# N/A\n" end def dump_inputparam(input) message = input.find_message params = "" message.parts.each do |part| params << ", " unless params.empty? params << safevarname(part.name) end if params.empty? "" else "(#{ params })" end end def add_at(base, str, pos) if base.size >= pos base + ' ' + str else base + ' ' * (pos - base.size) + str end end end end end
C++
UTF-8
3,116
2.890625
3
[]
no_license
#include "resource_manager.hpp" #include "file.hpp" #include "log.hpp" using std::string; // ResourceManager::GetInstance().FindResource(filename).c_str() bool FileExists(const std::string& filename) { FILE* fp = fopen(filename.c_str(), "rb"); if (fp != NULL) { fclose(fp); return true; } else { return false; } } ResourceManager& ResourceManager::GetInstance() { static ResourceManager instance; return instance; } ResourceManager::ResourceManager() { AddResourcePath("."); } void ResourceManager::AddResourcePath(const std::string& path) { resourcePaths.push_back(path); } std::string* ResourceManager::SearchResource(const std::string& resourceName) { std::string foundResource; if(!ResourceExists(resourceName, foundResource)) { SetError("The resource %s could not be found", resourceName.c_str()); return NULL; } return new string(foundResource); } bool ResourceManager::ResourceExists(const std::string& resourceName, std::string& foundResource) { for(const std::string& path : resourcePaths ) { std::string resourcePath = File::AppendPaths(path, resourceName); if(FileExists(resourcePath)) { foundResource = resourcePath; return true; } } foundResource = ""; return false; } bool ResourceManager::PathExists(const std::string& path) { for (const std::string& upperPath : resourcePaths) { std::string resourcePath = File::AppendPaths(upperPath, path); if (File::PathExists(resourcePath)) { return true; } } return false; } bool ResourceManager::ResourceExists(const std::string& resourceName) { std::string placeHolder; return ResourceExists(resourceName, placeHolder); } std::string ResourceManager::LocateAndReadResource(const std::string& resourcePath) { std::string* fullResourcePath = ResourceManager::GetInstance().SearchResource(resourcePath); if(!fullResourcePath) { PrintErrorExit(); } File *f = File::Load(resourcePath, FileModeReading); if(!f) { PrintErrorExit(); } return f->GetFileContents(); } File* ResourceManager::OpenResourceForReading(const std::string& resourcePath) { std::string* fullResourcePath = ResourceManager::GetInstance().SearchResource(resourcePath); if(!fullResourcePath) { return NULL; } File *f = File::Load(resourcePath, FileModeReading); if(!f) { return NULL; } return f; } ShaderProgram* ResourceManager::LoadShader( string vertexShaderPath, string fragmentShaderPath, std::vector<string> defines) { string vertexSource = ResourceManager::LocateAndReadResource(vertexShaderPath); string fragmentSource = ResourceManager::LocateAndReadResource(fragmentShaderPath); for(size_t i = 0; i < defines.size(); ++i) { vertexSource = string("#define ") + defines[i] + string("\n\n") + vertexSource; fragmentSource = string("#define ") + defines[i] + string("\n\n") + fragmentSource; // LOG_I("append: %s", (string("#define ") + defines[i] + string("\n\n")).c_str() ); } return ShaderProgram::Load(vertexSource, fragmentSource); }
Markdown
UTF-8
3,898
3.421875
3
[]
no_license
# CSC-2710 Hashing Project Authors: Nick Greiner, Matt Ray, Brysen Allen, Sam Mycroft https://github.com/NickGreiner/CSC-2710-Hashing-Project # The Assignment Hash functions and hash tables are one of the most powerful tools in computer science. When well implemented, they can take a complex large search space and reduce its complexity by a huge factor and in many cases even to O(1). I would like for you to work together in teams of three to apply hash-based techniques to creating a solution to problem you choose. At the most basic level this could consist of a simple system that improves the speed of finding a simple record in a set of data. There are certainly much more interesting applications available. In class we discussed how the technology can be applied to ensure the integrity of a sent message and dramatically speed the performance of spell checkers. A simple Internet search will yield a vast range of problem spaces where these techniques have proved effective. An ideal project would be one that would take some real world problem space and creatively use hashbased techniques to solve the problem or improve performance. The more interesting problem you choose the more you will get out of the assignment. # Team Based Work Working in teams is the norm in almost all work environments. Part of the assignment will be managing the strengths and weaknesses that are going to be part of any team. At the end of the project, each team member will be asked to anonymously assign each of their team members a rating and review. This peer review will be a portion of each student’s final grade for the project. # Presenting the Work Another aspect of programing that will be encountered in a work environment is the need to present work and programmatic solutions to complex problems to supervisors and peers. Often times the main visibility you will have to high level supervisors where you work is when you are presenting a project you have completed. This is a chance for you to shine and get noticed for career advancement. Being an effective presenter is also an important skill when multiple teams need to coordinate. Each team member will be responsible for presenting a portion of the project. The presentations will require three parts with one of the three team members being responsible for each of the three parts. # At a minumum, your presentation should include these three sections 1.) A description of the problem space that the team chose to explore. This presentation will include describing the hash-based approach the team took to try and solve the problem. 2.) A presentation and walkthrough of the code that was written by the team. 3.) A final analysis of the success of the team’s approach and solution. If the team’s program failed why did it do so. In computer science, it is quite normal for an attempted solution to fail to fully achieved the targeted goals. Some of the most successful software ever created has been built on the foundation of a few previous failed attempts where teams tried a solution and failed, but they gained valuable knowledge into why a certain approach will not work. # Written Report The final portion of this assignment will be a brief written report of your team’s work that will describe and analyze material similar to what was presented in the team’s presentations. One to two pages will be sufficient, but there is no limit. Again, this is a very important skill for all of you to develop. Often times hugely important decisions such as whether you are given a large project or whether your current project is cancelled will hinge entirely on the final decision that is made by a division head, where the only contact you will have is through a report you have written. # Project Due Date Your work will be due at the start of class on November 23, and your presentations will be given in class that day.
C++
UTF-8
1,799
2.859375
3
[]
no_license
#include <VL53L0X.h> #include <Wire.h> VL53L0X sensorL; VL53L0X sensorR; VL53L0X sensorArray[] = { sensorL, sensorR }; long int distance; int sensorLreset = 8; int sensorRreset = 7; int pwm; void setup() { // put your setup code here, to run once: Wire.begin(); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); //reset all sensors by pulling shutdownpins low and high (HIGH = active) digitalWrite(sensorLreset, LOW); digitalWrite(sensorRreset, LOW); delay(10); digitalWrite(sensorLreset, HIGH); digitalWrite(sensorRreset, HIGH); delay(10); //keep Left sensor on by pulling Right LOW, assign new adress digitalWrite(sensorRreset, LOW); sensorArray[0].init(); sensorArray[0].setAddress(0x30); sensorArray[0].setTimeout(500); //repeat on Right Sensor digitalWrite(sensorRreset, HIGH); sensorArray[1].init(); sensorArray[1].setAddress(0x31); sensorArray[1].setTimeout(0); Serial.begin(9600); } void loop() { long int distanceL; long int distanceR; // put your main code here, to run repeatedly: distanceL = leesWaarde(sensorArray[0]); distanceR = leesWaarde(sensorArray[1]); stuurRichting(distanceL, distanceR); } int stuurRichting(int long distanceL, int long distanceR) { distance = ((abs(75 - distanceL) + abs(75 - distanceR)) / 2); if (distanceL < 70 && distanceR > 80) { pwm = map(distance, 0, 75, 0, 100); Serial.println(pwm); return pwm; } else if ( distanceL > 80 && distanceR < 70) { pwm = map(distance, 0, 75, 0, -100); Serial.println(pwm); return pwm; } else if (distanceL > 70 && distanceL < 80) { pwm = 0; return pwm; } } int leesWaarde(VL53L0X sensor) { int waarde; waarde = sensor.readRangeSingleMillimeters(); return waarde; }
C++
UTF-8
990
3.390625
3
[]
no_license
#include <string> using namespace std; class Solution { public: string getPermutation(int n, int k) { // 更优的找规律做法 int factorial[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; string result = ""; string nums[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9"}; // 防止溢出 // 然而题目限制了不会溢出 k = k % factorial[n]; k = k==0? factorial[n]: k; while (n > 0) { int index = (k-1)/factorial[n-1]; result = result + nums[index]; k = k - index*factorial[n-1]; for(int i=index; i<n; i++) nums[i] = nums[i+1]; n--; } return result; // 常规的迭代做法 string res = ""; while(n>0) res = to_string(n--) + res; while(--k>0) res = getNext(res); return res; } string getNext(string str) { // 求下个全排列的值 return str; } };
JavaScript
UTF-8
320
2.78125
3
[]
no_license
function camelize(str) { let splited = str .split("-") .map((word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)) .join(""); return splited; } camelize('background-color') == 'backgroundColor'; camelize('list-style-image') == 'listStyleImage'; camelize('-webkit-transition') == 'WebkitTransition';
Markdown
UTF-8
2,580
2.828125
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: "If-None-Match 在刷票软件中的应用" subtitle: "那些刷票的骚操作" date: 2018-11-07 author: "ms2008" header-img: "img/post-bg-universe.jpg" catalog: true tags: - HTTP typora-root-url: .. --- **优化系统的极限就是不发送任何请求,这一点通常使用缓存来实现**。例如,在一些流量非常大 WEB 的系统中,我们通常会在源站前面启用 CDN。这样用户直接访问的是 CDN 中的缓存内容,降低真实服务端的压力。 ![](/img/in-post/WEB-CDN.png) 同样服务端在输出响应时,可以通过响应头输出一些与缓存有关的信息,从而达到少发或不发请求的目的。 例如,服务端可以通过响应头里的 `Last-Modified`(最后修改时间) 或者 `ETag`(内容特征) 标记实体。浏览器会存下这些标记,并在下次请求时带上 `If-Modified-Since`: 上次 `Last-Modified` 的内容或 `If-None-Match`: 上次 `ETag` 的内容,询问服务端资源是否过期。如果服务端发现并没有过期,直接返回一个状态码为 304、正文为空的响应,告知浏览器使用本地缓存;如果资源有更新,服务端返回状态码 200、新的 `Last-Modified`、`Etag` 和正文。 <u>这样就解释了为什么我们在刷票的时候,明明看到有票,但是却无法下单(实际上已经没票了,你看到的只是缓存信息)</u>。所以如何绕过 CDN 拿到余票的最新信息,成为了抢票成功与否的关键。有一些刷票软件开辟了个新的思路:通过伪造 `If-None-Match` 头来跳过 CDN 缓存,尽快获取源站的最新数据。 `If-None-Match` 是一个条件式请求首部,对应校验的源站头部为 `ETag`,当且仅当服务器上没有任何资源的 `ETag` 属性值与这个首部中所列出的相匹配的时候,才会对请求进行相应的处理(有文件则响应200),如果匹配会直接给304(文件没有修改)。<u>如果源站也没有`ETag`这个头,这样 CDN 的缓存文件也没法校验这个头信息,当终端发起的请求中带这个头信息时,CDN 会将这样的请求回源去校验</u>。 分析完了原理,屏蔽这些刷票软件也变得非常简单:就是在 CDN 上配置策略,删掉 `If-None-Match`、`If-Modified-Since` 这些请求头,再进行后续的处理。实际上拦截效果也非常好: ![](/img/in-post/HTTP-If-None-Match.jpg) *** ### 参考文献 - [Nginx 配置之性能篇](https://imququ.com/post/my-nginx-conf-for-wpo.html)
Ruby
UTF-8
1,433
3.265625
3
[]
no_license
require "./Board.rb" require "./Human_Player.rb" require 'socket' $hostname = 'localhost' #'199.241.200.213' $port = 8081 class Game def play(mode) board = Board.new color = :white socket = get_socket(mode) puts "lol" until board.done? system "clear" p mode board.render if (mode == :server) == (color == :white) sequence = [] begin puts "Your go!" puts "Enter a move sequence like this: [[1,3],[[2,4]]]" puts "Note that coordinates require the column's index before the row's" data = STDIN.gets.chomp start, sequence = eval(data) starting_piece = board[start] p starting_piece end until starting_piece.valid_move_seq?(sequence) socket.puts(data) else data = socket.gets end start, sequence = eval(data) starting_piece = board[start] if starting_piece || starting_piece.color = color board[start].perform_moves(sequence) end if color == :white color = :black else color = :white end end end def get_socket(mode) if mode == :server server = TCPServer.open($port) socket = server.accept else begin socket = TCPSocket.open($hostname, $port) rescue => error retry end end socket end end g = Game.new g.play(ARGV[0].to_sym)
Python
UTF-8
888
3.234375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SincDeltaFcn.py This script shows how a sinc^2 becomes a delta-function in the long-time limit. Origin: CHE 525, S21, Light-matter interaction lectures Author: Tom Allison """ # %% # Preliminaries =============================================================== import numpy as np import matplotlib.pyplot as plt # %% # Define functions ============================================================ def cn(delta,t): return 1*(1-np.exp(1j*delta*t))/(delta) # %% # Make Plots ================================================================== delta = np.linspace(-5,5,300) times = [5,30] fig = plt.figure() ax = plt.axes() for t in times: ax.plot(delta,cn(delta,t)*np.conj(cn(delta,t)), label = 't = ' + str(t)) #ax.set_ylim(-1,600) ax.set_xlabel('$\Delta = \omega_{n0} - \omega$ [arb. units]') ax.legend() ax.grid()
JavaScript
UTF-8
294
3.703125
4
[ "Apache-2.0" ]
permissive
function giveMeVal(secondFr){ var firstFr =5; function myResult(){ return secondFr/firstFr; } return myResult; } var firstValue= giveMeVal(5); var secondValue= giveMeVal(10); var thirdValue= giveMeVal(15); console.log(firstValue()); console.log(secondValue()); console.log(thirdValue());
Java
UTF-8
1,773
2.640625
3
[]
no_license
package common; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class TestAnnotationTransformerListener implements IAnnotationTransformer { private static HSSFSheet excelSheet; private static HSSFWorkbook excelBook; @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { // TODO Auto-generated method stub annotation.setEnabled(false); try { for (String testcaseName : getTestcaseName("Test")) { if (testMethod.getName().equals(testcaseName)) { annotation.setEnabled(true); System.out.println(testMethod.getName() + " is running"); break; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private ArrayList<String> getTestcaseName(String excelSheetName) throws IOException { ArrayList<String> testcaseName = new ArrayList<>(); try { FileInputStream file = new FileInputStream(new File(Constant.reportFilePath)); excelBook = new HSSFWorkbook(file); excelSheet = excelBook.getSheet(excelSheetName); for (int i = 1; i <= excelSheet.getLastRowNum(); i++) { testcaseName.add(excelSheet.getRow(i).getCell(0).getStringCellValue()); } excelBook.close(); file.close(); } catch (FileNotFoundException e) { System.out.println("Could not read the Excel sheet"); e.printStackTrace(); } return testcaseName; } }
Ruby
UTF-8
979
2.734375
3
[]
no_license
module Api class StocksController < APIController PAST_30_DAYS = { start_date: Time::now-(24*60*60*30), end_date: Time::now } MAX_QUERY_RESULTS = 10 def index query = params[:q] @stocks = if query.present? Stock.search query, MAX_QUERY_RESULTS else [] end end def show @stock = Stock.find(params[:id]) @quotes = quotes(params[:id]) end def quotes(symbol) id = 0 YahooFinance.historical_quotes(symbol, PAST_30_DAYS).map do |quote| id += 1 open = quote.open.to_f close = quote.close.to_f high = quote.high.to_f low = quote.low.to_f { id: id, avg: (open + close + high + low) / 4, open: open, close: close, high: high, low: low, date: quote.trade_date, volume: quote.volume.to_i } end end end end
Java
UTF-8
643
2.234375
2
[]
no_license
package cn.phoenixuzoo.oauth2service.domain; import java.math.BigDecimal; public class Item { private String itemName; private BigDecimal amount; private TimePeriod period; public void setItemName(String itemName) { this.itemName = itemName; } public String getItemName() { return itemName; } public void setAmount(BigDecimal amount) { this.amount = amount; } public BigDecimal getAmount() { return amount; } public void setPeriod(TimePeriod period) { this.period = period; } public TimePeriod getPeriod() { return period; } }