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
Java
UTF-8
738
3.09375
3
[]
no_license
package graph; import java.util.Comparator; public class Edge { int startIndex; int endIndex; int weight; public Edge(int startIndex, int endIndex, int weight) { this.startIndex = startIndex; this.endIndex = endIndex; this.weight = weight; } public int getWeight() { return weight; } public void setStartIndex(int startIndex) { this.startIndex = startIndex; } public void setEndIndex(int endIndex) { this.endIndex = endIndex; } public void setWeight(int weight) { this.weight = weight; } public int getStartIndex() { return startIndex; } public int getEndIndex() { return endIndex; } }
Python
UTF-8
4,370
2.8125
3
[]
no_license
import statistics import numpy as np import simpy import random import matplotlib.pyplot as plt from tabulate import tabulate random.seed(123) interarrival_frequency = [ [5, 1], [6, 3], [7, 6], [8, 7], [9, 9], [10, 10], [11, 11], [12, 11], [13, 11], [14, 9], [15, 7], [16, 6], [17, 5], [18, 4] ] unload_time = [ [9, 20], [10, 22], [11, 19], [12, 16], [13, 10], [14, 8], [15, 3], [16, 2] ] # Preparação dos dados def prep_data(data): sum = 0 for a in interarrival_frequency: sum += a[1] for i in range(len(data)): data[i].append(data[i][1] / sum) data[i].append(data[i][2] + data[i - 1][3] if i > 0 else data[i][2]) def get_value(data): value = random.random() for a in data: if a[3] > value: return a[0] return data[-1][0] shipsTable=[] class Ship: prep_data(interarrival_frequency) prep_data(unload_time) def __init__(self, env, docks, id_ship): # A well-known solutions to a deadlock is to allocate resources in some globally defined order self.env, self.docks, self.id = env, sorted(docks, key=id), id_ship self.waitedTime = 0 self.interval = 0 self.unloading = 0 self.waiting_times = [] env.process(self.run_life_cicle()) def get_docks(self): self.log("request first fork") dock1_rq = self.docks[0].request() yield dock1_rq self.log("Obtained the two docks") return dock1_rq def release_docks(self, fork1_rq): self.docks[0].release(fork1_rq) self.log("The docks were released") def run_life_cicle(self): while True: start_waiting = self.env.now arrival_time = self.env.now T0 = get_value(interarrival_frequency) # Mean arrival time T1 = get_value(unload_time) # Mean unloading time # arrivals time arrivals_time = random.expovariate(1 / T0) yield self.env.timeout(arrivals_time) # Getting hungry get_docks_process = self.env.process(self.get_docks()) docks1_rq = yield get_docks_process self.waitedTime = self.env.now - start_waiting # unloading time unloading_time = random.expovariate(1 / T1) yield self.env.timeout(unloading_time) self.interval = arrivals_time self.unloading = unloading_time self.release_docks(docks1_rq) self.waiting_times = self.env.now - arrival_time def log(self, message): # print(f"@{self.env.now} Philosopher {self.id} - {message}") pass # def print_stats(self): # if self.waiting_times: # average_wait = statistics.mean(self.waiting_times) # minutes, frac_minutes = divmod(average_wait, 1) # return round(minutes) # else: # print("No data to present.") def simulate(n_ships, time): env = simpy.Environment() # A fork is a reusable resource that should not be shared. docks = [simpy.Resource(env, capacity=1)] # Instantiate ships and assign them two docks (left and right) ships = Ship(env, docks, n_ships) env.run(until=time) shipsTable.append([n_ships, ships.interval, ships.waitedTime, ships.unloading, ships.waiting_times]) # print(shipsTable) return # sum(ship.waitedTime for ship in ships) / n_ships def main(max_ships, time, filename): X = range(1, max_ships +1) for n in X: simulate(n, time) unloading = 0 size = 0 arrival=0 queue1 = 0 total1 = 0 for i in shipsTable: queue1 += i[2] arrival += i[1] total1 += i[4] #descarga unloading += i[3] size += 1 print("Media de tempos de fila") print(queue1 / size) print("media descarga") print(unloading/size) print("Media de tempos de chegada") print(arrival/size) print("Media de tempos no porto") print(total1 / size) print(tabulate(shipsTable)) if __name__ == "__main__": max_ships = 20 time = 20000 filename = "../imgs/ships_3.jpg" main(max_ships, time, filename)
Markdown
UTF-8
1,381
2.890625
3
[ "MIT" ]
permissive
# BrainRust: an x86_64 BrainFuck JIT in Rust BrainRust is an interpreter and JIT for the [BrainFuck][bf] programming language. The interpreter is available on all platforms supported by Rust, while the JIT is for x86_64 only. It performs high-level optimizations that provide a 3x increase in performance for both JIT and interpreter, while the JIT provides a > 5x increase over the interpreter. [bf]: https://en.wikipedia.org/wiki/Brainfuck ## Supported optimizations * Straight-line sequences of mutation operations are simplified. Adjustments of the tape head are merged into a single adjustment at the end of the block. Modifications to the tape are merged into a single add / subtract / set operation per tape offset that performs the aggregate of all modifications to that location within the block. This allows sequences such as `>>+<<` to be converted to `Add(1, 1)`, and `->>+>>` to be represented as `Add(-1, 0), Add(1, 2), Move(4)`. * Loops that adjust the location under the tape head by a fixed amount, such as `[>++<-]`, can be recognized as multiplications by the value under the tape head. `[-]` zeroing the location under the tape head is covered by this optimization. ## Future optimizations * Loops that iterate a fixed number of times can be detected. * Constant propagation can be performed based on the initially-zeroed contents of the tape.
Python
UTF-8
310
3.015625
3
[]
no_license
#!/usr/bin/env python import sys lines = sys.stdin.readlines() if 0 < len(lines): m = int(lines[0].split()[4]) p = 0 i = 0 while i < len(lines): if m < int(lines[i].split()[4]): p = i m = int(lines[i].split()[4]) i = i + 1 print " ".join(lines[p].split()[5:])
PHP
UTF-8
2,311
2.578125
3
[ "MIT" ]
permissive
<?php namespace Feft\AddressBundle\Tests; use Feft\AddressBundle\Entity\Country; use Feft\AddressBundle\Entity\Locality; use Feft\AddressBundle\Entity\Region; class RegionTest extends \PHPUnit_Framework_TestCase { public function testSettersAndGetters() { $region = new Region(); $region->setName("śląskie"); $this->assertSame("śląskie", $region->getName()); $country = new Country("France", "FR"); $region->setCountry($country); $this->assertSame($country, $region->getCountry()); $locality = new Locality(); $locality->setName("Paris"); $region->addLocality($locality); $lion = new Locality(); $lion->setName("Lion"); $region->addLocality($lion); $this->assertCount(2, $region->getLocalities()); $region->removeLocality($locality); $this->assertCount(1, $region->getLocalities()); $this->assertNull($region->getId()); } public function testAddRegion() { $regions = array( "dolnośląskie", "kujawsko-pomorskie", "lubelskie", "lubuskie", "łódzkie", "małopolskie", "mazowieckie", "opolskie", "podkarpackie", "podlaskie", "pomorskie", "śląskie", "świętokrzyskie", "warmińsko-mazurskie", "wielkopolskie", "zachodniopomorskie" ); $country = new Country(); $country->setName("Poland"); foreach ($regions as $r) { $region = new Region(); $region->setName($r); #separate object for removeElement test if ($r == "wielkopolskie") { $region2 = new Region(); $region2->setName($r); $country->addRegion($region2); } else { $country->addRegion($region); } } $this->assertCount(16, $country->getRegions()); $i = 0; foreach ($country->getRegions() as $r) { $this->assertSame($regions[$i++], $r->getName()); } $country->getRegions()->removeElement($region2); $this->assertCount(15, $country->getRegions()); } }
Swift
UTF-8
3,237
2.9375
3
[ "Apache-2.0" ]
permissive
// // File.swift // FlatbufferSwift // // Created by Veasna Sreng on 2/14/17. // // import Foundation // Data extension helper extension Data { public func get<T>(at: Int, withType: T.Type) -> T? { let numberOfByte = at + MemoryLayout<T>.stride if count <= numberOfByte || numberOfByte < 1 { return nil } // TODO: investigate this option. Which cause memory allocation increate as it seem no deallocation has been perform return withUnsafeBytes { (ptr: UnsafePointer<T>) -> T in return ptr.advanced(by: (at/MemoryLayout<T>.stride)).pointee } } public func getInteger<T: Integer>(at: Int) -> T { let numberOfByte = at + MemoryLayout<T>.stride if count <= numberOfByte || numberOfByte < 1 { return 0 } let copyCount = MemoryLayout<T>.stride var bytes: [UInt8] = [UInt8](repeating: 0, count: copyCount) copyBytes(to: &bytes, from: at ..< Data.Index(at + copyCount)) return UnsafePointer(bytes).withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } public func getFloatingPoint<T: FloatingPoint>(at: Int) -> T { let numberOfByte = at + MemoryLayout<T>.stride if count <= numberOfByte || numberOfByte < 1 { return 0 } let copyCount = MemoryLayout<T>.stride var bytes: [UInt8] = [UInt8](repeating: 0, count: copyCount) copyBytes(to: &bytes, from: at ..< Data.Index(at + copyCount)) return UnsafePointer(bytes).withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } public func getByte(at: Int) -> Int8 { return getInteger(at: at) } public func getUnsignedByte(at: Int) -> UInt8 { return getInteger(at: at) } public func getShort(at: Int) -> Int16 { return getInteger(at: at) } public func getUsignedShort(at: Int) -> UInt16 { return getInteger(at: at) } public func getInt(at: Int) -> Int32 { return getInteger(at: at) } public func getUnsignedInt(at: Int) -> UInt32 { return getInteger(at: at) } public func getLong(at: Int) -> Int64 { return getInteger(at: at) } public func getUnsignedLong(at: Int) -> UInt64 { return getInteger(at: at) } public func getVirtualTaleOffset(at: Int) -> Int { return Int(getShort(at: at)) } public func getOffset(at: Int) -> Int { return Int(getInt(at: at)) } public func getFloat(at: Int) -> Float { return getFloatingPoint(at: at) } public func getDouble(at: Int) -> Double { return getFloatingPoint(at: at) } public func getArray(at: Int, count: Int, withType: UInt8.Type) -> [UInt8]? { var bytes: [UInt8] = [UInt8](repeating: 0, count: count) copyBytes(to: &bytes, from: at ..< Data.Index(at + count)) return bytes } } // String helper to extract Character by index of a string extension String { subscript (i: Int) -> Character { return self[self.characters.index(self.startIndex, offsetBy: i)] } }
Swift
UTF-8
2,503
2.84375
3
[ "MIT" ]
permissive
// // DistinctTests.swift // DBBBuilder-Demo-OSXTests // // Created by Dennis Birch on 3/5/19. // Copyright © 2019 Dennis Birch. All rights reserved. // import XCTest @testable import DBBBuilder class DistinctTests: XCTestCase { var dbManager: DBBManager? override func setUp() { super.setUp() dbManager = CommonTestTask.defaultTestManager(tables: [Person.self, Company.self, Project.self]) } override func tearDown() { super.tearDown() CommonTestTask.deleteDBFile(dbManager: dbManager) } func testDistinctSelect() { guard let manager = dbManager else { XCTFail() return } let firstName = "John" let lastName = "Doe" let daddyAge = 35 let billyAge = 7 let sallyAge = 5 let spouseAge = 33 let daddy = Person(firstName: firstName, lastName: lastName, age: daddyAge, dbManager: manager) let child1 = Person(firstName: "Billy", lastName: "Doe", age: billyAge, dbManager: manager) let child2 = Person(firstName: "Sally", lastName: "Doe", age: sallyAge, dbManager: manager) let spouse = Person(firstName: "Mary", lastName: "Doe", age: spouseAge, dbManager: manager) var saved = child1.saveToDB() saved = child2.saveToDB() XCTAssertTrue(saved) saved = spouse.saveToDB() XCTAssertTrue(saved) let daddyNickNames = ["Daddy", "Johnny"] daddy.nicknames = daddyNickNames daddy.children = [child1, child2] daddy.spouse = spouse saved = daddy.saveToDB() XCTAssertTrue(saved) var options = DBBQueryOptions.options(sortColumns: [Person.Keys.lastName], distinct: true) guard let results = Person.instancesWithOptions(options, manager: manager) as? [Person] else { XCTFail() return } XCTAssertEqual(results.count, 1) options.conditions = ["\(Person.Keys.lastName) = 'Doe'"] options.propertyNames = [Person.Keys.lastName] guard let does = Person.instancesWithOptions(options, manager: manager) as? [Person] else { XCTFail() return } XCTAssertEqual(does.count, 1) guard let firstDoe = does.first else { XCTFail() return } XCTAssertEqual(firstDoe.lastName, "Doe") } }
Python
UTF-8
3,313
2.90625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Fri May 05 19:26:13 2017 @author: YANGz1J """ import smtplib from email.mime.text import MIMEText from email.utils import formataddr from email.mime.multipart import MIMEMultipart my_sender='networkexperiment0@163.com' # 发件人邮箱账号 my_pass = 'qwer1234' # 发件人邮箱授权码 my_user='networkexperiment0@163.com' # 收件人邮箱账号,我这边发送给自己 def mail(): ret=True try: msg=MIMEText('计算机网络邮件客户实验','plain','utf-8')#plain是指显示纯文本 msg['From']=formataddr(["YANGz1J",my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To']=formataddr(["YANGz1J",my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 msg['Subject']="计算机网络邮件客户实验" # 邮件的主题,也可以说是标题 server=smtplib.SMTP("smtp.163.com", 25) # 发件人邮箱中的SMTP服务器,端口是25 server.set_debuglevel(1) server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(my_sender,[my_user,],msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret=False return ret def mail_Enclosure(): ret =True try: msg = MIMEMultipart() msg['From']=formataddr(["YANGz1J",my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To']=formataddr(["YANGz1J",my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 msg['Subject']="计算机网络邮件客户实验" # 邮件的主题,也可以说是标题 #邮件正文内容 msg.attach(MIMEText('这是计算机网络邮件客户实验 邮件发送测试……', 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 TaylorSwift.jpg 文件 att1 = MIMEText(open('TaylorSwift.jpg', 'rb').read(), 'base64', 'utf-8')#base64表示MIME的编码方式,是一种8bite编码方式 att1["Content-Type"] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = 'attachment; filename="TaylorSwift.jpg"' msg.attach(att1) server=smtplib.SMTP("smtp.163.com", 25) # 发件人邮箱中的SMTP服务器,端口是25 server.set_debuglevel(1) server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(my_sender,[my_user,],msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret=False return ret ret=mail() if ret: print("邮件发送成功") else: print("邮件发送失败") ret=mail_Enclosure() if ret: print("邮件发送成功") else: print("邮件发送失败")
Python
UTF-8
4,491
2.53125
3
[]
no_license
#!/usr/bin/python # encoding=utf-8 from utils import * from FuncWindow import CFuncWindow, CRegisterDlg, CForgotPassword class CMainWindow(gtk.Window): def __init__(self): super(CMainWindow, self).__init__(gtk.WINDOW_TOPLEVEL) self.fixed = gtk.Fixed() self.func_fixed = gtk.Fixed() self.init_window() self.login_btn = gtk.Button('登录') self.exit_btn = gtk.Button('关机') self.username_entry = gtk.Entry() self.password_entry = gtk.Entry() self.login = False self.__conf = CConfig(os.getcwd()+ "/conf.ini") self.user_name = self.__conf.get('user_info', 'user_name') self.password = self.__conf.get('user_info', 'password') self.init_login_window() self.init_func_window() def init_window(self): self.set_modal(True) self.set_decorated(False) self.connect("destroy", gtk.main_quit) self.set_position(gtk.WIN_POS_CENTER) self.set_size_request(WINDOW_X_SIZE, WINDOW_Y_SIZE) self.set_keep_above(True) self.set_title("医药管理系统") image = new_image_from_name("bg.jpg") self.fixed.put(image, 0, 0) self.add(self.fixed) def switch_ui(self): if not self.login: self.fixed.set_no_show_all(0) self.func_fixed.set_no_show_all(1) self.fixed.show_all() self.func_fixed.hide() else: self.fixed.set_no_show_all(1) self.func_fixed.set_no_show_all(0) self.fixed.hide() self.func_fixed.show_all() def init_func_window(self): image = new_image_from_name('bg.jpg') self.func_fixed.put(image, 0, 0) def init_login_window(self): label_size_x = 100 label_size_y = 30 entry_size_x = 300 entry_size_y = 30 start_x = (WINDOW_X_SIZE-label_size_x-entry_size_x)/2 start_y = (WINDOW_Y_SIZE)/2 user_label = gtk.Label('用户名:') user_label.set_size_request(label_size_x, label_size_y) self.fixed.put(user_label, start_x, start_y) self.username_entry.set_size_request(entry_size_x, entry_size_y) self.fixed.put(self.username_entry, start_x+100, start_y) start_y += 40 password_label = gtk.Label('密码:') password_label.set_size_request(label_size_x, label_size_y) self.fixed.put(password_label, start_x, start_y) self.password_entry.set_size_request(entry_size_x, entry_size_y) self.password_entry.set_visibility(False) self.fixed.put(self.password_entry, start_x+100, start_y) start_y += 40 start_x += 320 self.login_btn.set_size_request(80, 30) self.login_btn.connect("clicked", self.btn_cb, "login") self.fixed.put(self.login_btn, start_x, start_y) start_x -= 90 self.exit_btn.set_size_request(80, 30) self.exit_btn.connect("clicked", self.btn_cb, "shutdown") self.fixed.put(self.exit_btn, start_x, start_y) start_x -= 90 _btn = gtk.Button('忘记密码') _btn.set_size_request(80, 30) _btn.connect("clicked", self.btn_cb, "forgot_password") self.fixed.put(_btn, start_x, start_y) start_x -= 90 _btn = gtk.Button('注册') _btn.set_size_request(80, 30) _btn.connect("clicked", self.btn_cb, "register") self.fixed.put(_btn, start_x, start_y) def btn_cb(self, widget, opt): if "shutdown" == opt: os.system("shutdown -h now") elif "login" == opt: self.login_system() elif "forgot_password" == opt: CForgotPassword(self, self.__conf) elif "register" == opt: CRegisterDlg(self, self.__conf) def login_system(self): _password = self.password_entry.get_text() if _password == "" or self.username_entry.get_text() == "": CNotifyDlg('请输入用户名和密码') return self.password = self.__conf.get('user_info', 'password') self.user_name = self.__conf.get('user_info', 'user_name') if self.user_name != self.username_entry.get_text(): CNotifyDlg('用户名或密码不正确') return if self.password != _password: CNotifyDlg('密码不正确') return CFuncWindow(self) def run(self): self.show_all() gtk.main()
Markdown
UTF-8
3,672
3.15625
3
[ "MIT" ]
permissive
# Console This is a **Repl** (read-execute-print-loop) cross-platform text-based console for the *Pyro* system. Note that it starts with a local Server. Then it creates and connects a Peer to the server. The Peer is then used to connect to other Peers. This includes when running the app as a sole process. In this case, the Peer is connected to the Server and the Server is connected to the Peer. Just that the Peer connects to the Server on the same machine. This means that you can connect multiple Consoles to each other. It can connect to and remotely execute code on other peers in the domain. It can also be connected to by any other node. There is currently no security or ideas of users or permissions. There are two main languages used: [Pi](../../Library/Pi) and [Rho](../../Library/Rho). You can switch between them by typing `pi` or `rho` at the prompt. Whatever you enter at the prompt is sent to and executed in the context shown by the prompt. By default, this is the local machine. Typing `help` or `?` provides a simple help message. Press control-C to quit. ## Commands There isn't really a 'list of commands'. The language used exposes the .Net runtime so you can access pretty much everything. The syntax of *Pi* and *Rho* are explained in their relative locations. ## Description This is a C# program that creates a REPL (Read-Eval-Print Loop) console for the Pyro programming language. The console can connect to and enter into other consoles. Here is a brief overview of the code: * Namespace imports: Various namespaces are imported for execution context, language, and networking. * Program class: This class inherits from AppCommon.AppCommonBase. Constants and variables: ListenPort is the port number the console listens on for incoming connections. _peer is an instance of IPeer for connecting to other peers. _context is an instance of ExecutionContext for translation. * Main method: The entry point of the console application. It creates a new Program instance and calls the Repl method. * Program constructor: Initializes the execution context, starts a peer, sets up the peer, and runs initialization scripts. * SetupPeer method: Sets up event handlers for the _peer. * StartPeer method: Starts the peer, sets up the local execution context, and registers classes. * RunInitialisationScripts method: Placeholder for running initialization scripts like ~/.pyrorc.{pi,rho}. * Repl method: Main loop of the console that reads input, executes it, and writes the data stack. * WritePrompt method: Writes the prompt to the console. * GetInput method: Reads input from the user. * PreProcess method: Handles special input commands for help, language switching, and leaving the current context. * Execute method: Translates and executes the input in the current context. * OnConnected method: Event handler called when connected to a client. * WriteDataStackContents method: Writes the contents of the data stack to the console. * WriteDataStack method: Writes the data stack of the current context to the console. * ShowHelp method: Displays help information about the console. * Shutdown method: Shuts down the console, stops the peer, and exits the program. In summary, this is a console application for the Pyro language that allows users to enter code, execute it in the local or remote context, and display the results. It uses an internal TCP connection between the input and the processor, such that multiple servers can be used separately or simultaniously. Furthermore, the Console can 'Enter' a remote Peer and interact with it directly. ## TODO * Replicate remote data-stack. * Allow for remote object references.
Java
UTF-8
1,692
2.21875
2
[]
no_license
package Selinium; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Alerthandling { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\seleniumdriver\\chromedriver.exe"); WebDriver driver =new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.toolsqa.com/handling-alerts-using-selenium-webdriver/"); Thread.sleep(3000); ///html/body/div[1]/div[5]/div[2]/div/div/p[3]/button driver.findElement(By.xpath("//a[@id='cookie_action_close_header']")).click();////*[@id="cookie_action_close_header"] //Alert alerthandling = driver.switchTo().alert(); //alerthandling.accept(); //Thread.sleep(2000); driver.findElement(By.xpath("/html/body/div[1]/div[5]/div[2]/div/div/p[3]/button")).click(); Alert alerthandling1 = driver.switchTo().alert(); //alerthandling.dismiss(); String alertbox =alerthandling1.getText(); alerthandling1.dismiss(); System.out.println(alertbox); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"content\"]/p[7]/button")).click(); Alert alertb =driver.switchTo().alert(); String get= alertb.getText(); alertb.accept(); System.out.println(get); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"content\"]/p[10]/button")).click(); Alert popup = driver.switchTo().alert(); popup.sendKeys("juneeth"); String pop = popup.getText(); popup.accept(); System.out.println(pop); } }
JavaScript
UTF-8
1,368
3
3
[]
no_license
import * as actionTypes from './actions'; const initilState = { counter: 0, results: [] } const reducer = (state = initilState, action) => { if (action.type === 'INCREMENT') { let newState = Object.assign({}, state); newState.counter = state.counter + 1; return newState; } if (action.type === actionTypes.DECREMENT) { return { ...state, counter: state.counter - 1 } } if (action.type === actionTypes.ADD) { return { ...state, counter: state.counter + action.val } } if (action.type === actionTypes.SUBTRACT) { return { ...state, counter: state.counter - action.val } } if (action.type === actionTypes.STORE_RESULT) { return { ...state, results: state.results.concat({id: new Date(),value: state.counter}) } } if (action.type === actionTypes.DELETE_RESULT) { // let id = action.id; // const newArr = [...state.results]; // newArr.splice(id, 1); const updatedArray = state.results.filter((result, index) => { return action.id !== index; }) return { ...state, results: updatedArray } } return state; } export default reducer;
Python
UTF-8
1,175
3.21875
3
[ "MIT" ]
permissive
""" This module contains the interface for the class that stores the prototypes of some baseline. This class can be used to compare the prototypes obtained at the end of the online 'Seqclu' algorithm, where the number of identical prototypes divided by the total number of prototypes can be used as evaluation metric. """ from abc import ABC, abstractmethod from typing import List, Optional class IBaselinePrototypes(ABC): @staticmethod @abstractmethod def getPrototypes(experimentName: str) -> Optional[List[List[str]]]: """ This method returns the prototypes that were obtained after executing some baseline algorithm. These prototypes can be compared to the prototypes obtained at the end of the online 'SeqClu' algorithm, where the number of identical prototypes divided by the total number of prototypes can be used as evaluation metric. :param experimentName: The name of the experiment for which the prototypes need to be retrieved. :return: The prototypes obtained after executing some experiment identified by the experiment name. """ pass
Markdown
UTF-8
20,965
3
3
[ "MIT" ]
permissive
--- title: "[Day24] JS: javascript blackjack game" preview: "javascript OOP" permalink: "/articles/2019-03-26-js_blackjack" date: 2019-03-26 09:56:00 layout: post tags: - "note" - "front-end" - "javascript" comments: true --- 本篇會使用`jQuery` + `ES6`寫撲克牌小遊戲21點。一起來玩玩看吧! <!-- more --> <[點我進入網頁版完成品](../public/note/jsdemo/24-blackjack.html)> --- 目錄: * abstact {:toc} --- # 前置作業: 確定遊戲規則 * 發2張牌給玩家,發一張牌給莊家 * 玩家決定再拿牌(hit)或打住(stand) * 玩家選擇stand後輪到莊家 * 玩家或莊家先達21點者贏 * 超過21點輸,遊戲結束 * 玩家如果跟莊家同點數,平手,遊戲結束 * 如果連發5張都還沒超過21點,也算是贏,遊戲結束 * 不論花色,1-10點代表牌面上數字,J, Q, K表示10點,A表示1或11點 # 遊戲點數試算 * [3, J] = 3 + 10 = 13點 * [A, 2, 3] = 11 + 2 + 3 = 16點 * [6, 8, A] = 6 + 8 + 1(因為算11點就爆了) = 15點 * [A + K] = 11 + 10 = 21點 # Single Responsibility Principle (SRP) 單一職責原則:一個函數只做一件事 # Part 1. 準備遊戲 ## A. 初始化卡牌 `initCards()` 0.啟動 ```javascript $(document).ready { } ``` 1.為尚未翻開的牌面設計圖案 ```javascript $(document).ready { initCards(); } ``` 2.抓html內的元素,換圖案 * 先把功能寫出來 javascript版本 ```javascript //莊家牌 $(document).ready(function(){ // 抓所有div為card let alldealerCards = alldealerCards.forEach( card => { card.innerHTML = '㊎'; }); //玩家牌 let allyourCards = document.querySelectorAll('.yourCard'); allyourCards.forEach( card => { card.innerHTML = '㊖'; }); }); ``` * 獨立為function `initCards()` ```javascript // 程式碼寫在這裡! $(document).ready(function(){ initCards(); }); //把換牌面設計的功能獨立出來 function initCards(){ // 抓所有div為card let alldealerCards = document.querySelectorAll('.dealerCard'); alldealerCards.forEach( card => { card.innerHTML = '㊎'; }); let allyourCards = document.querySelectorAll('.yourCard'); allyourCards.forEach( card => { card.innerHTML = '㊖'; }); } ``` 把這段javascript版本註解掉,改寫成jQuery版本 ```javascript let alldealerCards = document.querySelectorAll('.dealerCard'); alldealerCards.forEach( card => { card.innerHTML = '㊎'; }); let allyourCards = document.querySelectorAll('.yourCard'); allyourCards.forEach( card => { card.innerHTML = '㊖'; }); ``` jQuery版本 ```javascript $('.card div').html('㊎'); $('.yourCard').html('㊖'); ``` * 小結 ```javascript $(document).ready(function(){ initCards(); }); function initCards(){ $('.dealerCard').html('㊎'); $('.yourCard').html('㊖'); } ``` ## B. 初始化按鈕 `initButtons()` 1.html按鈕區的id: 寫在`action-new-game`裡: ```html <footer class="action"> <input type="button" id="action-hit" class="action-button" value="Hit!" disabled> <input type="button" id="action-stand" class="action-button" value="Stand" disabled> <input type="button" id="action-new-game" class="action-button" value="New Game"> </footer> ``` 2.`New Game`按鈕: addEventListener javascript * addEventListener聽`click`的動作,用`console.log`測試 ```javascript $(document).ready(function(){ initCards(); // 綁定在New Game按鈕上面 document.querySelector('#action-new-game').addEventListener('click', evt => { console.log('hi'); }); }); ``` * 初始化按鈕 ```javascript initButtons(); ``` * 寫成獨立的function `initButtons(){}`: ```javascript $(document).ready(function(){ initCards(); initButtons(); }); function initButtons(){ document.querySelector('#action-new-game').addEventListener('click', evt => { console.log('hi'); }); } ``` jQuery版本 把這段javascript寫法 ```javascript document.querySelector('#action-new-game').addEventListener('click', evt => { }); ``` 改寫為 jQuery寫法 ```javascript $('#action-new-game').click( function(evt) { }); ``` 再簡寫為箭頭函數 複習: [js筆記:函數 function](https://hackmd.io/nAM4U5BsSJ6acOLVG5_yhw) ```javascript $('#action-new-game').click( evt => { }); ``` * 小結 ```javascript $(document).ready(function(){ initCards(); initButtons(); }); // 把換牌面設計的功能獨立出來 function initCards(){ // 抓所有div為card $('.dealerCard').html('㊎'); $('.yourCard').html('㊖'); } // 按完按鈕,重啟新牌局 function initButtons() { $('#action-new-game').click( evt => { console.log('hi'); }); } ``` ## C. 啟動遊戲 `newGame()` 1.`initButtons()` 串連到 `newGame()` 寫出`newGame()`架構: ```javascript function newGame() { console.log('new game'); } ``` 2.讓`initButtons()`去呼叫 ```javascript function initButtons() { $('#action-new-game').click( evt => { newGame(); }); } ``` 因為只有一行,可以省略大括弧: ```javascript function initButtons() { $('#action-new-game').click( evt => newGame() ); } ``` * 小結 ```javascript $(document).ready(function(){ initCards(); initButtons(); }); // 把換牌面設計的功能獨立出來 function initCards(){ $('.dealerCard').html('㊎'); $('.yourCard').html('㊖'); } // 按完按鈕,重啟新牌局 function initButtons() { $('#action-new-game').click( evt => newGame() ); } function newGame() { console.log('new game'); } ``` ## D. 建立牌組 `buildDeck()` 開始和朋友玩撲克牌遊戲的條件:**首先要有一副牌!!** 1.4種花色,每一種花色有13張牌 = 52張牌 => 兩層for迴圈 ```javascript function buildDeck(){ for(let suit = 1; suit <= 4; suit++) { for(let number = 1; number <= 13; number++){ } } ``` 2.用物件導向OOP做出卡牌的模組 ```javascript //用OOP做卡牌 class Card { constructor(suit, number){ this.suit = suit; this.number = number; } } ``` 3.完用模組做牌,迴圈內跑 ```javascript let c = new Card(suit, number); ``` 4.建立牌箱陣列(建了牌組之後,要有容器放牌) ```javascript let deck[]; ``` 5.迴圈內,把產生的物件用`push()`方法塞進陣列 ```javascript deck.push(c); ``` 6.在`newGame()`裡檢驗是否會回傳建立卡牌 ```javascript function newGame() { console.log(buildDeck()); } ``` * 小結 ```javascript function buildDeck(){ let deck = []; // 建立空陣列放牌 for(let suit = 1; suit <= 4; suit++) { for(let number = 1; number <= 13; number++){ let c = new Card(suit, number); //做出52種牌組 deck.push(c); //塞進去盒子 } } return deck; } //用OOP做卡牌 class Card { constructor(suit, number){ this.suit = suit; this.number = number; } } function newGame() { console.log(buildDeck()); } ``` console ```javascript 0: Object { suit: 1, number: 1 } 1: Object { suit: 1, number: 2 } 2: Object { suit: 1, number: 3 } 3: Object { suit: 1, number: 4 } 4: Object { suit: 1, number: 5 } 5: Object { suit: 1, number: 6 } 6: Object { suit: 1, number: 7 } 7: Object { suit: 1, number: 8 } 8: Object { suit: 1, number: 9 } ... 48: Object { suit: 4, number: 10 } 49: Object { suit: 4, number: 11 } 50: Object { suit: 4, number: 12 } 51: Object { suit: 4, number: 13 } ``` ## E. 洗牌 `shuffle()` javascript並沒有洗牌的功能 google 關鍵字: javascript array shuffle 1.尋找他人寫過的function ```javascript // 洗牌 //https://gomakethings.com/how-to-shuffle-an-array-with-vanilla-js/ var shuffle = function (array) { var currentIndex = array.length; var temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }; ``` 2.把建好的牌組洗牌 ```javascript function newGame() { console.log( shuffle ( buildDeck() ) ); } ``` * 小結 console內成功印出52張亂數牌 ```javascript 0: Object { suit: 3, number: 13 } 1: Object { suit: 4, number: 13 } 2: Object { suit: 3, number: 3 } 3: Object { suit: 2, number: 13 } 4: Object { suit: 4, number: 11 } 5: Object { suit: 2, number: 12 } 6: Object { suit: 3, number: 12 } 7: Object { suit: 2, number: 2 } 8: Object { suit: 1, number: 6 } 9: Object { suit: 4, number: 3 } 10: Object { suit: 3, number: 8 } ``` ## F. 發牌給玩家 `deal()` ### 重點:就算是簡單的一行程式碼,也有包成函數的價值! 1.啟動遊戲的時候,就有 `deck` = 那疊洗好的牌 ```javascript // Part 3 啟動遊戲: function newGame() { //console.log(shuffle(buildDeck())); deck = shuffle( buildDeck() ); } ``` 2.按照順序發牌: 用`shift();`取得第一張牌 ```javascript // Part 6 發牌: function deal() { return deck.shift(); } ``` 3.定義莊家和玩家的牌組 ```javascript let yourDeck = []; let dealerDeck = []; ``` 4.從啟動遊戲的funciton發牌,push一張給玩家,一張給莊家,再一張給玩家 ```javascript // Part 3 啟動遊戲: function newGame() { //console.log(shuffle(buildDeck())); deck = shuffle(buildDeck()); yourDeck.push(deal()); dealerDeck.push(deal()); yourDeck.push(deal()); } ``` ## G. 增加卡牌功能 `class Card{}` 1.計算卡牌的點數 `cardPoint() {}` ```javascript cardPoint() { switch(this.number) { case 1: return 11; case 11: case 12: case 13: return 10; defult: return this.number; } ``` 2.呈現花色樣式 ```javascript cardSuit() { switch(this.suit) { case 1: return '♠'; case 2: return '♥'; case 3: return '♦'; case 4: return '♣'; } } ``` ## H. 畫面顯示牌組 `renderGameTable()` Show Hand吧! 1.用jQuery把HTML值指定為成玩家抽到的牌,並顯示出來 ```javascript // Part 8 在畫面看到發牌的樣子 function renderGameTable() { //用迴圈的方式把已經抽到的牌翻出來 yourDeck.forEach((card, i) => { //把抓到的卡牌 0, 1, 2, 3, 4 用索引值[i]塞進去`.{i + 1}` let theCard = $(`#yourCard${i + 1}`); //兩層$, 內層放索引值,外層代表jQuery的取值方式 theCard.html('A'); //測試 }); } ``` 2.`cardShowNumber()`卡牌數字轉成A, J, Q, K ```javascript cardShowNumber() { switch(this.number) { case 1: return 'A'; case 11: return 'J'; case 12: return 'Q'; case 13: return 'K'; defult: return this.number; } } ``` 3.秀出卡牌 ```javascript // Part 8 在畫面看到發牌的樣子 function renderGameTable() { //用迴圈的方式把已經抽到的牌翻出來 yourDeck.forEach((card, i) => { //把抓到的卡牌 0, 1, 2, 3, 4 用索引值[i]塞進去`.{i + 1}` let theCard = $(`#yourCard${i + 1}`); //兩層$, 內層放索引值,外層代表jQuery的取值方式 theCard.html(card.cardShowNumber()); }); } ``` 4.秀出花色 如何把span的欄位抓出來? `<div class="card"><span></span><div class="yourCard" id="yourCard1"></div></div>` ### 把某標籤的前一個標籤抓出來`.prev()` 抓`<div class="yourCard></div>"`的前一個元素的寫法: ```javascript theCard.prev().html(card.cardSuit()): ``` 莊家與玩家的牌組: ```javascript function renderGameTable() { //用迴圈的方式把已經抽到的牌翻出來 yourDeck.forEach((card, i) => { let theCard = $(`#yourCard${i + 1}`); theCard.html(card.cardShowNumber()); theCard.prev().html(card.cardSuit()); }); dealerDeck.forEach((card, i) => { let theCard = $(`#dealerCard${i + 1}`); theCard.html(card.cardShowNumber()); theCard.prev().html(card.cardSuit()); }); } ``` ## I. 計算卡牌目前得分 `calcPoint(deck)` 1.迴圈算分數 ```javascript //Part9 用迴圈算牌的分數 function calcPoint(deck) { let point = 0; deck.forEach(card => { point += card.cardPoint(); }) return point; //記得要return分數回去 } ``` 2.一開始大家都是0點 ```javascript let yourPoint = 0; let dearlerPoint = 0 ``` 3.呈現分數 ```javascript function renderGameTable() { ... yourPoint = calcPoint(yourDeck); dealerPoint = calcPoint(dealerDeck); $('.your-cards h1').html(`你 (${yourPoint}點) `); $('.dealer-cards h1').html(`莊家 (${dealerPoint}點) `); } ``` ## J. 遊戲重置 `resetGame()` 1.把所有變數歸零 ```javascript function resetGame() { deck = []; yourDeck = []; dealerDeck = []; yourPoint = 0; dearlerPoint = 0; } ``` 2.在啟動遊戲前先reset game ```javascript // Part 3 啟動遊戲: function newGame() { // 初始化遊戲 resetGame(); ... } ``` # Part 2. 遊戲進行中 ## Q. 利用`inGame` 變數,標示遊戲進行中 1.inGame 布林值 ```javascript inGame = true //當new game按下去之後,處於遊戲狀態中 ``` 2.在新牌局內,標示遊戲進行中 ```javascript function newGame() { resetGame(); deck = shuffle(buildDeck()); yourDeck.push(deal()); dealerDeck.push(deal()); yourDeck.push(deal()); //遊戲進行中 inGame = true; //把玩家和莊家的卡牌畫出來 renderGameTable(); } ``` ## K. 設定另外兩個按鈕屬性 `.attr()` 1.按下`New Game`按鈕,啟動另外兩顆按鈕功能 ```javascript if (inGame) { $('#action-hit').attr('disabled', false); $('#action-stand').attr('disabled', false); } else { $('#action-hit').attr('disabled', true); $('#action-stand').attr('disabled', true); } } ``` 2.按鈕的打開與否,和inGame反向。 以上`if-else`可以簡寫為: ```javascript $('#action-hit').attr('disabled', !inGame); $('#action-stand').attr('disabled', !inGame); ``` 3.initButton() 設定另外兩顆按鈕的event ```javascript function initButtons() { $('#action-new-game').click( evt => newGame() ); //玩家叫牌 $ ('#action-hit').click( evt => { evt.preventDefault(); yourDeck.push(deal()); //從deal()移動一張牌推進去陣列 renderGameTable(); //再畫一次 }); //玩家停止叫牌,換莊家 $ ('#action-stand').click( evt => { evt.preventDefault(); dealerDeck.push(deal()); //從deal()移動一張牌推進去陣列 renderGameTable(); //再畫一次 }); } ``` ## L. 遊戲結束的條件: 任何一方>=21點 ```javascript //遊戲結束的條件 function renderGameTable() { ... if (yourPoint >= 21 || dearlerPoint >=21) { inGame = false; //hit & stand按鈕關閉 } } ``` ## M. 點數精算 Ace牌可以等於1點或11點,調整`calc()` ```javascript function calcPoint(deck) { let point = 0; deck.forEach(card => { point += card.cardPoint(); }) // M. 精算點數 if (point > 21) { deck.forEach(card => { if (card.cardShowNumber() == 'A'){ point -= 10; // A從11點變1點 } }) } return point; } ``` ## N. 莊家行動 `dealerRound()` 1.先把流程用中文寫下來 ```javascript //1. 發牌 //2. 如果點數 >= 玩家,結束,莊家贏 //3. 如果 < 玩家,重複1 //4. >21點,結束,玩家 ``` 2.使用while迴圈判斷 ```javascript function dealerRound() { while(true) { //whie: 不知道要做幾次, 無窮迴圈 dealerPoint = calcPoint(dealerDeck); if (dealerPoint < yourDeck) { dealerDeck.push(deal()); } else { break; } } inGame = false; //跳出後,結束遊戲 renderGameTable(); } ``` 3.以上由`dealerRound()`在`stand`的button區塊呼叫 ```javascript function initButtons() { ... $ ('#action-stand').click( evt => { evt.preventDefault(); dealerDeck.push(deal()); //再從deal()移動一張牌推進去陣列 //renderGameTable(); //因為dealerRound已經再畫一次,此行註解掉 dealerRound(); }); } ``` # Part 3. 遊戲結束,判斷贏家 1.設定贏家變數 ```javascript let winner = 0; // 0: 未定, 1: 玩家贏 2: 莊家贏 3: 平手 ``` 2.贏家重置 ```javascript function resetGame() { deck = []; yourDeck = []; dealerDeck = []; yourPoint = 0; dearlerPoint = 0; winner = 0; //不要忘記這段! } ``` 3.畫牌桌的時候,就把誰贏誰輸顯示出來 ```javascript function renderGameTable() { ... switch(true){ // 0. 比點數大小 case dealerPoint > yourPoint: winner = 2; break; // 1. 如果玩家21點,玩家贏 case yourPoint == 21: winner = 1; break; case dearlerPoint == 21: winner = 2; break; // 2. 如果玩家點數爆 case yourPoint > 21: winner = 2; break; // 3. 如果莊家點數爆 case dealerPoint > 21: winner = 1; break; // 4. 平手 case yourPoint == dealerPoint: winner = 3; break; // 5. 最後再用莊家的點來比點數 case dealerPoint > yourPoint: winner = 2; break; default: winner = 0; break; } } ``` 4. 蓋勝利章 ```javascript switch(winner) { case 1: $('.your-cards').addClass('win'); break; case 2: $('.dealer-cards').addClass('win'); break; case 3: //平手 break; default: break; } ``` # Part 4. 整理程式碼 O. 將`renderGameTable()`拆成小功能 ```javascript= checkWinner(); showWinStamp(); ``` # HTML + CSS 程式結構 html 抽到的牌會放在`<span></span>`區塊 莊家牌組 ```html <section class="dealer-cards zone"> <h1>莊家</h1> <div class="deck"> <div class="card"><span></span><div class="dealerCard" id="dealerCard1"></div></div> <div class="card"><span></span><div class="dealerCard" id="dealerCard2"></div></div> <div class="card"><span></span><div class="dealerCard" id="dealerCard3"></div></div> <div class="card"><span></span><div class="dealerCard" id="dealerCard4"></div></div> <div class="card"><span></span><div class="dealerCard" id="dealerCard5"></div></div> </div> </section> ``` 玩家牌組 ```html <section class="your-cards zone"> <h1>你</h1> <div class="deck"> <div class="card"><span></span><div class="yourCard" id="yourCard1"></div></div> <div class="card"><span></span><div class="yourCard" id="yourCard2"></div></div> <div class="card"><span></span><div class="yourCard" id="yourCard3"></div></div> <div class="card"><span></span><div class="yourCard" id="yourCard4"></div></div> <div class="card"><span></span><div class="yourCard" id="yourCard5"></div></div> </div> </section> ``` 按鈕區 ```html <footer class="action"> <input type="button" id="action-hit" class="action-button" value="Hit!" disabled> <input type="button" id="action-stand" class="action-button" value="Stand" disabled> <input type="button" id="action-new-game" class="action-button" value="New Game"> </footer> ``` CSS 分散對齊 ```css .deck { display: flex; justify-content: space-around; } ``` 勝利效果 ```css h1::after { position: absolute; border: solid 5px #d00; border-radius: 50%; color: #d00; content: '勝'; font-size: 80px; font-weight: bold; padding: 10px; margin: 0; opacity: 0; transform: scale(5); transition: all 0.3s cubic-bezier(0.6, 0.04, 0.98, 0.336); } .win h1::after { opacity: .85; transform: rotate(-15deg) scale(1); z-index: 1000; } ``` # 其他功能練習 1. 新增一個Deck類別,讓Deck可以自行計算分數 2. bug: 避免起始的時候直接輸掉 # 流程圖 flowchart 利用Scalable Vector Graphics (SVG) 可縮放式向量圖檔製作流程圖。 JS Code Flowchart https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart JS Code Flowchart Demo https://bogdan-lyashenko.github.io/js-code-to-svg-flowchart/docs/live-editor/ # 附:撲克牌遊戲所需素材 撲克牌花色: ♠♥♣♦ 圈圈字: ㊀㊁㊂㊃㊄㊅㊆㊇㊈㊉㊊㊋㊌㊍㊎㊏㊐㊑㊒㊓㊔㊕㊖㊗㊘㊙㊚㊛㊜㊝㊞㊟㊠㊡㊢㊣㊤㊥㊦㊧㊨㊩㊫㊬㊭㊮㊯㊰ # 相關連結 [HackMD筆記](https://hackmd.io/b0Bfp09RRZidfpoF3Ad9Mg?view) [CodePen練習](https://codepen.io/tingtinghsu/full/ZZQewG) [網頁版完成品](../public/note/jsdemo/24-blackjack.html){:target"_blank"} [google font](https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300) [陣列的洗牌(shuffle)功能](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array)
C++
UTF-8
5,787
2.703125
3
[ "MIT" ]
permissive
#include <string> #include <networkit/auxiliary/Log.hpp> #include <networkit/dynamics/GraphDifference.hpp> namespace NetworKit { GraphDifference::GraphDifference(const Graph &G1, const Graph &G2) : G1(&G1), G2(&G2) { if (G1.isDirected() != G2.isDirected()) { throw std::runtime_error("Error, either both or none of the graphs must be directed."); } if (G1.isWeighted() != G2.isWeighted()) { throw std::runtime_error("Error, either both or none of the graphs must be weighted."); } } void GraphDifference::run() { hasRun = false; edits.clear(); numNodeAdditions = 0; numNodeRemovals = 0; numNodeRestorations = 0; numEdgeAdditions = 0; numEdgeRemovals = 0; numWeightUpdates = 0; std::vector<bool> marker(G1->upperNodeIdBound(), false); std::vector<edgeweight> neighborWeights(G1->upperNodeIdBound(), 0); // collect node events and edge removals/additions in separate vectors // so we can later put them in the right order: first remove edges, // then remove and add nodes and then add edges. std::vector<GraphEvent> nodeEvents, edgeRemovals, edgeAdditions; node updatedUpperNodeIdBound = G1->upperNodeIdBound(); for (node u = 0; u < G1->upperNodeIdBound() || u < G2->upperNodeIdBound(); ++u) { // First, fix non-common nodes if (!G2->hasNode(u) && G1->hasNode(u)) { nodeEvents.emplace_back(GraphEvent::NODE_REMOVAL, u); ++numNodeRemovals; } else if (G2->hasNode(u) && !G1->hasNode(u)) { if (u < G1->upperNodeIdBound()) { nodeEvents.emplace_back(GraphEvent::NODE_RESTORATION, u); ++numNodeRestorations; } else { while (u > updatedUpperNodeIdBound) { // add and remove the same node immediately until we reach // the desired node id. nodeEvents.emplace_back(GraphEvent::NODE_ADDITION); nodeEvents.emplace_back(GraphEvent::NODE_REMOVAL, updatedUpperNodeIdBound); ++updatedUpperNodeIdBound; } // add the actually wanted node. nodeEvents.emplace_back(GraphEvent::NODE_ADDITION); ++updatedUpperNodeIdBound; ++numNodeAdditions; } } // mark neighbors of current node in G1 if (G1->hasNode(u)) { G1->forNeighborsOf(u, [&](node v, edgeweight w) { if (G1->isDirected() || u <= v) { TRACE("Marking neighbor of ", u, " in G1 ", v); marker[v] = true; neighborWeights[v] = w; } }); } // unmark common neighbors, detect edge additions if (G2->hasNode(u)) { G2->forNeighborsOf(u, [&](node v, edgeweight w) { // for undirected graphs, edges are only added in one direction unless // the other node does not exist in G1 (edges where both nodes do not // exist in G1 have been added above). if (G1->isDirected() || u <= v) { if (v < G1->upperNodeIdBound() && marker[v]) { if (neighborWeights[v] != w) { edgeAdditions.emplace_back(GraphEvent::EDGE_WEIGHT_UPDATE, u, v, w); ++numWeightUpdates; } TRACE("Unmarking neighbor of ", u, " in G2 ", v); marker[v] = false; } else { edgeAdditions.emplace_back(GraphEvent::EDGE_ADDITION, u, v, w); ++numEdgeAdditions; } } }); } if (G1->hasNode(u)) { // detect edge removals, unset the remaining neighbor markers G1->forNeighborsOf(u, [&](node v) { TRACE("Checking again (", u, ",", v, ")"); if (G1->isDirected() || u <= v) { TRACE("Edge (", u, ",", v, ") is considered"); if (marker[v]) { TRACE("Deleting (", u, ",", v, ")"); edgeRemovals.emplace_back(GraphEvent::EDGE_REMOVAL, u, v); ++numEdgeRemovals; marker[v] = false; } } }); } } numEdits = numNodeRemovals + numNodeAdditions + numNodeRestorations + numEdgeRemovals + numEdgeAdditions + numWeightUpdates; edits.swap(edgeRemovals); edits.reserve(nodeEvents.size() + edgeAdditions.size()); edits.insert(edits.end(), nodeEvents.begin(), nodeEvents.end()); edits.insert(edits.end(), edgeAdditions.begin(), edgeAdditions.end()); hasRun = true; } const std::vector<GraphEvent> &GraphDifference::getEdits() const { assureFinished(); return edits; } count GraphDifference::getNumberOfEdits() const { assureFinished(); return numEdits; } count GraphDifference::getNumberOfNodeAdditions() const { assureFinished(); return numNodeAdditions; } count GraphDifference::getNumberOfNodeRemovals() const { assureFinished(); return numNodeRemovals; } count GraphDifference::getNumberOfNodeRestorations() const { assureFinished(); return numNodeRestorations; } count GraphDifference::getNumberOfEdgeAdditions() const { assureFinished(); return numEdgeAdditions; } count GraphDifference::getNumberOfEdgeRemovals() const { assureFinished(); return numEdgeRemovals; } count GraphDifference::getNumberOfEdgeWeightUpdates() const { assureFinished(); return numWeightUpdates; } } // namespace NetworKit
Python
UTF-8
240
2.65625
3
[ "MIT" ]
permissive
def ResponseMaker(status, message, contentName = False, content = False): response = {} response["status"] = status response["message"] = message if(contentName and content): response[contentName] = content return response
C#
UTF-8
935
2.5625
3
[ "MIT" ]
permissive
using Native.Csharp.App.Gameplay.CharacterUtil.Classes.Template; using Native.Csharp.App.Gameplay.CharacterUtil.Skills; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Native.Csharp.App.Gameplay.CharacterUtil.Classes { /// <summary> /// 战士职业 /// </summary> public class ClassFighter : CharacterClass { private ClassFighter() { HealthPointPerLevel = 10; SkillPointPerLevel = 2; ClassSkills = new List<Type> { typeof(Profession), typeof(Survival) }; } public ClassFighter(Character owner) { Owner = owner; CharacterSkills skills = owner.Properties.Skills; } public override void LevelUp() { throw new NotImplementedException(); } } }
C++
UTF-8
556
2.625
3
[]
no_license
#ifndef FLOOR_H #define FLOOR_H #include <QGraphicsPixmapItem> /*! \class Floor \brief The Floor class represents floor in the game. Floor class defines floor object in the game. Floor is set during initialization of the levels. It is not set through all of the level, so the player can fall. */ class Floor : public QGraphicsPixmapItem { public: Floor(QGraphicsItem *parent = 0); enum { Type = UserType + 2 }; int type() const; bool visible() const; void setVisible(bool visible); bool mVisible; }; #endif // FLOOR_H
Java
UTF-8
775
2.59375
3
[]
no_license
package cn.mccreefei.dao; import cn.mccreefei.model.User; import org.apache.ibatis.annotations.Param; /** * 用户dao接口 */ public interface UserDAO { /** * 以用户名和密码查询用户 * @param name * @param password * @return 存在返回该用户对象,不存在返回null */ public User queryUser(@Param("name") String name,@Param("password") String password); /** * 以用户名查询用户 * @param name * @return 存在该用户名返回用户对象,否则返回null */ public User queryUserByName(String name); /** * 插入一位用户 * @param name * @param password */ public void insertUser(@Param("name") String name,@Param("password") String password); }
C
UTF-8
854
3.9375
4
[]
no_license
/* * Programmer : Josh Booth Date : Mar 22 , 2019 * Instructor : Professor Hou Class : ENGR 120 - 03 * * Approximates the value of e */ #include <stdio.h> /* Includes printf, scanf */ #include <math.h> /* Includes fabs, exp */ /* Threshold for the allowed difference between actual value and approximated value */ #define DIF_THRESHOLD 0.000001 int main(void) { int x = 0; /* Set counting variable to 0 */ double e_approx; /* Approximation of e */ do { x += 1; /* Increment x */ /* Calculate e approximaition */ e_approx = pow((2.0 * x + 1) / (2.0 * x - 1), x); } while(fabs(exp(1) - e_approx) > DIF_THRESHOLD); /* Continue while difference between actual and approximate is above threshold */ /* Print results */ printf("Converged at x = %d, %.7f, exp(1.0) = %.7f\n", x, e_approx, exp(1)); return 0; }
Java
UTF-8
4,253
2.25
2
[]
no_license
package org.mira.companion.Fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import android.util.Log; import org.mira.companion.R; import org.mira.companion.Utils.ExploitWebServer; import butterknife.BindView; import butterknife.ButterKnife; import fi.iki.elonen.NanoHTTPD; /** * A simple {@link Fragment} subclass. */ public class ExploitHostFragment extends Fragment { @BindView(R.id.server_status) TextView server_status; @BindView(R.id.server_ip) TextView server_ip; @BindView(R.id.server_toogle) ToggleButton server_toogle; public ExploitHostFragment() { // Required empty public constructor } ExploitWebServer exploitWebServer; boolean serverStatus = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_exploit_host, container, false); ButterKnife.bind(this, v); ButterKnife.setDebug(true); // exploitWebServer = ExploitWebServer(); // exploitWebServer = new ExploitWebServer(9913); exploitWebServer = new ExploitWebServer(8080); try { exploitWebServer.start(); } catch (Exception ex) { server_status.setText("Server was started at : "); server_ip.setText(exploitWebServer.getHostname()+":"+exploitWebServer.getListeningPort()); Log.e("Exploit Server", "Server wasn't started - Exception : "+ex.getMessage()); } if(exploitWebServer.isAlive()) { Log.e("Exploit Server", "Server is Live"+exploitWebServer.toString()); } server_toogle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { serverStatus = !serverStatus; server_toogle.setChecked(serverStatus); if(serverStatus) { try { exploitWebServer.start(); } catch (Exception ex) { Log.e("Exploit Server", "Server wasn't started - Exception : "+ex.getMessage()); } if(exploitWebServer.wasStarted()) { server_toogle.setText("Turn Off"); server_status.setText("Server was started at : "); server_ip.setText(exploitWebServer.getHostname()+":"+exploitWebServer.getListeningPort()); Toast.makeText(getContext(), "Exploit Server was started...", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Exploit Server couldn't get started. AN error occured", Toast.LENGTH_SHORT).show(); } } else { try { exploitWebServer.stop(); } catch (Exception ex) { Log.e("Exploit Server", "Server hasn't stopped - Exception : "+ex.getMessage()); } if(!exploitWebServer.wasStarted()) { server_toogle.setText("Turn On"); server_status.setText("Server has been stopped ! "); server_ip.setText(""); Toast.makeText(getContext(), "Exploit Server has stopped...", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Exploit Server couldn't stop AN error occured", Toast.LENGTH_SHORT).show(); } } } }); return v; } }
C#
UTF-8
3,612
2.84375
3
[]
no_license
 using System; using System.Drawing; using System.Runtime.CompilerServices; namespace Game.Components { public static class BodyComponentExtensions { public static BodyComponent StrengthInit(this BodyComponent component, int strength) { component.Strength = strength; return component; } public static BodyComponent IntelligenceInit(this BodyComponent component, int intelligence) { component.Intelligence = intelligence; return component; } public static BodyComponent ConstitutionInit(this BodyComponent component, int constitution) { component.Constitution = constitution; return component; } public static BodyComponent DexterityInit(this BodyComponent component, int dexterity) { component.Dexterity = dexterity; return component; } public static BodyComponent CharismaInit(this BodyComponent component, int charisma) { component.Charisma = charisma; return component; } } public static class BaseBodyComponentExtensions { public static void Config(this ref BaseBodyComponent baseBody, int x = 0, int y = 0) { if (baseBody.Head.Size.Width == 0) { baseBody.Head = new HeadPart { Value = 0, Enchantment = 0, Location = new Point(x,y), Size = new Size(10, 10) }; baseBody.Torso = new TorsoPart { Value = baseBody.Torso.Value, Enchantment = baseBody.Torso.Enchantment, Start = new Point(baseBody.Head.Location.X, baseBody.Head.Location.Y + baseBody.Head.Size.Height / 2), }; baseBody.LeftArm = new ArmPart { Value = baseBody.LeftArm.Value, Enchantment = baseBody.LeftArm.Enchantment, Start = new Point(baseBody.Head.Location.X, baseBody.Head.Location.Y + baseBody.Head.Size.Height / 2 + baseBody.Head.Size.Width / 4), }; baseBody.RightArm = new ArmPart { Value = baseBody.LeftArm.Value, Enchantment = baseBody.LeftArm.Enchantment, Start = new Point(baseBody.Head.Location.X, baseBody.Head.Location.Y + (baseBody.Head.Size.Height / 2 + baseBody.Head.Size.Width / 4)), }; baseBody.LeftLeg = new LegPart { Value = 0, Enchantment = 0, Start = Point.Add(baseBody.Head.Location, new Size(0, baseBody.Head.Size.Width * 2)) }; baseBody.RighLeg = new LegPart { Value = 0, Enchantment = 0, Start = Point.Add(baseBody.Head.Location, new Size(0, baseBody.Head.Size.Width * 2)) }; } else { var Head = baseBody.Head; Head.Location = new Point(x, y); baseBody.Head = Head; baseBody.Torso.Start = new Point(x, y + Head.Size.Height / 2); baseBody.Torso.End = new Point(x, y + Head.Size.Height * 2); baseBody.LeftArm.Start = new Point(x, y + Head.Size.Height / 2 + Head.Size.Width / 4); baseBody.LeftArm.End = new Point(x - Head.Size.Width, y + Head.Size.Width); baseBody.RightArm.Start = new Point(x, y + (Head.Size.Height / 2 + Head.Size.Width / 4)); baseBody.RightArm.End = new Point(x + Head.Size.Width, y + Head.Size.Height); } } } }
Python
UTF-8
2,531
2.546875
3
[ "MIT" ]
permissive
# Created by Haorui Chen # Updated by 05/15/2020 import time import json import random from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By # find by name, id, .. from selenium.webdriver.support import expected_conditions as EC def get_peets_coffee(): chrome_options = webdriver.ChromeOptions() driver = webdriver.Chrome( executable_path=r'C:\Users\vipxr\OneDrive\Coding\find_ur_coffee\data_crawling\chromedriver.exe') product_data = {} # peet's coffee # date: 05/21/2020 url_peet = 'https://www.peets.com/coffee/drip-brewing' driver.get(url_peet) for t in range(3): time.sleep(random.randint(2, 3)) driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") product = driver.find_elements_by_class_name("product-link") product_links = [p.get_attribute('href') for p in product] # print('product_links:', len(product_links), '\n', product_links) product_data['peets coffee'] = [] for p_link in product_links: time.sleep(random.randint(2, 5)) cur_product = driver.get(p_link) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "product_addtocart_form")) ) driver.get(p_link) # [name, bio, price, rating, flvr_note, flvr_ctgy, roast_lv, origin] name = driver.find_element_by_class_name('product-name').text short_description = driver.find_element_by_class_name('std').text price = driver.find_element_by_class_name('price').text rating = driver.find_element_by_xpath('//*[@id="BVRRSummaryContainer"]/div/div/div/div/div/div/dl/dd[1]/div/a/span').text flavor_note = driver.find_element_by_xpath('//*[@id="product_addtocart_form"]/div[3]/div/div[3]/div[1]/div').text flavor_category = driver.find_element_by_class_name('flavor').text roast_lv = driver.find_element_by_xpath('//*[@id="product_addtocart_form"]/div[3]/div/div[3]/div[3]/div/div').text product_data['peets coffee'].append({ 'name': name, 'short_description': short_description, 'price': price, 'rating': rating, 'flavor_note': flavor_note, 'flavor_category': flavor_category, 'roast_lv': roast_lv }) with open('coffee_product_data.json', 'w') as outfile: json.dump(product_data, outfile) driver.close() # TODO: def get_starbucks_coffee():
Markdown
UTF-8
537
2.546875
3
[]
no_license
# Entities ##❯ Primitives Basic type is a data type provided by a programming language as a basic building block. References: http://en.wikipedia.org/wiki/Primitive_data_type ##❯ Objects Particular instance of a class where the object can be a combination of variables, functions, and data structures. References: http://en.wikipedia.org/wiki/Object_(computer_science) ##❯ Binary large object (blob) Collection of binary data stored as a single entity. References: https://en.wikipedia.org/wiki/Binary_large_object
C++
UTF-8
7,676
2.953125
3
[ "MIT" ]
permissive
/// @file /// @author David Pilger <dpilger26@gmail.com> /// [GitHub Repository](https://github.com/dpilger26/NumCpp) /// @version 1.1 /// /// @section License /// Copyright 2019 David Pilger /// /// Permission is hereby granted, free of charge, to any person obtaining a copy of this /// software and associated documentation files(the "Software"), to deal in the Software /// without restriction, including without limitation the rights to use, copy, modify, /// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to /// permit persons to whom the Software is furnished to do so, subject to the following /// conditions : /// /// The above copyright notice and this permission notice shall be included in all copies /// or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, /// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR /// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE /// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR /// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. /// /// @section Description /// Functions for working with NdArrays /// #pragma once #include "NumCpp/Core/Error.hpp" #include "NumCpp/Core/Shape.hpp" #include "NumCpp/Core/Types.hpp" #include "NumCpp/NdArray.hpp" #include <string> namespace nc { //============================================================================ // Method Description: /// Integrate along the given axis using the composite trapezoidal rule. /// /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trapz.html /// /// @param inArray /// @param dx: (Optional defaults to 1.0) /// @param inAxis (Optional, default NONE) /// /// @return /// NdArray /// template<typename dtype> NdArray<double> trapz(const NdArray<dtype>& inArray, double dx = 1.0, Axis inAxis = Axis::NONE) noexcept { const Shape inShape = inArray.shape(); switch (inAxis) { case Axis::COL: { NdArray<double> returnArray(inShape.rows, 1); for (uint32 row = 0; row < inShape.rows; ++row) { double sum = 0; for (uint32 col = 0; col < inShape.cols - 1; ++col) { sum += static_cast<double>(inArray(row, col + 1) - inArray(row, col)) / 2.0 + static_cast<double>(inArray(row, col)); } returnArray[row] = sum * dx; } return returnArray; } case Axis::ROW: { NdArray<dtype> arrayTranspose = inArray.transpose(); const Shape transShape = arrayTranspose.shape(); NdArray<double> returnArray(transShape.rows, 1); for (uint32 row = 0; row < transShape.rows; ++row) { double sum = 0; for (uint32 col = 0; col < transShape.cols - 1; ++col) { sum += static_cast<double>(arrayTranspose(row, col + 1) - arrayTranspose(row, col)) / 2.0 + static_cast<double>(arrayTranspose(row, col)); } returnArray[row] = sum * dx; } return returnArray; } case Axis::NONE: { double sum = 0.0; for (uint32 i = 0; i < inArray.size() - 1; ++i) { sum += static_cast<double>(inArray[i + 1] - inArray[i]) / 2.0 + static_cast<double>(inArray[i]); } NdArray<double> returnArray = { sum * dx }; return returnArray; } default: { // this isn't actually possible, just putting this here to get rid // of the compiler warning. return NdArray<double>(0); } } } //============================================================================ // Method Description: /// Integrate along the given axis using the composite trapezoidal rule. /// /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trapz.html /// /// @param inArrayY /// @param inArrayX /// @param inAxis (Optional, default NONE) /// /// @return /// NdArray /// template<typename dtype> NdArray<double> trapz(const NdArray<dtype>& inArrayY, const NdArray<dtype>& inArrayX, Axis inAxis = Axis::NONE) { const Shape inShapeY = inArrayY.shape(); const Shape inShapeX = inArrayX.shape(); if (inShapeY != inShapeX) { THROW_INVALID_ARGUMENT_ERROR("input x and y arrays should be the same shape."); } switch (inAxis) { case Axis::COL: { NdArray<double> returnArray(inShapeY.rows, 1); for (uint32 row = 0; row < inShapeY.rows; ++row) { double sum = 0; for (uint32 col = 0; col < inShapeY.cols - 1; ++col) { const double dx = static_cast<double>(inArrayX(row, col + 1) - inArrayX(row, col)); sum += dx * (static_cast<double>(inArrayY(row, col + 1) - inArrayY(row, col)) / 2.0 + static_cast<double>(inArrayY(row, col))); } returnArray[row] = sum; } return returnArray; } case Axis::ROW: { NdArray<dtype> arrayYTranspose = inArrayY.transpose(); NdArray<dtype> arrayXTranspose = inArrayX.transpose(); const Shape transShape = arrayYTranspose.shape(); NdArray<double> returnArray(transShape.rows, 1); for (uint32 row = 0; row < transShape.rows; ++row) { double sum = 0; for (uint32 col = 0; col < transShape.cols - 1; ++col) { const double dx = static_cast<double>(arrayXTranspose(row, col + 1) - arrayXTranspose(row, col)); sum += dx * (static_cast<double>(arrayYTranspose(row, col + 1) - arrayYTranspose(row, col)) / 2.0 + static_cast<double>(arrayYTranspose(row, col))); } returnArray[row] = sum; } return returnArray; } case Axis::NONE: { double sum = 0.0; for (uint32 i = 0; i < inArrayY.size() - 1; ++i) { const double dx = static_cast<double>(inArrayX[i + 1] - inArrayX[i]); sum += dx * (static_cast<double>(inArrayY[i + 1] - inArrayY[i]) / 2.0 + static_cast<double>(inArrayY[i])); } NdArray<double> returnArray = { sum }; return returnArray; } default: { // this isn't actually possible, just putting this here to get rid // of the compiler warning. return NdArray<double>(0); } } } }
Python
UTF-8
528
2.609375
3
[]
no_license
import requests import json import matplotlib.pyplot as plt # Question 1 rv = [] profile_urls = [ 'https://geosci.uchicago.edu/~kite/doc/geos28600_2020_lab_3/GEOS_38600_Lab_2_Profile_1.txt', 'https://geosci.uchicago.edu/~kite/doc/geos28600_2020_lab_3/GEOS_38600_Lab_2_Profile_2.txt', 'https://geosci.uchicago.edu/~kite/doc/geos28600_2020_lab_3/GEOS_38600_Lab_2_Profile_2.txt' ] for url in profile_urls: r = requests.get(url) txt = r.text txt = txt.split() rv.append(txt) print(rv[0][3:])
Python
UTF-8
1,728
4.125
4
[]
no_license
""" 使用方法:KMP 判断是不是双生词 1.S与S'长度相同 2.将S首尾相接绕成环,再选一个位置切开,顺时针或逆时针能够得到S' 给定一批仅由英文小写字母组成的字符串,询问他们之中是否存在双生词 input: 首先给出测试组数t,表示一共有多少组数据 对于每组数据,第一行为一个整数n,表示一共有多少个字符串。接下来n行,每行一个字符串 output: 对于每组数据,若存在双生词,输出Yeah。若不存在,输出Sad 示例: 3 2 helloworld hdlrowolle 2 helloworld worldhello 2 abcde acbde output: Yeah Yeah Sad 1 2 helloworld worldhello """ def next(p): # m为p的长度 m = len(p) nextList = [-1] * m for i in range(1, m): k = nextList[i-1] while k != -1 and p[i] != p[k]: k = nextList[k] nextList[i] = k + 1 return nextList def kmp(s, p): s = s+s nextP = next(p) i = 0 j = 0 while i < len(s) and j < len(p): if j == -1 or s[i] == p[j]: i += 1 j += 1 else: j = nextP[j] if j == len(p): return True return False def isTwinsWords(wordsList, numWords): for i in range(numWords): for j in range(numWords): if (i != j) and (len(wordsList[i]) == len(wordsList[j])): if kmp(wordsList[i], wordsList[j]) or kmp(wordsList[i], wordsList[j][::-1]): return 'Yean' return 'Sad' t = int(input()) res = [] for i in range(t): n = int(input()) words = [] #第i组词 for j in range(n): words.append(input()) res.append(isTwinsWords(words, n)) print(res)
Java
UTF-8
562
2.078125
2
[]
no_license
package vgomes.marvelheroes.datastorage.helper; import android.util.Log; import io.realm.DynamicRealm; import io.realm.RealmMigration; import io.realm.RealmSchema; import vgomes.marvelheroes.datastorage.consts.DataStorageConstants; /** * Created by victorgomes on 28/06/17. */ public class Migration implements RealmMigration { int version; @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { RealmSchema schema = realm.getSchema(); version = DataStorageConstants.DATABASE_VERSION; } }
C#
UTF-8
1,116
2.578125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MusicController : MonoBehaviour { public List<AudioSource> musicTracks = new List<AudioSource>(); // Use this for initialization void Start () { foreach(AudioSource track in musicTracks) { track.Play(); track.volume = 0; } musicTracks[0].volume = 1; } // Update is called once per frame void Update () { } public void ChooseMusic(int trackNumber) { StopCoroutine("FadeSwap"); StartCoroutine(FadeSwap(musicTracks[trackNumber])); } IEnumerator FadeSwap(AudioSource primarySouce) { List<AudioSource> otherSources = new List<AudioSource>(musicTracks); otherSources.Remove(primarySouce); while (primarySouce.volume < 1) { primarySouce.volume += Time.deltaTime; foreach (AudioSource otherSource in otherSources) { otherSource.volume -= Time.deltaTime; } yield return null; } } }
JavaScript
UTF-8
406
2.796875
3
[ "MIT" ]
permissive
//Fade Out Elements while scrolling //Created by @snkrsnkampa //Link this '.js' file from your html file //Add the class .fade-out to the elements you want to fade-out $(window).scroll(function(){ $(".fade-out").css("opacity", 1 - $(window).scrollTop() / 800); //Decrese the value from '800' to fade-out fast and vice-versa and 0 for no fade effect }); //NOTE: jQuery is required for this script to work
Java
UTF-8
4,255
2.1875
2
[]
no_license
package com.example.ettimadai; import androidx.appcompat.app.AppCompatActivity; import android.app.ActionBar; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; public class VideoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); String newString; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if(extras == null) { newString= null; } else { newString= extras.getString("video"); } } else { newString= (String) savedInstanceState.getSerializable("video"); } if(newString.equals("1")){ VideoView videoview = (VideoView) findViewById(R.id.videoView); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.one); videoview.setVideoURI(uri); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoview); videoview.setMediaController(mediaController); videoview.start(); } else if(newString.equals("2")){ VideoView videoview = (VideoView) findViewById(R.id.videoView); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.two); videoview.setVideoURI(uri); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoview); videoview.setMediaController(mediaController); videoview.start(); } else if(newString.equals("3")){ VideoView videoview = (VideoView) findViewById(R.id.videoView); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.three); videoview.setVideoURI(uri); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoview); videoview.setMediaController(mediaController); videoview.start(); } else if(newString.equals("4")){ VideoView videoview = (VideoView) findViewById(R.id.videoView); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.four); videoview.setVideoURI(uri); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoview); videoview.setMediaController(mediaController); videoview.start(); } else if(newString.equals("5")){ VideoView videoview = (VideoView) findViewById(R.id.videoView); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.five); videoview.setVideoURI(uri); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoview); videoview.setMediaController(mediaController); videoview.start(); } else if(newString.equals("6")){ VideoView videoview = (VideoView) findViewById(R.id.videoView); View view = findViewById(R.id.videoView); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.width =600; view.setLayoutParams(layoutParams); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.six); videoview.setVideoURI(uri); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoview); videoview.setMediaController(mediaController); videoview.start(); } else{ Toast.makeText(this,"There is no Such video",Toast.LENGTH_LONG).show(); } } }
Python
UTF-8
187
3.3125
3
[]
no_license
#BOJ_10870 def fibonacci(n): if n==0: ans=0 elif n==1: ans=1 else: ans= fibonacci(n-2) + fibonacci(n-1) return ans print(fibonacci(int(input())))
C
UTF-8
4,530
3.03125
3
[]
no_license
/* ** PERSONAL PROJECT, 2019 ** gomoku ** File description: ** gomoku swap2 rule */ #include <stdlib.h> #include <stdio.h> #include "../include/gomoku.h" #include "../include/my.h" static int p2_choice(data **game) { char *entry = NULL; size_t buf = 0; int nb[3] = {1, 2, 3}; my_putstr("\n"); my_putstr((*game)->name2); my_putstr(", please choose '1', '2' or '3':\n 1) play with \033[1m"); my_putchar((*game)->p1); my_putstr("\033[0ms\n 2) play with \033[1m"); my_putchar((*game)->p2); my_putstr("\033[0ms and place one piece\n 3) place two pieces and let "); my_putstr((*game)->name1); my_putstr(" choose which piece they want to play with\n"); while (1) { my_putstr("\nChoice: "); if (getline(&entry, &buf, stdin) == END_OF_FILE) { free(entry); return (END_OF_FILE); } if (my_int_isinarray(nb, my_atou(entry), 3)) { buf = my_atou(entry); free(entry); return (buf); } err_invalid_choice(); } } static void play(data **game, uchar whose_turn, int i) { if (i != 2) (*game)->board[(*game)->played_x][(*game)->played_y] = (whose_turn == PLAYER1 ? (*game)->p1 : (*game)->p2); else (*game)->board[(*game)->played_x][(*game)->played_y] = (whose_turn == PLAYER2 ? (*game)->p1 : (*game)->p2); my_putstr(whose_turn == PLAYER1 ? (*game)->name1 : (*game)->name2); my_putstr(" placed a piece on "); my_putnbr((*game)->played_x); my_putchar(','); my_putnbr((*game)->played_y); my_putchar('\n'); my_putstr(" 1234567890123456789 \n"); for (uint i = 0; i < HEIGHT_BOARD; i++) { my_putstr((*game)->board[i]); if (i && i < 20) my_putnbr(i % 10); my_putchar('\n'); } } static int user_play(data *game, uchar whose_turn, int i) { int ret_v; do { ret_v = get_x(&game); } while (ret_v != END_OF_FILE && check_played_x(game) == FAILURE); if (ret_v == END_OF_FILE) return (END_OF_FILE); do { ret_v = get_y(&game); while (ret_v != END_OF_FILE && check_played_xy(game) == FAILURE) { do { ret_v = get_x(&game); } while (ret_v != END_OF_FILE && check_played_x(game) == FAILURE); ret_v = get_y(&game); } } while (ret_v != END_OF_FILE && check_played_xy(game) == FAILURE); if (ret_v == END_OF_FILE) return (END_OF_FILE); play(&game, whose_turn, i); return (SUCCESS); } static int choice3(data *game) { char *entry = NULL; size_t buf = 0; int played = 0; for (uint i = 0; i < 2; i++) { my_putstr("\n"); my_putstr(game->name2); my_putstr(", which player's piece do you want to place ? (1/2) "); while (!played) { if (getline(&entry, &buf, stdin) == END_OF_FILE) return (quit(entry)); if (my_str_isequal(entry, "1\n") || my_str_isequal(entry, "2\n")) played = my_getnbr(entry); } if (user_play(game, PLAYER2, (played == 2 ? 1 : 2)) == END_OF_FILE) return (quit(entry)); played = 0; } my_putstr("\n\n"); my_putstr(game->name1); my_putstr(", which player's piece do you want to play with ? (1/2)\n"); for (int playedd = 0; !playedd;) { if (getline(&entry, &buf, stdin) == END_OF_FILE) return (quit(entry)); if (my_str_isequal(entry, "1\n") || my_str_isequal(entry, "2\n")) { if (my_getnbr(entry) == 2) switch_name(&game); playedd = 1; } } free(entry); return (SUCCESS); } int swap2(data *game) { int ret_v; for (uint i = 0; i < 3; i++) { my_putstr("\n\nIt's "); my_putstr(game->name1); my_putstr("'s turn, placing a '"); my_putchar(i != 2 ? game->p1 : game->p2); my_putstr("':\n"); if (user_play(game, PLAYER1, i) == END_OF_FILE) return (END_OF_FILE); } ret_v = p2_choice(&game); if (ret_v == END_OF_FILE) return (END_OF_FILE); if (ret_v == 1) switch_name(&game); else if (ret_v == 2) { my_putstr("\nIt's "); my_putstr(game->name2); my_putstr("'s turn:\n"); if (user_play(game, PLAYER2, 0) == END_OF_FILE) return (END_OF_FILE); } else if (choice3(game) == END_OF_FILE) return (END_OF_FILE); return (SUCCESS); }
Markdown
UTF-8
5,715
3.71875
4
[]
no_license
##<a name="create-client"></a>Create a Client Connection Create a client connection by creating a `WindowsAzure.MobileServiceClient` object. Replace `appUrl` with the URL to your Mobile App. ``` var client = WindowsAzure.MobileServiceClient(appUrl); ``` ##<a name="table-reference"></a>Work with Tables To access or update data, create a reference to the backend table. Replace `tableName` with the name of your table ``` var table = client.getTable(tableName); ``` Once you have a table reference, you can work further with your table: * [Query a Table](#querying) * [Filtering Data](#table-filter) * [Paging through Data](#table-paging) * [Sorting Data](#sorting-data) * [Inserting Data](#inserting) * [Modifying Data](#modifying) * [Deleting Data](#deleting) ###<a name="querying"></a>How to: Query a Table Reference Once you have a table reference, you can use it to query for data on the server. Queries are made in a "LINQ-like" language. To return all data from the table, use the following: ``` /** * Process the results that are received by a call to table.read() * * @param {Object} results the results as a pseudo-array * @param {int} results.length the length of the results array * @param {Object} results[] the individual results */ function success(results) { var numItemsRead = results.length; for (var i = 0 ; i < results.length ; i++) { var row = results[i]; // Each row is an object - the properties are the columns } } function failure(error) { throw new Error('Error loading data: ', error); } table .read() .then(success, failure); ``` The success function is called with the results. Do not use `for (var i in results)` in the success function as that will iterate over information that is included in the results when other query functions (such as `.includeTotalCount()`) are used. For more information on the Query syntax, refer to the [Query object documentation]. ####<a name="table-filter"></a>Filtering Data on the server You can use a `where` clause on the table reference: ``` table .where({ userId: user.userId, complete: false }) .read() .then(success, failure); ``` You can also use a function that filters the object. In this case the `this` variable is assigned to the current object being filtered. The following is functionally equivalent to the prior example: ``` function filterByUserId(currentUserId) { return this.userId === currentUserId && this.complete === false; } table .where(filterByUserId, user.userId) .read() .then(success, failure); ``` ####<a name="table-paging"></a>Paging through data Utilize the take() and skip() methods. For example, if you wish to split the table into 100-row records: ``` var totalCount = 0, pages = 0; // Step 1 - get the total number of records table.includeTotalCount().take(0).read(function (results) { totalCount = results.totalCount; pages = Math.floor(totalCount/100) + 1; loadPage(0); }, failure); function loadPage(pageNum) { let skip = pageNum * 100; table.skip(skip).take(100).read(function (results) { for (var i = 0 ; i < results.length ; i++) { var row = results[i]; // Process each row } } } ``` The `.includeTotalCount()` method is used to add a totalCount field to the results object. The totalCount field is filled with the total number of records that would be returned if no paging is used. You can then use the pages variable and some UI buttons to provide a page list; use loadPage() to load the new records for each page. You should implement some sort of caching to speed access to records that have already been loaded. ####<a name="sorting-data"></a>How to: Return data sorted Use the .orderBy() or .orderByDescending() query methods: ``` table .orderBy('name') .read() .then(success, failure); ``` For more information on the Query object, refer to the [Query object documentation]. ###<a name="inserting"></a>How to: Insert Data Create a JavaScript object with the appropriate date and call table.insert() asynchronously: ``` var newItem = { name: 'My Name', signupDate: new Date() }; table .insert(newItem) .done(function (insertedItem) { var id = insertedItem.id; }, failure); ``` On successful insertion, the inserted item is returned with the additional fields that are required for sync operations. You should update your own cache with this information for later updates. Note that the Azure Mobile Apps Node.js Server SDK supports dynamic schema for development purposes. In the case of dynamic schema, the schema of the table is updated on the fly, allowing you to add columns to the table just by specifying them in an insert or update operation. We recommend that you turn off dynamic schema before moving your application to production. ###<a name="modifying"></a>How to: Modify Data Similar to the .insert() method, you should create an Update object and then call .update(). The update object must contain the ID of the record to be updated - this is obtained when reading the record or when calling .insert(). ``` var updateItem = { id: '7163bc7a-70b2-4dde-98e9-8818969611bd', name: 'My New Name' }; table .update(updateItem) .done(function (updatedItem) { // You can now update your cached copy }, failure); ``` ###<a name="deleting"></a>How to: Delete Data Call the .del() method to delete a record. Pass the ID in an object reference: ``` table .del({ id: '7163bc7a-70b2-4dde-98e9-8818969611bd' }) .done(function () { // Record is now deleted - update your cache }, failure); ``` <!--HONumber=Apr16_HO1-->
PHP
UTF-8
619
2.671875
3
[]
no_license
<?php session_start(); ?> <html> <style type ="text/css"> p{ text-align : center; } h1{ text-align : center; } </style> <body> <?php if($_POST["q1"] == "b" ){ $_SESSION["score"]++; } if($_POST["q2"] == "a" ){ $_SESSION["score"]++ ;} if($_POST["q3"] == "a" ){ $_SESSION["score"]++ ;} if($_POST["q4"] == "c"){ $_SESSION["score"]++ ;} if($_POST["q5"] == "b"){ $_SESSION["score"]++ ;} echo "<p> Hi " .$_SESSION["username"]. "</p>"; echo "<p> Congrats your score is ".$_SESSION["score"]."</p>"; ?> <a href="user_home.php">Home</a> </html> </body>
C
UTF-8
296
3.4375
3
[]
no_license
//compile: gcc ex_1-6.c //run: ./a.out //Exercise 1-6: Verify that the expression getchar() != EOF is 0 or 1. #include <stdio.h> int main(){ int c; while(c = (getchar() != EOF)) printf("(getchar() != EOF) == %d\n", c); //after EOF detected printf("(getchar() == EOF) == %d", c); }
Java
WINDOWS-1252
3,213
2.171875
2
[]
no_license
/** * ATReference Copyright 2011 Rockefeller Archive Center * All rights reserved. * * This software is free. You can redistribute it and / or modify it under the terms of the Educational Community License (ECL) * version 1.0 (http://www.opensource.org/licenses/ecl1.php) * * This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ECL license for more details about permissions and limitations. * * * ATReference * https://github.com/RockefellerArchiveCenter/ATReference/wiki * * @author Lee Mandell * Date: May 4, 2010 * Time: 2:24:54 PM */ package org.rac.dialogs; import org.archiviststoolkit.dialog.ErrorDialog; import org.archiviststoolkit.dialog.QueryEditorPanel; import org.archiviststoolkit.dialog.QueryField; import org.archiviststoolkit.model.LookupListItems; import org.archiviststoolkit.structure.ATFieldInfo; import org.archiviststoolkit.structure.DatabaseFields; import org.archiviststoolkit.util.ATBeanUtils; import org.archiviststoolkit.util.LookupListUtils; import javax.swing.*; import java.awt.*; import java.beans.IntrospectionException; import java.util.Date; import java.util.Vector; public class QueryFieldRelated extends QueryField { public QueryFieldRelated(DatabaseFields field, Class clazz) { this.fieldName = field.getFieldName(); this.displayFieldName = field.getFieldLabel(); this.tableName = clazz.getName(); //first intercept accession number and resource id for special treatment try { Class fieldType = ATBeanUtils.getPropertyType(clazz, fieldName); if (fieldType == String.class) { ATFieldInfo fieldInfo = ATFieldInfo.getFieldInfo(this.tableName + "." + this.fieldName); Vector<LookupListItems> values = LookupListUtils.getLookupListValues2(fieldInfo.getLookupList()); if (values.size() == 0) { setValueComponent(new QueryEditorRelatedTextPanel()); } else { // JComboBox comboBox = new JComboBox(new DefaultComboBoxModel(values)); // comboBox.setOpaque(false); // comboBox.setMaximumSize(new Dimension(110, 32767)); // set the size so that it shows up properly in subject search // comboBox.setMinimumSize(new Dimension(110, 27)); // setValueComponent(new QueryEditorRelatedTextPanel(comboBox)); } } else if (fieldType == Date.class) { setValueComponent(new QueryEditorRelatedDatePanel()); // } else if (fieldType == Integer.class) { // setValueComponent(new QueryEditorRelatedIntegerPanel(QueryEditorPanel.RETURN_INTEGER_VALUES)); // } else if (fieldType == Long.class) { // setValueComponent(new QueryEditorRelatedIntegerPanel(QueryEditorPanel.RETURN_LONG_VALUES)); // } else if (fieldType == Double.class) { // setValueComponent(new QueryEditorRelatedDoublePanel()); // } else if (fieldType == Boolean.class) { // setValueComponent(new QueryEditorRelatedBooleanPanel()); } } catch (IntrospectionException e) { new ErrorDialog("", e).showDialog(); } } }
PHP
UTF-8
1,942
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php declare(strict_types=1); namespace WoohooLabs\Worm\Examples\Infrastructure\Model; use WoohooLabs\Worm\Examples\Domain\Course; use WoohooLabs\Worm\Examples\Domain\SchoolClass; use WoohooLabs\Worm\Model\AbstractModel; use WoohooLabs\Worm\Model\Relationship\RelationshipInterface; class ClassModel extends AbstractModel { public $id; public $course_id; public $room_id; public $teacher_id; public $students; public $datetime; private ClassStudentModel $classStudentModel; private StudentModel $studentModel; public function __construct(ClassStudentModel $classStudentModel, StudentModel $studentModel) { parent::__construct(); $this->classStudentModel = $classStudentModel; $this->studentModel = $studentModel; } public function getTable(): string { return "classes"; } public function getPrimaryKeys(): array { return [$this->id]; } public function mapClass(Course $course, SchoolClass $class): array { return [ $this->id => $class->getId(), $this->course_id => $course->getId(), $this->room_id => $class->getRoomId(), $this->teacher_id => $class->getTeacherId(), $this->datetime => $class->getDatetime()->format("Y-m-d H:i:s"), ]; } protected function getRelationships(): array { return [ "students" => function (): RelationshipInterface { return $this ->hasManyThrough( $this->id, $this->classStudentModel, $this->classStudentModel->class_id, $this->classStudentModel->student_id, $this->studentModel, $this->studentModel->id ) ->toRelationship(); }, ]; } }
Java
UTF-8
123
1.929688
2
[]
no_license
package org.automation.dojo; /** * Created by Sanja on 03.11.2014. */ public interface Dice { int next(int max); }
C
UTF-8
642
2.734375
3
[]
no_license
/*************************************************************************//** @file queue.h @brief Software Library to make work with a queue @author Marcos Darino (MD) ******************************************************************************/ #ifndef QUEUE_H_ #define QUEUE_H_ #include "os.h" /* queue definition */ #define QUEUE_LEN 1 typedef int queueItem_t; typedef struct { queueItem_t data[QUEUE_LEN]; int count; EventMaskType ev; TaskType task; }queue_t; void queueInit(queue_t * q, EventMaskType e); void queuePut(queue_t * q, queueItem_t d); queueItem_t queueGet(queue_t * q); #endif /* QUEUE_H_ */
TypeScript
UTF-8
445
3.1875
3
[]
no_license
export function sdkInsertAt<T>(array: T[], index: number, newItem: T): T[] { return [...array.slice(0, index), newItem, ...array.slice(index)]; } export function sdkRemoveAt<T>(array: T[], index: number): T[] { return [...array.slice(0, index), ...array.slice(index + 1)]; } export function sdkReplaceAt<T>(array: T[], index: number, item: T): T[] { const newArray = [...array]; newArray.splice(index, 1, item); return newArray; }
C++
UTF-8
211
2.96875
3
[]
no_license
#include <iostream> using namespace std; int main() { int input; cin >> input; if (input % 2 == 0) cout << "Is your name even steven?" << endl; if (input % 2 == 1) cout << "You are an odd ball!"<<endl; }
JavaScript
UTF-8
7,939
2.90625
3
[]
no_license
// App constants const HIDDEN_CLASS = 'hidden'; const TWITCH_API_URL = 'https://api.twitch.tv/kraken/search/streams'; const CLIENT_ID = 'rnol6rl7vokxusycd1dk7rqbddb2nw'; const LIMIT = 10; // App controls const loader = document.getElementById('loader'); const welcomeElement = document.getElementById('welcome_msg'); const notFoundElement = document.getElementById('not_found_msg'); const errorElement = document.getElementById('error_msg'); const streamListElement = document.getElementById('stream_list'); const searchFormElement = document.getElementById('search_form'); const searchQueryInput = document.getElementById('search_query'); const totalElement = document.getElementById('total'); const prevButton = document.getElementById('prev_btn'); const nextButton = document.getElementById('next_btn'); const currentPageElement = document.getElementById('current_page'); const totalPagesElement = document.getElementById('total_pages'); // Current search query and offset let query = ''; let offset = ''; /** * Load strams from Twitch API * API documentation: https://dev.twitch.tv/docs/v5/reference/search/#search-streams */ const getStreams = () => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); const url = `${TWITCH_API_URL}${getQueryString()}&limit=${LIMIT}`; xhr.open('GET', url); xhr.responseType = 'json'; xhr.setRequestHeader('Client-ID', CLIENT_ID); xhr.send(); xhr.onload = () => { if (xhr.status === 200) { resolve(xhr.response); } else { // Check if there is an error message in the server response if (xhr.response.error) { reject(new Error(`Error ${xhr.status}: ${xhr.response.error}`)); return; } // Otherwise, throw error status information reject(new Error(`Error ${xhr.status}: ${xhr.statusText}`)); } }; xhr.onerror = () => { reject(new Error('Network error')); }; }); }; /** * Get human readable time from now */ const fromNow = rawDate => { const interval = Math.floor(((new Date()).getTime() - (new Date(rawDate)).getTime()) / 1000); const minutes = Math.floor(interval / 60) % 60; const hours = Math.floor(interval / 60 / 60) % 24; const days = Math.floor(interval / 60 / 60 / 24); let result = ''; if (days > 0) { result += `${days}d `; } if (hours > 0) { result += `${hours}h `; } if (minutes > 0) { result += `${minutes}m `; } if (result === '') { result = 'less than a minute'; } return result; } /** * Add thousands separators into number. Resulting format is 4,294,967,295 */ const formatNumber = rawNumber => { const number = []; rawNumber.toString().split('').reverse().forEach((value, index) => { if (index > 0 && index % 3 === 0) { number.push(','); } number.push(value); }); return number.reverse().join(''); } /** * Hide DOM element using class name */ const hide = element => { if (!element.classList.contains(HIDDEN_CLASS)) { element.classList.add(HIDDEN_CLASS); } } /** * Show DOM element using class name */ const show = element => { if (element.classList.contains(HIDDEN_CLASS)) { element.classList.remove(HIDDEN_CLASS); } } const showError = message => { errorElement.textContent = message; show(errorElement); } /** * Stream template */ const renderStream = data => { return `<li class="stream"> <a class="stream-link" href="${data.channel.url}" target="_blank"> <img class="stream-thumb" src="${data.preview.medium}"> <h2 class="stream-title">${data.channel.status}</h2> <p class="stream-text">${data.game} - ${formatNumber(data.viewers)} viewers</p> <p class="stream-text">${data.channel.name} • started ${fromNow(data.created_at)} ago • ${formatNumber(data.channel.views)} total views</p> </a> </li>`; } /** * Build search query string */ const getQueryString = () => { let str = `?query=${query}`; if (offset) { str += `&offset=${offset}`; } return str; } /** * Load streams using query parameter */ const loadStream = () => { show(loader); // Hide all messages hide(welcomeElement); hide(notFoundElement); hide(errorElement); // Remove all streams in a safe way let child = streamListElement.lastElementChild; while (child) { streamListElement.removeChild(child); child = streamListElement.lastElementChild; } // Disable pagination nextButton.disabled = true; prevButton.disabled = true; getStreams().then(response => { totalElement.textContent = response._total; // Catch empty response if (response._total === 0) { currentPageElement.textContent = '−'; totalPagesElement.textContent = '−'; show(notFoundElement); hide(loader); return; } currentPageElement.textContent = Math.floor(offset / LIMIT) + 1; totalPagesElement.textContent = Math.ceil(response._total / LIMIT); // Check "Next" button availability if (offset + LIMIT < response._total) { nextButton.disabled = false; nextButton.value = offset + LIMIT; } // Check "Prev" button availability if (offset - LIMIT >= 0) { prevButton.disabled = false; prevButton.value = offset - LIMIT; } // Combine all streams as plain HTML and then append them into streams container let streams = ''; response.streams.forEach(stream => { streams += renderStream(stream); }); streamListElement.insertAdjacentHTML('afterbegin', streams); hide(loader); }).catch(error => { showError(error.message); hide(loader); }); } /** * Handle search form submitting */ searchFormElement.addEventListener('submit', event => { event.preventDefault(); const value = searchQueryInput.value.trim(); if (value === '') { showError('The search query cannot be empty.'); return; } try { query = encodeURI(value); } catch (e) { showError('An error occurred while processing a search query. Incorrect characters were used.'); return; } offset = 0; const queryString = getQueryString(); history.pushState({query, offset}, null, queryString); loadStream(); }); /** * Handle click on "Prev" button */ prevButton.addEventListener('click', () => { offset = parseInt(prevButton.value); history.pushState({query, offset}, null, getQueryString()); loadStream(); }); /** * Handle click on "Next" button */ nextButton.addEventListener('click', () => { offset = parseInt(nextButton.value); history.pushState({query, offset}, null, getQueryString()); loadStream(); }); /** * Handle history entry changes */ window.addEventListener('popstate', event => { if (!event.state || typeof event.state.query === 'undefined') { return; } searchQueryInput.value = decodeURI(event.state.query); query = event.state.query; offset = event.state.offset; loadStream(); }); /** * Initialize application */ (() => { // Parse URL params and check if there are params for this app const urlParams = new URLSearchParams(window.location.search); const queryParam = urlParams.get('query'); const offsetParam = urlParams.get('offset'); if (!queryParam) { return; } searchQueryInput.value = decodeURI(queryParam); query = queryParam; offset = offsetParam ? parseInt(offsetParam) : 0; loadStream(); })();
JavaScript
UTF-8
2,357
2.59375
3
[ "MIT" ]
permissive
/*eslint-disable*/ import '../sass/styles.sass'; window.onload = () => { const recordButton = document.querySelector('#record'); const raffleButton = document.querySelector('#raffle'); const playbackButton = document.querySelector('#playback'); const video = document.getElementById('video'); const url = '/record'; let lastVideoSaved; let source; var $playbackSection = $('.section--playback'), $videoSection = $('.section--video'), $recordSection = $('.section--record'), $recordingSection = $('.section--recording'), $closeButton = $('#close'); function sendRequest() { const posting = $.post(url); posting.done(function(data) { lastVideoSaved = `videos/${data}`; source = document.createElement('source'); source.setAttribute('src', lastVideoSaved); video.appendChild(source); $recordingSection.fadeOut(300, function() { $playbackSection.fadeIn(300); }); }); } function animateValue(id, start, end, duration) { var range = end - start; var current = start; var increment = end > start? 1 : -1; var stepTime = Math.abs(Math.floor(duration / range)); var obj = document.getElementById(id); var timer = setInterval(function() { current += increment; obj.innerHTML = current; if (current == end) { clearInterval(timer); $('#countdown').fadeOut(300, function() { $recordingSection.fadeIn(300); }); sendRequest(); } }, stepTime); } function record(event) { event.preventDefault(); $(this).fadeOut(300, function() { animateValue("countdown", 6, 0, 6000); }); } function playVideo() { video.play(); video.addEventListener('ended', function() { $closeButton.fadeIn(300); }); } function playback() { video.playbackRate = 0.3; $playbackSection.fadeOut(300, function(){ $videoSection.fadeIn(800, function() { playVideo(); }); }); } recordButton.addEventListener('click', record); playbackButton.addEventListener('click', playback); $closeButton.on('click', function() { $videoSection.fadeOut(300, function() { location.reload(); $recordSection.fadeIn(200); }); }); }
Java
UTF-8
2,438
4.125
4
[]
no_license
package com.hybeecodes.interviewprep.CTCI.arrays_strings; // Cracking The Coding Interview > Arrays And Strings// import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; // IS Unique public class IsUnique { public static void main(String[] args) { boolean isUnique1 = solution3("Discover"); boolean isUnique2 = solution3("Relieve"); System.out.println(isUnique1); System.out.println(isUnique2); } // Each Solution is going to be a static function /** This is the Brute Force Solution * T = O(n^2) * @param s * @return check */ static boolean solution1 (String s) { boolean check = true; for (int i =0; i < s.length()-1; i++) { for (int j = i+1; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { check = false; break; } } } return check; } /** A more Optimal solution using HashMap * T = O(n), S (space) = O(n) * @param s * @return check */ static boolean solution2 (String s) { boolean check = true; Set<Character> set = new HashSet<Character>(); for (int i =0; i < s.length(); i++) { if (set.contains(s.charAt(i))) { check = false; break; }else{ set.add(s.charAt(i)); } } return check; } /** A more Optimal solution by sorting first * T = O(n(log n)), * @param s * @return check */ static boolean solution3 (String s) { boolean check = true; s = sortString(s); for (int i = 0; i < s.length()-1; i++) { if (s.charAt(i) == s.charAt(i+1)) { check = false; break; } } return check; } /** A more Optimal solution using bit vector * T = O(n) * @param s * @return check */ static boolean solution4 (String s) { // Not implemented Yet return false; } public static String sortString(String inputString) { // convert input string to char array char[] tempArray = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray); } }
Python
UTF-8
8,928
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- # This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python. # Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, # session persistence, api calls, and more. # This sample is built using the handler classes approach in skill builder. import logging import ask_sdk_core.utils as ask_utils from publish import publish_function from consultConnection import consult_connection from ask_sdk_core.skill_builder import SkillBuilder from ask_sdk_core.dispatch_components import AbstractRequestHandler from ask_sdk_core.dispatch_components import AbstractExceptionHandler from ask_sdk_core.handler_input import HandlerInput from ask_sdk_model import Response logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class LaunchRequestHandler(AbstractRequestHandler): """Handler for Skill Launch.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_request_type("LaunchRequest")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = "Bem-vindo ao assistente da placa Node MCU, aqui você pode consultar o estado atual da conexão com o dispositivo e também alterar os intervalos de conexão, alarme e estou bem!" reprompt_txt = "Você pode dizer 5 minutos para o alarme, 5 minutos para conexão e 8 minutos para estou bem. Vamos faça o mesmo!" return ( handler_input.response_builder .speak(speak_output) .ask(reprompt_txt) .response ) class ConsultConnectionIntentHandler(AbstractRequestHandler): """Handler for Hello World Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("ConsultConnectionIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response consult = str(consult_connection()) speak_output = "A placa está {consult}.".format(consult=consult) return ( handler_input.response_builder .speak(speak_output) #.ask(reprompt_txt) .response ) class PublicDeviceIntentHandler(AbstractRequestHandler): """Handler for Hello World Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("PublicDeviceIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response slots = handler_input.request_envelope.request.intent.slots connection = int(slots["TimeConnection"].value) alarm = int(slots["TimeAlarm"].value) imok = int(slots["TimeImOK"].value) unitConnection = slots["unitConnection"].value unitAlarm = slots["unitAlarm"].value unitImOK = slots["unitImOK"].value if(unitConnection == "minutos" or unitConnection == "minuto"): connectionTime = connection*60 else: connectionTime = connection if(unitAlarm == "minutos" or unitAlarm == "minuto"): alarmTime = alarm*60 else: alarmTime = alarm if(unitImOK == "minutos" or unitImOK == "minuto"): imokTime = imok*60 else: imokTime = imok publish_function(connectionTime, alarmTime, imokTime) speak_output = "Ok! você disse que quer que o intervalo da conexão seja {connection} {unitConnection}, o alarme para {alarm} {unitAlarm} e estou bem {imok} {unitImOK}.".format(alarm=alarm, connection=connection, imok=imok, unitConnection=unitConnection, unitAlarm=unitAlarm, unitImOK=unitImOK) return ( handler_input.response_builder .speak(speak_output) #.ask(reprompt_txt) .response ) class HelpIntentHandler(AbstractRequestHandler): """Handler for Help Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = "You can say hello to me! How can I help?" return ( handler_input.response_builder .speak(speak_output) .ask(speak_output) .response ) class CancelOrStopIntentHandler(AbstractRequestHandler): """Single handler for Cancel and Stop Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input)) def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = "Goodbye!" return ( handler_input.response_builder .speak(speak_output) .response ) class FallbackIntentHandler(AbstractRequestHandler): """Single handler for Fallback Intent.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response logger.info("In FallbackIntentHandler") speech = "Hmm, I'm not sure. You can say Hello or Help. What would you like to do?" reprompt = "I didn't catch that. What can I help you with?" return handler_input.response_builder.speak(speech).ask(reprompt).response class SessionEndedRequestHandler(AbstractRequestHandler): """Handler for Session End.""" def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_request_type("SessionEndedRequest")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response # Any cleanup logic goes here. return handler_input.response_builder.response class IntentReflectorHandler(AbstractRequestHandler): """The intent reflector is used for interaction model testing and debugging. It will simply repeat the intent the user said. You can create custom handlers for your intents by defining them above, then also adding them to the request handler chain below. """ def can_handle(self, handler_input): # type: (HandlerInput) -> bool return ask_utils.is_request_type("IntentRequest")(handler_input) def handle(self, handler_input): # type: (HandlerInput) -> Response intent_name = ask_utils.get_intent_name(handler_input) speak_output = "You just triggered " + intent_name + "." return ( handler_input.response_builder .speak(speak_output) # .ask("add a reprompt if you want to keep the session open for the user to respond") .response ) class CatchAllExceptionHandler(AbstractExceptionHandler): """Generic error handling to capture any syntax or routing errors. If you receive an error stating the request handler chain is not found, you have not implemented a handler for the intent being invoked or included it in the skill builder below. """ def can_handle(self, handler_input, exception): # type: (HandlerInput, Exception) -> bool return True def handle(self, handler_input, exception): # type: (HandlerInput, Exception) -> Response logger.error(exception, exc_info=True) speak_output = "Sorry, I had trouble doing what you asked. Please try again." return ( handler_input.response_builder .speak(speak_output) .ask(speak_output) .response ) # The SkillBuilder object acts as the entry point for your skill, routing all request and response # payloads to the handlers above. Make sure any new handlers or interceptors you've # defined are included below. The order matters - they're processed top to bottom. sb = SkillBuilder() sb.add_request_handler(ConsultConnectionIntentHandler()) sb.add_request_handler(LaunchRequestHandler()) sb.add_request_handler(PublicDeviceIntentHandler()) sb.add_request_handler(HelpIntentHandler()) sb.add_request_handler(CancelOrStopIntentHandler()) sb.add_request_handler(FallbackIntentHandler()) sb.add_request_handler(SessionEndedRequestHandler()) sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers sb.add_exception_handler(CatchAllExceptionHandler()) lambda_handler = sb.lambda_handler()
C++
UTF-8
7,264
3.640625
4
[]
no_license
//#include, using etc #include "Game.h" #include <iostream> #include <conio.h> #include <ctime> using namespace std; // Default Constructor Game::Game() { } // Constructor passing in the player type Game::Game(int playertype) { // create a new human and ai object human = new Human(playertype); ai = new AI(playertype); } // Default Destructor Game::~Game() { // delete player and ai delete human; delete ai; } // main game function void Game::MainFunction() { int userInput; // start match loop bool gameRunning = true; while (gameRunning) { //Sort teams by remaining health human->BubbleSort(); // Bubble Sort (Sort type 1) ai->InsertionSort(); // Insertion Sort (Sort type 2) // Display both teams health system("cls"); ShowHealth(); //Check if a team has lost or won gameRunning = CheckWin(); // Display the options for the players turn cout << endl << " ACTIONS:" << endl; cout << " 1. ATTACK" << endl; cout << " 2. TAUNT" << endl; cout << " 3. CHEER UP" << endl << endl; // get input for player options cin >> userInput; cin.clear(); cin.ignore(999999, '\n'); // Do player turn PlayerTurn(userInput); //check if a team has lost or won gameRunning = CheckWin(); // Do AI turn system("cls"); ShowHealth(); AITurn(); //Check sanity CheckInsane(); } } // function for checking if a team member is insane void Game::CheckInsane() { // get the team counts int AICount = ai->monsterCount; int HumanCount = human->monsterCount; // Check if the player is insane for (int i = 0; i < HumanCount; i++) { human->army[i]->Insane(); if (human->army[i]->insane) { cout << endl << " One of your team members is losing 10 health a turn. Better try and cheer them up." << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } } // Check if the AI is insane for (int i = 0; i < AICount; i++) { ai->army[i]->Insane(); if (ai->army[i]->insane) { cout << endl << " One of the AI team members is losing 10 health a turn. Keep up that taunting!" << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } } } // display health function void Game::ShowHealth() { // get the team counts int AICount = ai->monsterCount; int HumanCount = human->monsterCount; // Display player team health cout << endl; cout << " YOUR TEAM: " << endl; for (int i = 0; i < HumanCount; i++) { cout << " " << human->army[i]->health << "H " << human->army[i]->cheer << "C"; } cout << endl << endl; // Display AI team health cout << " ENEMY TEAM: " << endl; for (int i = 0; i < AICount; i++) { cout << " " << ai->army[i]->health << "H"; } cout << endl << endl << endl; } // Function to check if someone has won bool Game::CheckWin() { // get team count int AICount = ai->monsterCount; int HumanCount = human->monsterCount; int temp; temp = 0; // Display lose for (int i = 0; i < HumanCount; i++) { // check that all of the team is 0 health if (human->army[i]->health == 0) { temp += 1; if (temp == HumanCount) { system("cls"); cout << endl << " __ ______ _ _ _ ____ _____ ______ _ " << endl; cout << " \\ \\ / / __ \\| | | | | | / __ \\ / ____| ____| |" << endl; cout << " \\ \\_/ / | | | | | | | | | | | | (___ | |__ | |" << endl; cout << " \\ /| | | | | | | | | | | | |\\___ \\| __| | |" << endl; cout << " | | | |__| | |__| | | |___| |__| |____) | |____|_|" << endl; cout << " |_| \\____/ \\____/ |______\\____/|_____/|______(_)" << endl; cout << " YOU LOSE :( SORRY THEY WERE SO MEAN.." << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); return false; } } } temp = 0; // Display Win for (int i = 0; i < AICount; i++) { // check that all of the team is 0 health if (ai->army[i]->health == 0) { temp += 1; if (temp == AICount) { system("cls"); cout << endl << " __ _______ _ _ _ _ ______ _____ _ " << endl; cout << " \\ \\ / /_ _| \\ | | \\ | | ____| __ \\| |" << endl; cout << " \\ \\ /\\ / / | | | \\| | \\| | |__ | |__) | |" << endl; cout << " \\ \\/ \\/ / | | | . ` | . ` | __| | _ /| |" << endl; cout << " \\ /\\ / _| |_| |\\ | |\\ | |____| | \\ \\|_|" << endl; cout << " \\/ \\/ |_____|_| \\_|_| \\_|______|_| \\_(_)" << endl; cout << " YOU WIN! YOU HAVE KILLED/BULLIED ALL OF THE ENEMY TEAM!" << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); return false; } } } return true; } // Run the players turn void Game::PlayerTurn(int input) { // Attack if (input == 1) { system("cls"); ShowHealth(); // set the damage int damage = human->Attack(input); // Apply the damage ai->army[0]->takeDamage(damage, 1); cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } // Taunt else if (input == 2) { if (ai->army[0]->sanity > 0) { system("cls"); ShowHealth(); // Set the taunt damage int taunt = human->Taunt(); // Apply the taunt damage ai->army[0]->lowerSanity(taunt, 1); cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } // Message to display if youve taunted them to much else { system("cls"); ShowHealth(); cout << endl << " You jerk.. they're crying thier eyes out! No more taunting.. " << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } } // Cheer else if (input == 3) { system("cls"); ShowHealth(); // Go to the cheer store human->Cheer(input); } // invalid input else { system("cls"); ShowHealth(); input = 0; cout << endl << " You can do nothing if you like?" << endl; cout << " Thats what I thought, please make a valid choice" << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } } // Run the AI teams turn void Game::AITurn() { // Create a random input for the AI attack selection int input = 0; input = rand() % 2 + 1; // Attack if (input == 1) { system("cls"); ShowHealth(); input = 0; input = rand() % 3 + 1; // Find out the damage int damage = ai->Attack(input); // Apply for damage human->army[0]->takeDamage(damage, 2); cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } // Taunt else if (input == 2) { if (human->army[0]->sanity > 0) { system("cls"); ShowHealth(); // Find out the taunt damage int taunt = ai->Taunt(); // Apply the taunt damage human->army[0]->lowerSanity(taunt, 2); cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } // Message to display if youve been taunted to much else { system("cls"); ShowHealth(); cout << endl << " They continue to taunt you even though you're already crying. Good thing you're so sad you hardly notice.. " << endl; cout << endl << endl << " PRESS ANY KEY TO CONTINUE..." << endl; _getch(); } } }
C#
UTF-8
8,176
2.59375
3
[ "Apache-2.0" ]
permissive
//----------------------------------------------------------------------- // <copyright author="Muhammad Haroon"> // Texticize // Codeplex Project: http://texticize.codeplex.com/ // Copyright (c) Muhammad Haroon, http://www.softwarerockstar.com/ // Released under Apache License Version 2.0, http://www.apache.org/licenses/ // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text.RegularExpressions; using SoftwareRockstar.ComponentModel.Extensibility; using System.Collections; namespace SoftwareRockstar.Texticize.SubstitutionProcessors { [Export(typeof(ISubstitutionProcessor))] [ExportMetadata(UniquenessEvidenceFields.UniqueName, SystemSubstitutionProcessorNames.Vocabulary)] class VocabularySubstitutionProcessor : ISubstitutionProcessor { public ProcessorOutput Process(ProcessorInput input) { Logger.LogMethodStartup(); ProcessorOutput output = new ProcessorOutput(); if (input != null) { try { // Process regular vocabulary with provided maps Logger.LogInfo("Processing Maps"); output.Combine(ProcessMaps(input)); // If no mpas specified but a default variable is specified then see if default variable is a // dictionary and then perform dictionary subsitutions if (input.Maps.Count == 0 && input.Variables.ContainsKey(input.Configuration.DefaultVariableKey)) { if (output.IsSuccess || input.Configuration.ContinueOnError) { input.Target = output.Result; Logger.LogInfo("Processing Default Variables"); output.Combine(ProcessDefaultVariableDictionary(input)); } } } catch (ApplicationException ex) { Logger.LogError(ex); output.Exceptions.Add(ex); } } Logger.LogMethodEnd(); return output; } /// <summary> /// If default variable is an IDictionary performs subsitutions based on it's keys and values. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> protected ProcessorOutput ProcessDefaultVariableDictionary(ProcessorInput input) { ProcessorOutput output = new ProcessorOutput(); try { output.Result = input.Target; var dictionary = input.Variables[input.Configuration.DefaultVariableKey] as IDictionary; if (dictionary != null) foreach (DictionaryEntry item in dictionary) output.Result = output.Result.Replace( input.Configuration.PlaceHolderBegin + item.Key.ToString() + input.Configuration.PlaceHolderEnd, item.Value.ToString()); } catch (ApplicationException ex) { output.Exceptions.Add(ex); } return output; } /// <summary> /// Iterates through provided maps and processes the template performing substitutions specified by maps. /// </summary> /// <returns>String result.</returns> protected ProcessorOutput ProcessMaps(ProcessorInput input) { ProcessorOutput output = new ProcessorOutput(); output.Result = input.Target; try { foreach (var map in input.Maps) { // Escape begin and end tokens string placeHolderBegin = Regex.Escape(input.Configuration.PlaceHolderBegin); string placeHolderEnd = Regex.Escape(input.Configuration.PlaceHolderEnd); // Generate pattern based on mapy's key and begin and end tokens string originalPattern = placeHolderBegin + Regex.Escape(map.Key) + placeHolderEnd; // Insert parameters pattern into generated pattern string parameterPattern = input.Configuration.TemplateRegexPatternFormatted; string pattern = originalPattern.Insert(originalPattern.Length - placeHolderEnd.Length, parameterPattern); Regex regex = new Regex(pattern, input.Configuration.TemplateRegexOptions); // Get all regex matches in template var matches = regex.Matches(output.Result); // Process each match... for (int j = 0; j < matches.Count; j++) { var match = matches[j]; // Process each group in the match... if (match.Success && match.Groups.Count > 0 && match.Groups.Count > 1) { // Determine variable name string varName = (map.Key.Contains(input.Configuration.PropertySeperator)) ? map.Key.Substring(0, map.Key.IndexOf(input.Configuration.PropertySeperator)) : input.Variables.ContainsKey(input.Configuration.DefaultVariableKey) ? input.Configuration.DefaultVariableKey : input.Configuration.NoVariableName; // Determine expression found in template to be replaced string expression = (map.Key.Contains(input.Configuration.PropertySeperator)) ? expression = String.Format("{0}{1}", map.Key.Substring(0, 1), map.Key.Substring(map.Key.IndexOf(input.Configuration.PropertySeperator) + 1)) : match.Value; // Determine parameters within expression Dictionary<string, string> parameterDictionary = (match.Groups.Count > 1) ? match.Groups[input.Configuration.TemplateRegexParamInternalGroupName] .ToParameterDictionary(input.Configuration.ParameterSeperatorChar) : new Dictionary<string, string>(); // Determine target variable object target = (input.Variables.ContainsKey(varName)) ? input.Variables[varName] : new System.Object(); // Create context to be sent to delegate that will provide replacement value IContext context = CachedContext.GetContext( variable: target, variableName: varName, expression: expression, parameters: parameterDictionary); // Get substitute value var substitute = map.Value.DynamicInvoke(context).ToString(); // Make replacement in template output.Result = output.Result.Replace(match.Value, substitute); } } } } catch (ApplicationException ex) { output.Exceptions.Add(ex); } return output; } } }
Java
UTF-8
1,456
2.0625
2
[ "Apache-2.0" ]
permissive
package io.izenecloud.msgpack; import java.io.IOException; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.OutputCommitter; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; public class MsgpackOutputFormat<K, V> extends OutputFormat<K, V> { @Override public void checkOutputSpecs(JobContext context) throws IOException, InterruptedException { } @Override public OutputCommitter getOutputCommitter(TaskAttemptContext context) throws IOException, InterruptedException { return new OutputCommitter() { public void abortTask(TaskAttemptContext taskContext) { } public void cleanupJob(JobContext jobContext) { } public void commitTask(TaskAttemptContext taskContext) { } public boolean needsTaskCommit(TaskAttemptContext taskContext) { return false; } public void setupJob(JobContext jobContext) { } public void setupTask(TaskAttemptContext taskContext) { } public boolean isRecoverySupported() { return true; } public void recoverTask(TaskAttemptContext taskContext) throws IOException { // Nothing to do for recovering the task. } }; } @Override public RecordWriter<K, V> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException { return new MsgpackRecordWriter<K, V>(context); } }
Python
UTF-8
495
3.03125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Thu Jul 11 01:04:18 2019 @author: Inki """ import threading class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self): super(StoppableThread, self).__init__() self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set()
JavaScript
UTF-8
3,021
2.515625
3
[ "Apache-2.0" ]
permissive
(function(SBCOM) { SBCOM.core = (function() { // dependencies var sandbox = SBCOM.sandbox; // end of dependencies // private properties and methods var modules = {}; // end of private properties and methods // public API return { registerModule: function(moduleId, creator) { modules[moduleId] = { create: creator, instance: null }; SBCOM.log(1, moduleId + ' has been registered'); }, start: function(moduleId) { var module = modules[moduleId]; if(module) { module.instance = module.create(sandbox.create(this, moduleId)); SBCOM.log(1, moduleId + ' has been created'); module.instance.init(); SBCOM.log(1, moduleId + ' has been initialized'); } }, startAll: function() { var moduleId; for(moduleId in modules) { if(modules.hasOwnProperty(moduleId)) { this.start(moduleId); } } }, stop: function(moduleId) { var module = modules[moduleId]; if(module && module.instance) { module.instance.destroy(); module.instance = null; SBCOM.log(1, moduleId + ' has been stopped'); } }, stopAll: function() { var moduleId; for(moduleId in modules) { if(modules.hasOwnProperty(moduleId)) { this.stop(moduleId); } } }, subscribe: function(events, moduleId) { modules[moduleId].events = events; SBCOM.log(1, moduleId + ' has been subscribed'); }, unsubscribe: function(events, moduleId) { delete modules[moduleId].events; SBCOM.log(1, moduleId + ' has been unsubscribed'); }, publish: function(event) { var moduleId; for(moduleId in modules) { if (modules.hasOwnProperty(moduleId)) { modules[moduleId].events[event.type](event.data); SBCOM.log(1, event.type + ' has been published'); } } } }; }()); }(SBCOM));
Java
UTF-8
1,821
2.140625
2
[]
no_license
package com.catDog.mpadoption; public class Mpadoption { private long num; private String userId; private String nickName; private int adoptionListNum; private int adoptionNum; private int speciesSort; private String status; private String adoptionSubject; private String adoptionCreted; private int adoptionHitCount; public long getNum() { return num; } public void setNum(long num) { this.num = num; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public int getAdoptionNum() { return adoptionNum; } public void setAdoptionNum(int adoptionNum) { this.adoptionNum = adoptionNum; } public int getSpeciesSort() { return speciesSort; } public void setSpeciesSort(int speciesSort) { this.speciesSort = speciesSort; } public String getAdoptionSubject() { return adoptionSubject; } public void setAdoptionSubject(String adoptionSubject) { this.adoptionSubject = adoptionSubject; } public String getAdoptionCreted() { return adoptionCreted; } public void setAdoptionCreted(String adoptionCreted) { this.adoptionCreted = adoptionCreted; } public int getAdoptionHitCount() { return adoptionHitCount; } public void setAdoptionHitCount(int adoptionHitCount) { this.adoptionHitCount = adoptionHitCount; } public int getAdoptionListNum() { return adoptionListNum; } public void setAdoptionListNum(int adoptionListNum) { this.adoptionListNum = adoptionListNum; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
Python
UTF-8
134
3.5
4
[]
no_license
while True: n=input() if n.isdigit(): print("n=%s"%n) break else: print('is not a number')
C++
UTF-8
4,516
3.796875
4
[]
no_license
#include "std_lib_facilities.h" #include <fstream> #include <string> #include <iomanip> #include <vector> int min(int x, int y, int z) // Function that calculates the minimum of 3 numbers. { return min(min(x, y), z); } int levenshtein_distance(string s1, string s2) // Function that calculates the Levenshtein distance between 2 strings. { int str1l = s1.length(); // Variable that holds the size of the first string. int str2l = s2.length(); // Variable that holds the size of the second string. int sub_cost = 0; // The substitution cost of each operation. int edits[str1l+1][str2l+1]; // The array that holds the total edits needed for each case. size_t i,j; // The iterators needed for looping the array. for(i=0; i<=str1l; i++) // For loop that sets every cell of the array to 0 { for(j=0; j<=str2l; j++) { edits[i][j] = 0; } } for (i = 0; i <=str1l; i++) // For loop that sets the values of the first column equal to the according row number. { edits[i][0] = i; } for (j = 0; j <=str2l; j++) // For loop that sets the values of the first row equal to the according column number. { edits[0][j] = j; } //-----|Main loop that compares each letter of the strings and calculates the number of edits|-----// for(i=1; i<=str1l; i++) { for(j=1; j<=str2l; j++) { if(s1[i] == s2[j]) // If the according characters of the string are equal, { // the sub. cost is 0 and the edits are equal to the upper left diagonal value. sub_cost = 0; edits[i][j]=edits[i-1][j-1]; } else // If they are unequal then the edits are equal to { // the minimum value of the left + 1, upper + 1, and upper left + sub. cost values. sub_cost = 1; edits[i][j] = min(edits[i-1][j] + 1, edits[i][j-1] + 1, edits[i-1][j-1]+sub_cost); } } } //-------------------------------------------------------------------------------------------------// return edits[str1l][str2l]; // Returns the lower right value of the array which is the total edits needed. } string delete_linebreaks(string str) //Function that removes the linebreaks of the inserted string. { string::size_type pos = 0; while ( ( pos = str.find ("\r\n",pos) ) != string::npos ) // Searches for the "\r\n" characters until the end of file and removes them. { str.erase ( pos, 2 ); } return str; } double difference_percentage(string string1, string string2) // Function that calculates the percentage difference of the two strings. { double lev_dis = levenshtein_distance(string1, string2); // Calculates the levenshtein distance. int max_length = max(string1.length()-1, string2.length()-1); // Defines the max length of the two strings. double percentage = (lev_dis / double(max_length))*100; // Divides the levenshtein distance by the max string length to calculate the percentage. cout << "The file A and file B are " << setprecision(3) << percentage << "% " << "different.\n"; } int main() // Start of the main function. { ifstream file1("Read_a.txt"); // Opens the two files for reading. ifstream file2("Read_b.txt"); if(!file1 || !file2) // If the program is unable to open a file print an error message and terminate. { cout << "Error opening files!\n"; return -1; } string word1((std::istreambuf_iterator<char>(file1)), (std::istreambuf_iterator<char>())); // Use of the istreambuf_iterator to place the contents of the files string word2((std::istreambuf_iterator<char>(file2)), (std::istreambuf_iterator<char>())); // inside the according strings. word1 = delete_linebreaks(word1); //Remove the linebreaks of each word. word2 = delete_linebreaks(word2); difference_percentage(word1, word2); // Calculate the percentage difference of the two files. file1.close(); //Close the files. file2.close(); keep_window_open(); }
JavaScript
UTF-8
2,293
2.9375
3
[]
no_license
import {START_GAME, END_GAME} from './gameInfo'; import {getNumberOfLines} from './score'; const INCREMENT_CURRENT_LEVEL = 'INCREMENT_CURRENT_LEVEL'; const INCREMENT_STARTING_LEVEL = 'INCREMENT_STARTING_LEVEL'; const initialState = { current: 0, starting: 0, }; export default function(state = initialState, action) { switch (action.type) { case INCREMENT_CURRENT_LEVEL: return {...state, current: state.current + 1}; case INCREMENT_STARTING_LEVEL: return {...state, starting: state.starting + 1}; case START_GAME: return {...state, current: state.starting}; case END_GAME: return {...state, starting: 0}; default: return state; } } export const getCurrentLevel = (state) => state.level.current; export const getStartingLevel = (state) => state.level.starting; export function canAdvanceToNextLevel(state) { const numberOfLines = getNumberOfLines(state); const currentLevel = getCurrentLevel(state); const startingLevel = getStartingLevel(state); if (currentLevel === startingLevel) { const optionA = startingLevel * 10 + 10; const optionB = Math.max(startingLevel * 10 - 50); if (numberOfLines === optionA || numberOfLines === optionB) { return true; } } else if (numberOfLines % 10 === 0) { return true; } return false; } export function getDropSpeedInMS(state) { const framesPerSecond = 60; const level = getCurrentLevel(state); let framesPerGridCell = 48; if (level <= 8) { framesPerGridCell -= 5 * level; } else if (level === 9) { framesPerGridCell = 6; } else if (level >= 10 && level <= 12) { framesPerGridCell = 5; } else if (level >= 13 && level <= 15) { framesPerGridCell = 4; } else if (level >= 16 && level <= 18) { framesPerGridCell = 3; } else if (level >= 19 && level <= 28) { framesPerGridCell = 2; } else { framesPerGridCell = 1; } framesPerGridCell += 1; // add one frame for the 'drop' return (framesPerGridCell / framesPerSecond) * 1000; } export function incrementCurrentLevel() { return {type: INCREMENT_CURRENT_LEVEL}; } export function incrementStartingLevel() { return (dispatch, getState) => { if (getStartingLevel(getState()) < 19) { dispatch({type: INCREMENT_STARTING_LEVEL}); } }; }
Java
UTF-8
6,128
2.21875
2
[ "Apache-2.0" ]
permissive
package com.t3hh4xx0r.openhuesdk.sdk; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.SweepGradient; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class ColorPickerView extends View { public static abstract interface OnColorChangedListener { public abstract void colorChanged(int color, int hue); } private static int CENTER_RADIUS = 0; private static int CENTER_X = 0; private static int CENTER_Y = 0; private static final float PI = 3.141593F; private long colorChangeRateLimit = 200000000L; private int hue; private long lastColorChange; private Paint mCenterPaint; private final int[] mColors = { -65536, -65281, -16776961, -16711681, -16711936, -256, -65536 }; private boolean mHighlightCenter; private OnColorChangedListener mListener; private Paint mPaint; private boolean mTrackingCenter; private int parentHeight; private int parentWidth; public ColorPickerView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); SweepGradient localSweepGradient = new SweepGradient(0.0F, 0.0F, mColors, null); mPaint = new Paint(1); mPaint.setShader(localSweepGradient); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(32.0F); mCenterPaint = new Paint(1); mCenterPaint.setStrokeWidth(5.0F); } private int ave(int paramInt1, int paramInt2, float paramFloat) { return paramInt1 + Math.round(paramFloat * (paramInt2 - paramInt1)); } private int floatToByte(float paramFloat) { return Math.round(paramFloat); } public int getColor() { return mCenterPaint.getColor(); } public int getHue() { return hue; } private int interpColor(int colors[], float unit) { if (unit <= 0) { return colors[0]; } if (unit >= 1) { return colors[colors.length - 1]; } float p = unit * (colors.length - 1); int i = (int) p; p -= i; int c0 = colors[i]; int c1 = colors[i + 1]; int a = ave(Color.alpha(c0), Color.alpha(c1), p); int r = ave(Color.red(c0), Color.red(c1), p); int g = ave(Color.green(c0), Color.green(c1), p); int b = ave(Color.blue(c0), Color.blue(c1), p); return Color.argb(a, r, g, b); } @Override protected void onDraw(Canvas canvas) { float f = CENTER_X - 0.5F * mPaint.getStrokeWidth(); canvas.translate(CENTER_X, CENTER_X); canvas.drawOval(new RectF(-f, -f, f, f), mPaint); canvas.drawCircle(0.0F, 0.0F, CENTER_RADIUS, mCenterPaint); if (mTrackingCenter) { int i = mCenterPaint.getColor(); mCenterPaint.setStyle(android.graphics.Paint.Style.STROKE); if (mHighlightCenter) mCenterPaint.setAlpha(255); else mCenterPaint.setAlpha(128); canvas.drawCircle(0.0F, 0.0F, CENTER_RADIUS + mCenterPaint.getStrokeWidth(), mCenterPaint); mCenterPaint.setStyle(android.graphics.Paint.Style.FILL); mCenterPaint.setColor(i); } } @Override protected void onMeasure(int paramInt1, int paramInt2) { parentWidth = View.MeasureSpec.getSize(paramInt1); parentHeight = View.MeasureSpec.getSize(paramInt2); int i = Math.max(Math.min(parentWidth, parentHeight), 320); setMeasuredDimension(i, i); CENTER_X = i / 2; CENTER_Y = i / 2; CENTER_RADIUS = i / 6; } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX() - CENTER_X; float y = event.getY() - CENTER_Y; boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTrackingCenter = inCenter; if (inCenter) { mHighlightCenter = true; invalidate(); break; } case MotionEvent.ACTION_MOVE: if (mTrackingCenter) { if (mHighlightCenter != inCenter) { mHighlightCenter = inCenter; invalidate(); } } else { float f3 = (float) Math.atan2(y, x) / 6.283185F; if (f3 < 0.0F) { f3 += 1.0F; } hue = ((int) ((1.0F - f3) * 65535.0F)); mCenterPaint.setColor(interpColor(mColors, f3)); invalidate(); return true; } break; case MotionEvent.ACTION_UP: if (mTrackingCenter) { if (inCenter) { if (mListener != null) { mListener.colorChanged(mCenterPaint.getColor(), hue); } } mTrackingCenter = false; // so we draw w/o halo invalidate(); } break; } return true; // float f1 = paramMotionEvent.getX() - CENTER_X; // float f2 = paramMotionEvent.getY() - CENTER_Y; // boolean bool; // if (Math.sqrt(f1 * f1 + f2 * f2) <= CENTER_RADIUS) { // bool = true; // switch (paramMotionEvent.getAction()) { // default: // case 0: // case 2: // case 1: // } // } // label129: do { // do { // return true; // bool = false; // break; // mTrackingCenter = false; // if (bool) { // mHighlightCenter = true; // invalidate(); // return true; // } // if (!mTrackingCenter) // break label129; // } while (mHighlightCenter == bool); // mHighlightCenter = bool; // invalidate(); // return true; // float f3 = (float) Math.atan2(f2, f1) / 6.283185F; // if (f3 < 0.0F) // f3 += 1.0F; // if (-f3 < 0.0F) // ; // for (float f4 = 1.0F - f3;; f4 = f3) { // hue = ((int) (f4 * 65535.0F)); // mCenterPaint.setColor(interpColor(mColors, f3)); // invalidate(); // return true; // } // if (mTrackingCenter) { // mTrackingCenter = false; // invalidate(); // } // } while (System.nanoTime() - lastColorChange <= // colorChangeRateLimit); // mListener.colorChanged(mCenterPaint.getColor(), hue); // lastColorChange = System.nanoTime(); } private int pinToByte(int paramInt) { if (paramInt < 0) paramInt = 0; while (paramInt <= 255) return paramInt; return 255; } public void setInitialColor(int paramInt) { if (mPaint != null) { mCenterPaint = new Paint(1); mCenterPaint.setStrokeWidth(5.0F); } mCenterPaint.setColor(paramInt); } public void setOnColorChangedListener( OnColorChangedListener paramOnColorChangedListener) { mListener = paramOnColorChangedListener; } }
JavaScript
UTF-8
3,254
2.578125
3
[]
no_license
function validateSearch(num) { var search = document.getElementById("searchbar-input-" + num).value; console.log("search = " + search); var params = { "search": search } getSearchResults(params); sessionStorage.setItem("view", "Search"); loadContent(); return false; } function getSearchResults(params) { // console.log(params); document.getElementById("you-searched-for").innerHTML = "<h2>You Searched for \"" + params.search + "\"" $.ajax({ url: 'http://localhost:8080/CSCI201-FinalProject/searchSongsByTitle', data: { format: 'json', search: params.search }, error: function() { $('#info').html('<p>An error has occurred</p>'); console.log("IDIOT"); }, dataType: 'json', success: function(data) { console.log(data); if(data.length > 0) { document.getElementById("search-results-songs").innerHTML = ""; var html = ""; html += "<table class=\"table table-striped\"><tbody>"; for(var i=0 ; i<data.length ; i++) { url = "http://localhost:8080/CSCI201-FinalProject/" + data[i].path; html += "<tr>"; html += "<td>" + (i+1) + ". </td>"; html += "<td>" + data[i].title + "</td>"; html += "<td><button type=\"button\" id=\"button-play\" class=\"btn btn-primary btn-lg\" onClick=\"MIDIjs.play('" + url + "');\">" + "Play <i class=\"fa fa-play\"> </i></button>"; html += "<td><button type=\"button\" id=\"button-save\" class=\"btn btn-primary btn-lg\" onclick=\"saveSong(\'"+ store.get("userid")+ "\',\'" + data[i].title + "\',\'" + data[i].path + "\')\">" + "<i>Save</i></button>"; html += "</tr>"; } html += "</tbody></table>"; document.getElementById("search-results-songs").innerHTML = html; } }, type: 'GET' }); $.ajax({ url: 'http://localhost:8080/CSCI201-FinalProject/searchUsersByName', data: { format: 'json', search: params.search }, error: function() { $('#info').html('<p>An error has occurred</p>'); console.log("IDIOT"); }, dataType: 'json', success: function(data) { console.log(data); if(data.length > 0) { document.getElementById("search-results-users").innerHTML = ""; var html = ""; for(var i=0 ; i<data.length ; i++) { html += "<div class=\"row\">"; html += "<div class=\"col-sm-2\">"; html += "<h4>" + (i+1) + "</h4>"; html += "</div>"; html += "<div class=\"col-sm-6\">"; console.log("You clicked on username: " + data[i].username); html += "<a href=\"#\" onClick=\"loadUserpage(\'" + data[i].username.toLowerCase() + "\');\"><h4>" + data[i].username + "</h4></a>"; html += "</div>"; html += "<div class=\"col-sm-4 justify-content-center\">" html += "<img src=\"" + data[i].imageUrl + "\" class=\"results-img\"></img>" html += "</div>" html += "</div>"; } document.getElementById("search-results-users").innerHTML += html; } }, type: 'GET' }); }
Java
UTF-8
271
1.726563
2
[]
no_license
package edu.teco.ecqels.lang.op; import edu.teco.ecqels.lang.window.Duration; /** * * @author Michael Jacoby * @organization Karlsruhe Institute of Technology, Germany www.kit.edu * @email michael.jacoby@student.kit.edu */ public interface OpRefreshable { public Duration getDuration(); }
Java
UTF-8
414
2.03125
2
[ "MIT" ]
permissive
package voogasalad_GucciGames.gameplayer.scenes; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; public interface GameSceneInterface { public <T extends Event> void addEventHandler(EventType<T> eventType, EventHandler<T> eventHandler); public <T extends Event> void addEventFilter(EventType<T> eventType, EventHandler<T> eventHandler); public void refresh(); }
Java
UTF-8
9,585
2.5
2
[]
no_license
package sky.housecommon; public class InstantaneousConsumption implements Timed,Comparable<InstantaneousConsumption> { private final long time; private final PricingPeriod pricingPeriod; private final double blueDayOffPeakHourTotal; private final double blueDayPeakHourTotal; private final double whiteDayOffPeakHourTotal; private final double whiteDayPeakHourTotal; private final double redDayOffPeakHourTotal; private final double redDayPeakHourTotal; private final String consumer1Name; private final int consumer1Consumption; private final String consumer2Name; private final int consumer2Consumption; private final String consumer3Name; private final int consumer3Consumption; private final String consumer4Name; private final int consumer4Consumption; private final String consumer5Name; private final int consumer5Consumption; private final String consumer6Name; private final int consumer6Consumption; private final String consumer7Name; private final int consumer7Consumption; private final String consumer8Name; private final int consumer8Consumption; private final String consumer9Name; private final int consumer9Consumption; private final String consumer10Name; private final int consumer10Consumption; public InstantaneousConsumption(long time,PricingPeriod pricingPeriod,double blueDayOffPeakHourTotal,double blueDayPeakHourTotal,double whiteDayOffPeakHourTotal,double whiteDayPeakHourTotal,double redDayOffPeakHourTotal,double redDayPeakHourTotal,String consumer1Name,int consumer1Consumption,String consumer2Name,int consumer2Consumption,String consumer3Name,int consumer3Consumption,String consumer4Name,int consumer4Consumption,String consumer5Name,int consumer5Consumption,String consumer6Name,int consumer6Consumption,String consumer7Name,int consumer7Consumption,String consumer8Name,int consumer8Consumption,String consumer9Name,int consumer9Consumption,String consumer10Name,int consumer10Consumption) { this.time=time; this.pricingPeriod=pricingPeriod; this.blueDayOffPeakHourTotal=blueDayOffPeakHourTotal; this.blueDayPeakHourTotal=blueDayPeakHourTotal; this.whiteDayOffPeakHourTotal=whiteDayOffPeakHourTotal; this.whiteDayPeakHourTotal=whiteDayPeakHourTotal; this.redDayOffPeakHourTotal=redDayOffPeakHourTotal; this.redDayPeakHourTotal=redDayPeakHourTotal; this.consumer1Name=consumer1Name; this.consumer1Consumption=consumer1Consumption; this.consumer2Name=consumer2Name; this.consumer2Consumption=consumer2Consumption; this.consumer3Name=consumer3Name; this.consumer3Consumption=consumer3Consumption; this.consumer4Name=consumer4Name; this.consumer4Consumption=consumer4Consumption; this.consumer5Name=consumer5Name; this.consumer5Consumption=consumer5Consumption; this.consumer6Name=consumer6Name; this.consumer6Consumption=consumer6Consumption; this.consumer7Name=consumer7Name; this.consumer7Consumption=consumer7Consumption; this.consumer8Name=consumer8Name; this.consumer8Consumption=consumer8Consumption; this.consumer9Name=consumer9Name; this.consumer9Consumption=consumer9Consumption; this.consumer10Name=consumer10Name; this.consumer10Consumption=consumer10Consumption; } public long getTime() { return time; } public PricingPeriod getPricingPeriod() { return pricingPeriod; } public double getBlueDayOffPeakHourTotal() { return blueDayOffPeakHourTotal; } public double getBlueDayPeakHourTotal() { return blueDayPeakHourTotal; } public double getWhiteDayOffPeakHourTotal() { return whiteDayOffPeakHourTotal; } public double getWhiteDayPeakHourTotal() { return whiteDayPeakHourTotal; } public double getRedDayOffPeakHourTotal() { return redDayOffPeakHourTotal; } public double getRedDayPeakHourTotal() { return redDayPeakHourTotal; } public double getTotal(PricingPeriod aPricingPeriod) { return aPricingPeriod.getTotal(this); } public double getTotalOfTotals() { int total=0; for(PricingPeriod aPricingPeriod:PricingPeriod.values()) total+=(int)(getTotal(aPricingPeriod)*1000d); return (double)total/1000d;//le passage par des int évite les erreurs d'arrondis en double } public String getConsumer1Name() { return consumer1Name; } public int getConsumer1Consumption() { return consumer1Consumption; } public String getConsumer2Name() { return consumer2Name; } public int getConsumer2Consumption() { return consumer2Consumption; } public String getConsumer3Name() { return consumer3Name; } public int getConsumer3Consumption() { return consumer3Consumption; } public String getConsumer4Name() { return consumer4Name; } public int getConsumer4Consumption() { return consumer4Consumption; } public String getConsumer5Name() { return consumer5Name; } public int getConsumer5Consumption() { return consumer5Consumption; } public String getConsumer6Name() { return consumer6Name; } public int getConsumer6Consumption() { return consumer6Consumption; } public String getConsumer7Name() { return consumer7Name; } public int getConsumer7Consumption() { return consumer7Consumption; } public String getConsumer8Name() { return consumer8Name; } public int getConsumer8Consumption() { return consumer8Consumption; } public String getConsumer9Name() { return consumer9Name; } public int getConsumer9Consumption() { return consumer9Consumption; } public String getConsumer10Name() { return consumer10Name; } public int getConsumer10Consumption() { return consumer10Consumption; } public String getConsumerName(int rank) { try { return (String)getClass().getMethod("getConsumer"+rank+"Name").invoke(this); } catch(Exception e) { return null; } } public int getConsumerConsumption(int rank) { try { return ((Integer)getClass().getMethod("getConsumer"+rank+"Consumption").invoke(this)).intValue(); } catch(Exception e) { return -1; } } public int getTotalOfConsumptions() { int total=0; for(int rank=1;rank<=10;rank++) total+=getConsumerConsumption(rank); return total; } @Override public String toString() { return getClass().getSimpleName() + "\r\n{" + "\r\n\ttime="+time+"," + "\r\n\tpricingPeriod="+pricingPeriod+"," + "\r\n\tblueDayOffPeakHourTotal="+blueDayOffPeakHourTotal+" kWh," + "\r\n\tblueDayPeakHourTotal="+blueDayPeakHourTotal+" kWh," + "\r\n\twhiteDayOffPeakHourTotal="+whiteDayOffPeakHourTotal+" kWh," + "\r\n\twhiteDayPeakHourTotal="+whiteDayPeakHourTotal+" kWh," + "\r\n\tredDayOffPeakHourTotal="+redDayOffPeakHourTotal+" kWh," + "\r\n\tredDayPeakHourTotal="+redDayPeakHourTotal+" kWh," + "\r\n\ttotalOfTotals="+getTotalOfTotals()+" kWh," + "\r\n\t\""+consumer1Name+"\"="+consumer1Consumption+" W," + "\r\n\t\""+consumer2Name+"\"="+consumer2Consumption+" W," + "\r\n\t\""+consumer3Name+"\"="+consumer3Consumption+" W," + "\r\n\t\""+consumer4Name+"\"="+consumer4Consumption+" W," + "\r\n\t\""+consumer5Name+"\"="+consumer5Consumption+" W," + "\r\n\t\""+consumer6Name+"\"="+consumer6Consumption+" W," + "\r\n\t\""+consumer7Name+"\"="+consumer7Consumption+" W," + "\r\n\t\""+consumer8Name+"\"="+consumer8Consumption+" W," + "\r\n\t\""+consumer9Name+"\"="+consumer9Consumption+" W," + "\r\n\t\""+consumer10Name+"\"="+consumer10Consumption+" W," + "\r\n\ttotalOfConsumptions="+getTotalOfConsumptions()+" W" + "\r\n}"; } public int compareTo(InstantaneousConsumption o) { return Long.compare(time,o.time); } @Override public int hashCode() { int hash=7; hash=31*hash+(int)(this.time^(this.time>>>32)); return hash; } @Override public boolean equals(Object obj) { if(this==obj) return true; if(obj==null) return false; if(getClass()!=obj.getClass()) return false; final InstantaneousConsumption other=(InstantaneousConsumption)obj; if(this.time!=other.time) return false; return true; } }
C++
UTF-8
1,125
2.59375
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define INF 0x3f3f3f3; int map[110][110],dis[110],visited[110]; void Dijkstra(int n,int x) { int i,p,j,min; for (i=1;i<=n;i++) { dis[i]=map[1][i]; visited[i]=0; } visited[x]=1; for (i=1;i<=n;i++) { min=INF; for (j=1;j<=n;j++) { if(!visited[j] && dis[j]<min) { p=j; min=dis[j]; } } visited[p]=1; for (j=1;j<=n;j++) { if(!visited[j] && dis[p]+map[p][j]<dis[j]) { dis[j]=dis[p]+map[p][j]; } } } } int main() { int n,m,i,j,a,b,t; while(scanf("%d%d",&n,&m)!=EOF,n+m) { for (i=1;i<=n;i++) { for (j=1;j<=n;j++) { map[i][j]=INF; } } for(i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&t); map[a][b]=map[b][a]=t; } Dijkstra(n,1); printf("%d\n",dis[n]); } return 0; }
Java
UTF-8
160
1.515625
2
[]
no_license
package com.ltao.service; /** * Created by ltao on 2017/10/25. */ public interface EhCacheService { public String getTimestamp(String param, int num); }
Java
UTF-8
191
2.375
2
[]
no_license
package grupp03.calculatorApplication.calculator.model; /** * Created by August on 2016-09-27. */ public interface ExpressionCalculatorStrategy<T> { T calculate(String expression); }
Markdown
UTF-8
5,938
3.625
4
[]
no_license
#### 原文地址 [嗨,你真的懂this吗?](https://juejin.im/post/5c96d0c751882511c832ff7b) #### this的绑定规则 1. 默认绑定 2. 隐式绑定 3. 硬绑定 4. new绑定 #### 默认绑定 在不能应用其他绑定规则的时候使用默认规则,通常是独立函数调用 ```js function sayHi() { console.log('hello',this.name); } var name = 'Ybettelau'; sayHi(); ``` #### 隐式绑定 函数调用实在某个对象上触发的,既调用位置上存在上下文对象。形式xxx.function() ```js fucntion sayHi() { console.log('hello',this.name); } var person = { name:'YvetteLau', sayHi:sayHi } var name ='Wiliam'; person.sayHi(); /*hello,YvetteLau*/ ``` sayHi函数在外部声明,从代码看来不属于person,但是调用person的时候,会使用person的上下文来引用函数,隐式绑定会把函数调用中的this绑定到这个上下文对象 对象属性链中只有最后一层会影响到调用位置。 ```js function sayHi() { console.log('hello',this.name); } var person2 = { name:'Christina', sayHi:sayHi } var person1 = { name:'YvetteLau', friend:person2 } person1.friend.sayHi(); /**hello,Christina**/ ``` 根据最后一层会确定this的指向,不管有多少层,在判断this的时候,我们只需要关注最后一层,也就是person2的name 隐式绑定有一个问题,绑定很容易丢失(容易给我们造成误导,我们以为this指向的是什么,但是实际并非如此). ```js function sayHi() { coonsole.log('hello',this.name); } var person = { name:'YvetteLau', sayHi:sayHi } var name = 'Wiliam'; var Hi = person.sayHi; Hi(); /**hello,Wiliam**/ ``` Hi直接指向了sayHi的引用,在调用的时候,跟person没有任何关系,xxx.fn(),fn()前如果什么都没有,那就肯定不是隐式绑定,但也不一定是默认绑定。 隐式绑定的丢失发生在回调函数中。 ```js function sayHi() { console.log('hello',this.name); } var person1 = { name:'YvetteLau', sayHi:function() { setTimeout(function(){ console.log('hello',this.name) }) } } var person2 = { name:'Christina', sayHi:sayHi, } var name ='wiliam'; person1.sayHi(); /**hello,wiliam**/ setTimeout(person2.sayHi,100); /**hello,wiliam**/ setTimeout(function(){ person2.sayHi(); },200) /**hello,Christina**/ ``` 第一个结果,setTimeout的回调函数中,this使用的是默认绑定,在严格模式下,执行的是全局对象 第二个结果,为什么xxx.fun()的时候,this没有指向xxx。 setTimeout(fn,delay) { fn(); },相当于将person2.sayHi赋值给了一个变量,最后再执行这个变量,最后sayHi中的this显然和person2九没了关系 第三个结果也在setTimeout中,但执行的是person2.sayHi(),使用的是隐式绑定,因此这是this指向的是person2,跟当前作用域没有任何关系。 #### 显式绑定 显示绑定就是通过call,apply,bind的方式,显示的指向this所指向的对象。 cally,apply和bind的第一个参数,就是对应函数的this所指向的对象。call和apply的作用一样,只是传参方式不同。call和apply都执行对应的函数,而bind方式不会。 ```js function sayHi() { console.log('hello,',this.name) } var person = { name:'YvetteLau', sayHi:sayHi } var name = 'Wiliam'; var Hi = person.sayHi; Hi.call(person); /**hello,YvetteLau**/ ``` 因为使用硬绑定将this绑定在了person上 那么使用了硬绑定,是不是意味着不会出现隐式绑定所遇到的绑定丢失列? ```js function sayHi() { console.log('hello,',this.name); } var person = { name:YvetteLau, sayHi:sayHi } var name = 'Wiliam'; var Hi = function(fn) { fn() } Hi.call(person,person.sayHi); /**hello,wiliam**/ ``` Hi.call(person,person.sayHi)的确是将this绑定到Hi中的this了。但是在执行fn的时候,相当于直接调用了sayHi方法(person.sayHi已经被赋值给fn了,隐式绑定也丢了),没有指定的this的值,对应的是默认绑定 。 在调用fn的时候,也给硬绑定 ```js function sayHi(){ console.log('hello,',this.name); } var person = { name:'Yvettelau', sayhi:sayHi } var name = 'Wiliam'; var Hi = function (fn) { fn.call(this); } Hi.call(person,person.sayHi); /**hello,Yvettelau**; ``` 因为person被绑定到了Hi函数中的this上,fn又将这个对象绑定给了sayHi的函数。此时sayHi中的this指向的就是person对象。 #### new绑定 javascript没有类,在JavaScript中,构造函数只是使用new操作符时被调用的函数,这些函数和普通的函数并没有什么不同,他不属于某个类,也不可能实例化出一个类。任何一个函数都可以使用new来调用,因此其实并不存在构造函数,而只有对于函数的'构造调用'。 使用new来调用函数,会自动执行下面的操作: 1.创建一个新对象 2.将构造函数的作用域赋值给新对象,既this指向这个新对象 3.执行构造函数中的代码 4.返回新对象 因此,我们使用new对象来调用函数的时候,就会新对象绑定到这个函数的this上。 ```js function sayHi(name) { this.name = name; } var Hi = new sayHi('Yevtte'); console.log('Hello',Hi.name) /**hello,Yevtte**/ ``` 因为在var Hi = new sayHi('Yevtte');这一步,会将sayHi中的this绑定到Hi对象上。 #### 绑定优先级 new绑定>显示绑定>隐式绑定>默认绑定 #### 绑定例外 如果我们将null或者undefined作为this的绑定对象传入call、apply或者bind,这些值在调用时被忽略,实际应用的默认绑定规则 ```js function sayHi(){ console.log('Hello,', this.name); } var person = { name: 'YvetteLau', sayHi: sayHi } var name = 'Wiliam'; var Hi = function(fn) { fn(); } Hi.call(null, person.sayHi); /**hello,Wiliam**/ ```
PHP
UTF-8
1,797
2.515625
3
[]
no_license
<?php namespace Metinet\AppBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAware; class Builder extends ContainerAware { public function mainMenu(FactoryInterface $factory, array $options) { $menu = $factory->createItem('root'); $menu->setChildrenAttributes(array("class" => "nav nav-pills")); $menu->addChild('Home', array('route' => 'home')); $menu->addChild('Random', array('route' => 'random')); $menu->addChild('Submit', array('route' => 'submit')); $menu->addChild("To Validate", array('route' => 'to_validate')); if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) { $logoutItem = $menu->addChild('Logout', array('route' => 'logout')); $logoutItem ->setLinkAttributes(array( 'id' => 'logout-link', 'class' => 'btn btn-default', )) ; } else { $menu->addChild("SignUp", array('route' => 'register')); $menu->addChild("SignIn", array('route' => 'login')); } /* // access services from the container! $em = $this->container->get('doctrine')->getManager(); // findMostRecent and Blog are just imaginary examples $fact = $em->getRepository('Metinet:AppBundle:Fact')->findMostRecent(); $menu->addChild('Latest Blog Post', array( 'route' => 'blog_show', 'routeParameters' => array('id' => $fact->getId()) )); // you can also add sub level's to your menu's as follows $menu['About Me']->addChild('Edit profile', array('route' => 'edit_profile')); // ... add more children*/ return $menu; } }
C#
UTF-8
1,602
2.875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HappyTrip.Model.Entities.Log; using System.IO; using System.Web; namespace HappyTripFileLogger { public class FileLogger : ILogger { string logFile = "TextLog.txt"; public FileLogger() { } public FileLogger(object param) { logFile = param.ToString(); } #region ILogger Members public bool WriteToLog(HappyTrip.Model.Entities.Log.LogMessage message) { bool isSuccessful = true; try { HttpContext httpContext = HttpContext.Current; string lf = httpContext.Server.MapPath("~/Log/") + logFile; StreamWriter sw = new StreamWriter(lf, true); StringBuilder sb = new StringBuilder(); sb.Append("=====HappyTripLog: Start=======\n"); sb.AppendFormat("Message: {0}\n", message.Message); sb.AppendFormat("Class Name: {0}\n", message.ClassName); sb.AppendFormat("Method Name: {0}\n", message.MethodName); sb.AppendFormat("Time of Log: {0}\n", message.MessageDateTime.ToLongTimeString() + ", " + message.MessageDateTime.ToLongDateString()); sb.Append("=====HappyTripLog: End=======\n"); string logMessage = sb.ToString(); sw.WriteLine(logMessage); sw.Close(); sw.Dispose(); } catch (Exception) { isSuccessful = false; } return isSuccessful; } #endregion } }
C++
UTF-8
1,629
3.734375
4
[ "MIT" ]
permissive
/** * Demonstrate usage std::async. */ #include <iostream> #include <future> int main() { auto sleep = []() -> int { std::this_thread::sleep_for(std::chrono::seconds(1)); return 1; }; // this spawns and execute on a new thread auto f = std::async(std::launch::async, sleep); std::cout << "You can see this immediately" << std::endl; std::cout << f.get() << " This will be shown after 1 second" << std::endl; // this will NOT spawn a new thread, execute immediately // it can be called on any thread no need to be the same as a thread called std::async to create such std::future auto f2 = std::async(std::launch::deferred, sleep); std::cout << f2.get() << " This will be shown after 1 second" << std::endl; // create std::future like this will result in setting both policy flag // it's up to implementation defined, see result for yourself whether it goes for std::launch::async or std::launch::deferred auto f3 = std::async([]() -> int { std::this_thread::sleep_for(std::chrono::seconds(2)); return 2; }); std::cout << "Did you see this immediately? If so, then implementation follows std::launch::async" << std::endl; std::cout << f3.get() << "This will be shown after 2 seconds" << std::endl; auto f4 = std::async(std::launch::async, sleep); std::cout << "f4 is launched" << std::endl; auto f5 = std::async(std::launch::async, sleep); std::cout << "f5 is launched" << std::endl; // wait from both f4, and f5 std::cout << f4.get() << " " << f5.get() << std::endl; return 0; }
Java
UTF-8
798
2.3125
2
[]
no_license
package com.epidial.utils; import org.apache.tomcat.util.codec.binary.Base64; /** * @ CreateDate : Create in 11:17 2019/5/5 * @ Explain : * @ UpdateDate : Update in * @ Author : Eestill */ public class CodeUtils { public static String encodeStr(String plainText){ byte[] b=plainText.getBytes(); Base64 base64=new Base64(); b=base64.encode(b); String s=new String(b); return s; } /** * * 创建日期2011-4-25上午10:15:11 * 修改日期 * 作者:dh *TODO 使用Base64加密 *return */ public static String decodeStr(String encodeStr){ byte[] b=encodeStr.getBytes(); Base64 base64=new Base64(); b=base64.decode(b); String s=new String(b); return s; } }
Python
UTF-8
2,605
2.578125
3
[]
no_license
# Author: Mikita Sazanovich import itertools import os import configuration def run_experiment(config, update_params, tag): generated_config = config.copy() for field_path, field_value in update_params.items(): field_parts = field_path.split('/') config_scope = generated_config for index, field in enumerate(field_parts): assert field in config_scope, f'Updating {field_path} which is unspecified in the initial config.' if index + 1 == len(field_parts): config_scope[field] = field_value else: config_scope = config_scope[field] generated_config_path = 'configs/unit/generated_duckietown_unit.yaml' configuration.dump_config(generated_config, generated_config_path) os.system(f'python train.py {tag} --config_path {generated_config_path} --summarize') def iterations_to_desc(iterations: int) -> str: return f'{iterations // 1000}K' def main(): original_config_path = 'configs/unit/duckietown_unit.yaml' config = configuration.load_config(original_config_path) iterations = 100000 channels = 16 tag_to_update_params_items = [] for map_label, map_path in [ ('DALP', 'home/zerogerc/msazanovich/aido3/data/daffy_loop_empty'), ('DAIS', 'home/zerogerc/msazanovich/aido3/data/daffy_udem1')]: for use_tcc_loss in [True, False]: for use_triplet_loss in [True, False]: if use_tcc_loss: tcc_w = 0.1 else: tcc_w = 0.0 if use_triplet_loss: triplet_w = 0.1 triplet_margin = 1.0 else: triplet_w = 0.0 triplet_margin = 0.0 tag = (f'T46-{map_label}2DUCK-{channels}' f'-TCC-{tcc_w}-TRIPLET-{triplet_w}-MAR-{triplet_margin}-{iterations_to_desc(iterations)}') update_params = { 'hyperparameters/loss/tcc_w': tcc_w, 'hyperparameters/loss/triplet_w': triplet_w, 'hyperparameters/loss/triplet_margin': triplet_margin, 'hyperparameters/iterations': iterations, 'hyperparameters/gen/ch': channels, 'hyperparameters/dis/ch': channels, 'datasets/general/datasets_dir': '/', 'datasets/domain_a/dataset_path': map_path, 'datasets/domain_b/dataset_path': 'home/zerogerc/msazanovich/duckietown-data/aido3/duckietown', } tag_to_update_params_items.append((tag, update_params)) for index in itertools.count(): item_index = index % len(tag_to_update_params_items) tag, update_params = tag_to_update_params_items[item_index] run_experiment(config, update_params, tag) if __name__ == '__main__': main()
Python
UTF-8
1,392
3.71875
4
[]
no_license
# 댓글에서 추첨해서 1명이 치킨, 3명이 커피. # 20명이 댓글을 달았다. 아이데는 1 ~ 20 이라고 가정. # 무작위로 추첨하고 중복으로 당첨은 불가능. # ramdom 모듈의 shuffle 과 sample을 활용. # 치킨 당첨자는 그냥 int # 커피 당첨자는 list from random import * # random 안에 shuffle 과 sample이 있다. lst = list(range(1, 21)) print(lst) shuffle(lst) # lst에 있는 것의 순서를 섞는다. print(lst) winner = sample(lst, 2) # lst에 있는 2개를 랜덤하게 뽑는다. print(winner) # shffle 과 sample은 동시에 쓰는 것이 좋은가? candidates = list(range(0, 21)) shuffle(candidates) first_pick = sample(candidates, 4) print('first pick: ',first_pick) second_pick = sample(first_pick, 1)[0] # print('second pick: ',second_pick) first_pick.remove(second_pick) print('''-- 당첨자 발표 -- 치킨 당첨자 : {chicken} 커피 당첨자 : {coffee} -- 축하합니다. -- '''.format(chicken = second_pick, coffee = first_pick)) # remove의 입력에는 list의 요소의 변수형이 들어가야한다. # 그런데, list가 int로 형변환되지 않아서 오류가 발생했었다. # 그래서 list의 첫 번째 요소가 int인 것에 착안하여 [0]으로 # 한 요소만을 second_pick에 저장했다. # 원래 second_pick은 int로 저장되어야 한다.
Shell
UTF-8
857
3.3125
3
[]
no_license
#!/bin/bash # Install nvidia-docker2. if ! dpkg-query -W nvidia-docker2; then # Purge nvidia-docker if it exists. docker volume ls -q -f driver=nvidia-docker | xargs -r -I{} -n1 docker ps -q -a -f volume={} | xargs -r docker rm -f sudo apt-get purge -y nvidia-docker sudo apt-get install -y nvidia-modprobe # Add the package repositories curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | \ sudo apt-key add - curl -s -L https://nvidia.github.io/nvidia-docker/ubuntu16.04/amd64/nvidia-docker.list | \ sudo tee /etc/apt/sources.list.d/nvidia-docker.list sudo apt-get update # Pin to a specific version of docker-ce and nvidia-docker2. sudo apt-get install -y nvidia-docker2=2.0.3+docker17.09.1-1 nvidia-container-runtime=2.0.0+docker17.09.1-1 # reload the Docker daemon configuration. sudo pkill -SIGHUP dockerd fi
JavaScript
UTF-8
1,403
2.96875
3
[]
no_license
/* Creamos un objeto MediaPlayer */ function MediaPlayer(config) { this.media = config.el; this.plugins = config.plugins || []; this._initPlugins(); } /* Función que inicializa los plugins */ MediaPlayer.prototype._initPlugins = function() { /* Creamos un objeto que tiene la función play, pause y dos propiedades virtuales */ const player = { play : () => this.play, pause : () => this.pause, media : this.media, /*Podemos crear una propiedad virtual con get*/ get muted(){ return this.media.muted; }, /*Podemos crear una propiedad virtual con set*/ set muted(value){ this.media.muted = value; } } /*Se le aplicara una función a cada plugin. Lo que hacemos es ejecutar cada plugin.*/ this.plugins.forEach(plugin => { /* Tenemos que llamar un método específico En este caso a plugin le pasamos como parámetro el video = this.media */ plugin.run(this.media); }); } MediaPlayer.prototype.togglePlay = function () { if (this.media.paused){ this.play(); }else{ this.pause(); } } MediaPlayer.prototype.play = function () { this.media.play(); }; MediaPlayer.prototype.pause = function () { this.media.pause(); }; MediaPlayer.prototype.mute = function () { this.media.muted = true; }; MediaPlayer.prototype.unmute = function () { this.media.muted = false; }; export default MediaPlayer;
C++
UTF-8
1,211
2.6875
3
[]
no_license
#ifndef SHADER_H #define SHADER_H #include "GLinclude.h" #include <string> class Shader { public: // program ID unsigned int ID; // constructor, generates the shader Shader(const char* vertexPath, const char* fragmentPath); // ------------------------------------------------------------------------ // activate the shader void bind() { glUseProgram(ID); } void unbind() { glUseProgram(0); } // ------------------------------------------------------------------------ // utility uniform functions void setBool(const std::string& name, bool value) const; // ------------------------------------------------------------------------ void setInt(const std::string& name, int value) const; // ------------------------------------------------------------------------ void setFloat(const std::string& name, float value) const; // ------------------------------------------------------------------------ private: // utility function for checking shader compilation/linking errors. void checkCompileErrors(unsigned int shader, std::string type); // ------------------------------------------------------------------------ }; #endif
JavaScript
UTF-8
97
3.03125
3
[]
no_license
let sum = 1; for (let i = 1; i < 51; i++) { if (i % 3 === 0 || i % 5 === 0) console.log(i); }
Java
UTF-8
198
2.578125
3
[]
no_license
package OOP_Inheritance; public class Vehicle { public void engine() { System.out.println("Vehicle ----- engine"); } public void start() { System.out.println("Vehicle ----- start"); } }
Markdown
UTF-8
1,488
3.21875
3
[]
no_license
Audio and video ------------------------------ Audio and video in javascript, are, surpringsingly easy. Sort of. Audio ------------------------------ In order to use audio in javascript one needs to have the audio loaded in at runtime, or via an audio tag. Either way, one needs to be using the correct format for that browser. [Check a website](http://www.w3schools.com/html/html5_audio.asp) to figure out what format is supported by the browsers you are targeting. As of writing this, there is **not one 'winning' format**. Instead, you will probably need to use a combination of mp3/wav to hit all browers. Well then, the Audio Tag ------------------------------ Getting sound into our web pages isn't too hard, use the audio tag ``` <audio id="myAudio"> <source src="horse.wav" type="audio/wav"> <source src="horse.mp3" type="audio/mpeg"> </audio> ``` Playing a sound ---------------------------- ``` var myAudio = document.getElementById('myAudio'); myAudio.play(); ``` Listening for sound events ---------------------------- There's more to life than mouse events. Let's listen for when a sound ends: ``` myAudio.addEventListener('ended', function(event) { //Sound is over. }) ``` Changing the audio to be played ---------------------------- ``` myAudio.src = "new/url/to/file.wav"; ``` Audio events ---------------------------- - A few key ones - **ended**: fires when the audio has finished playing - **canplay**: fires when the audio is loaded enough to play
Markdown
UTF-8
1,491
3.1875
3
[]
no_license
# Charge.js Example This directory is a brief example of a [Charge.js](https://charge.js.org/) site using the [@now/static-build](https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build) Builder. ## Initializing this Example To get started with Charge.js on Now, you can use the [Now CLI](https://zeit.co/docs/v2/getting-started/installation#now-cli) to initialize the project: ```shell $ now init charge ``` ## Example Contents The example consists of one source directory, `/source`, which contains an index and layout component. `/source` also includes a `/pages` directory where `.mdx` files are stored. This file structure is very basic as Charge focuses on simplicity, however, you are free to use whatever file structure suits your needs best. The example also includes a `now.json` file, this is used to configure your build when deploying to Now. The `package.json` has seen some minor changes with the addition of scripts from the Charge.js [documentation](https://charge.js.org/usage) along with a `now-build` script used by Now in deployment. ## Resources For more information on how you can deploy your own Charge.js sites, see the following resources: - [Our Static Builder (@now/static-build) documentation](https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build) - [The basics of deploying on Now](https://zeit.co/docs/v2/deployments/basics/) - [The official Charge.js documentation](https://charge.js.org/)
Markdown
UTF-8
2,856
2.984375
3
[]
no_license
# Generative Art Workshop (IAP 2021) [![Binder](https://mybinder.org/badge_logo.svg)](https://gke2.mybinder.org/v2/gh/gvarnavi/generative-art-iap-binder-env/main?urlpath=git-pull%3Frepo%3Dhttps%253A%252F%252Fgithub.com%252Fgvarnavi%252Fgenerative-art-iap%26urlpath%3Dtree%252Fgenerative-art-iap%252F%26branch%3Dmaster) This is the git repository of the generative art workshop, taught by Jovana Andrejevic, Nina Andrejevic, and George Varnavides, in IAP 2021. This is the fourth iteration of the generative art workshop taught over IAP by the instructors (previously taught in 2017 and 2018 with Emma Vargo, and in 2020 with Amina Matt). We are indebted to Emma and Amina for some of the original content we'll use in the workshop. ## Communication There are three main ways in which we'll communicate for this class. * [Github repository](https://github.com/gvarnavi/generative-art-iap): To access the notebooks and files used in class * [Generative Art 2021 Slack workspace](https://join.slack.com/t/generativeart2021/shared_invite/zt-knj01qsy-5UvufhL4cBrjFEm6o9A~_g): To communicate with the instructors and each other (primary means of communication) * [generative-art-2021@mit.edu Mailing list](https://groups.mit.edu/webmoira/list/generative-art-2021): To communicate class-wide announcements (will be used very sparsely) ## Programming Languages While there are many great programming and scripting languages to do generative art with, the class will be taught using Python and the Wolfram Language. This choice is partly due to the following reasons (aside from the instructors' familiarity with these languages): 1. Ease of prototyping (and learning) code 2. Built-in (high-level) visualization functions 3. The interactive Notebook format compliments the way we prototype and think of generative art This last point also motivates the use of Jupyter notebooks in particular. We'll use [mybinder.org](https://mybinder.org/) to share fully-executable notebooks with both Python and Wolfram Language kernels. Note that we'll try and provide *most* of the content in both languages; while we'll alternate presenting certain concepts in Mathematica and others in Python, you will have the corresponding notebook in the other language for reference. ### Installation instructions You shouldn't need to install anything to follow-along! Just follow the link to [![Binder](https://mybinder.org/badge_logo.svg)](https://gke2.mybinder.org/v2/gh/gvarnavi/generative-art-iap-binder-env/main?urlpath=git-pull%3Frepo%3Dhttps%253A%252F%252Fgithub.com%252Fgvarnavi%252Fgenerative-art-iap%26urlpath%3Dtree%252Fgenerative-art-iap%252F%26branch%3Dmaster) (you might have to wait a bit for instance to launch). If you prefer to clone the repository and follow-along locally, follow [these instructions](https://github.com/WolframResearch/WolframLanguageForJupyter) to set up a Wolfram Engine kernel with jupyter.
TypeScript
UTF-8
165
2.5625
3
[]
no_license
interface LcuGameSessionData { gameData: GameData; phase: string; } interface GameData { gameId: number; queue: Queue; } interface Queue { id: number; }
Java
UTF-8
320
2.140625
2
[]
no_license
package weatherreporter.dataclasses; /** * Created by Ravi on 1/12/2015. */ public class AllData { public AllWeatherData mAllWeatherData; public AllForecastData mAllForecastData; public AllData() { mAllWeatherData = new AllWeatherData(); mAllForecastData = new AllForecastData(); } }
Java
UTF-8
3,332
3.8125
4
[]
no_license
package M9D12; import java.util.Scanner; /** * 企业发放的奖金根据利润提成 * @version 1.0 * @author 孔德成 */ /* Python if 逻辑 if (profit > 100) { // 高于100万元时,超过100万元的部分按1%提成; bonus += (profit-100)*(1.0/100); }else if (profit>60 && profit <=100) { if (profit > 100) { profit = 100; } // 60万到100万之间时,高于60万元的部分,可提成1.5%, bonus += (profit-60)*(1.5/100); }else if (profit>40 && profit<=60) { if (profit > 60) { profit = 60; } // 40万到60万之间时高于40万元的部分,可提成3%; bonus += (profit-40)*(3.0/100); }else if (profit>20 && profit <=40) { if (profit > 40) { profit = 40; } // 20万到40万之间时,高于20万元的部分,可提成5%; bonus += (profit-20)*(5.0/100); }else if (profit>10 && profit<=20) { if (profit > 20) { profit = 20; } // 高于10万元的部分,可可提成7.5%; bonus += (profit-10)*(7.5/100); }else if (profit > 0){ // 利润低于或等于10万元时,奖金可提10%; bonus += profit * (10.0/100); } System.out.println("当月利润为:"+profit+unit+" 发放奖金为:"+bonus+unit); */ class Quiz4 extends Quiz{ void show() { System.out.println("现在运行的是实验4--------"); Scanner in = new Scanner(System.in); System.out.println("请输入当月利润:"); double profit = in.nextDouble(); String unit = "万"; double bonus = 0; if (profit > 100) { // 高于100万元时,超过100万元的部分按1%提成; bonus = (profit-100)*(1.0/100)+(100-60)*(1.5/100)+(60-40)*(3.0/100)+(40-20)*(5.0/100)+(20-10)*(7.5/100)+10*(10.0/100); }else if (profit>60 && profit <=100) { // 60万到100万之间时,高于60万元的部分,可提成1.5%, bonus = (profit-60)*(1.5/100)+(60-40)*(3.0/100)+(40-20)*(5.0/100)+(20-10)*(7.5/100)+10*(10.0/100); }else if (profit>40 && profit<=60) { // 40万到60万之间时高于40万元的部分,可提成3%; bonus = (profit-40)*(3.0/100)+(40-20)*(5.0/100)+(20-10)*(7.5/100)+10*(10.0/100); }else if (profit>20 && profit <=40) { if (profit > 40) { profit = 40; } // 20万到40万之间时,高于20万元的部分,可提成5%; bonus = (40-20)*(5.0/100)+(20-10)*(7.5/100)+10*(10.0/100); }else if (profit>10 && profit<=20) { if (profit > 20) { profit = 20; } // 高于10万元的部分,可可提成7.5%; bonus = (profit-10)*(7.5/100)+10*(10.0/100); }else if (profit <= 10){ // 利润低于或等于10万元时,奖金可提10%; bonus = profit * (10.0/100); } System.out.println("当月利润为:"+profit+unit+" 发放奖金为:"+bonus+unit); System.out.println("实验4展示完成--------"); } }
Python
UTF-8
7,914
2.78125
3
[ "MIT" ]
permissive
import os import glob import click import pickle import zipfile import datetime import pandas as pd @click.command() @click.option('--redmine_instance', help='Path to pickled Redmine API instance') @click.option('--issue', help='Path to pickled Redmine issue') @click.option('--work_dir', help='Path to Redmine issue work directory') @click.option('--description', help='Path to pickled Redmine description') def qiimecombine_redmine(redmine_instance, issue, work_dir, description): # Unpickle Redmine objects redmine_instance = pickle.load(open(redmine_instance, 'rb')) issue = pickle.load(open(issue, 'rb')) description = pickle.load(open(description, 'rb')) """ Description is expected to be in the following format. level=taxlevel column_header=column_sample # Allow searching on more than one column header by adding more lines optional! startdate-enddate. If not provided, assume we want to search all. For column_header=column_sample rows, using a ~ instead of an = will allow for searching for partial matches instead of complete So an example would be: level=5 sample_type=meat 180401-190408 """ # Parse description try: level, column_headers, column_contents, start_date, end_date, operators = parse_description(description) except: # Don't try to be too specific here, this could blow up in many ways. redmine_instance.issue.update(resource_id=issue.id, status_id=4, notes='Your description was not formatted correctly. See DOCS for a description ' 'of how to format the description.') return tax_barplots = glob.glob('/mnt/nas2/processed_sequence_data/miseq_assemblies/*/qiime2/taxonomy_barplot.qzv') # As it turns out, qiime2 qzv files are actually just zip files with a bunch of data/metadata. # https://github.com/joey711/phyloseq/issues/830 # Getting at data seems to be easiest if we just unzip and read in the relevant csv files with pandas for tax_barplot in tax_barplots: # Check the date of the assembly to see if it's in our range. date_string = tax_barplot.split('/')[-3] run_date = string_to_year(date_string) if start_date < run_date < end_date: cmd = 'cp {} {}'.format(tax_barplot, work_dir) os.system(cmd) output_dir = os.path.join(work_dir, tax_barplot.split('/')[-3]) with zipfile.ZipFile(os.path.join(work_dir, 'taxonomy_barplot.qzv'), 'r') as zipomatic: zipomatic.extractall(output_dir) # Now we should have folders for all of our QIIME2 runs (named with as run dates). # Grab the csv file for level of interest for all of them. dataframe_list = list() csv_files = glob.glob(os.path.join(work_dir, '*', '*', 'data', 'level-{}.csv'.format(level))) for csv_file in csv_files: df = pd.read_csv(csv_file) for column in df.columns: df.rename(columns={column: column.replace(' ', '_').upper()}, inplace=True) try: df = df.apply(lambda x: x.astype(str).str.upper()) for j in range(len(column_headers)): column_header = column_headers[j] column_content = column_contents[j] if operators[j] == 'equals': df = df.loc[df[column_header] == column_content] elif operators[j] == 'contains': df = df.loc[df[column_header].str.contains(column_content)] dataframe_list.append(df) except KeyError: redmine_instance.issue.update(resource_id=issue.id, notes='WARNING: Could not find column {} in run {}'.format(column_header, csv_file.split('/')[-4])) output_list = list() output_dict = dict() output_dict['path'] = os.path.join(work_dir, 'results.csv') output_dict['filename'] = 'QIIMEcombine_results.csv' output_list.append(output_dict) result_df = pd.concat(dataframe_list, ignore_index=True, sort=False) result_df.fillna(0, inplace=True) # Drop any columns that are entirely zeros. Might be a more pandas-esque way to do this, but this works and is fast. columns_to_drop = list() for column in result_df.columns: all_zeros = True for item in result_df[column]: if str(item) != '0': all_zeros = False if all_zeros is True: columns_to_drop.append(column) result_df = result_df.drop(columns_to_drop, axis=1) # Also want to reorder the columns. Need to have index first, then all the taxonomy information, and then everything # else. output_column_order = ['INDEX'] # First pass through - grab all the taxonomy information. for column in result_df.columns: if column.startswith('D_'): output_column_order.append(column) # Final pass - grab everything else. for column in result_df.columns: if column != 'INDEX' and not column.startswith('D_'): output_column_order.append(column) result_df = result_df[output_column_order] result_df.to_csv(os.path.join(work_dir, 'results.csv'), index=False) # Clean up files. cmd = 'rm -r {}'.format(os.path.join(work_dir, '*/')) os.system(cmd) # Upload files, set status to Feedback redmine_instance.issue.update(resource_id=issue.id, status_id=4, uploads=output_list, notes='QIIMECombine complete. See attached file for results.') def string_to_year(yymmdd_string): year = int('20' + yymmdd_string[:2]) month = int(yymmdd_string[2:4]) day = int(yymmdd_string[4:6]) return datetime.datetime(year, month, day) def parse_description(description): level = description[0].split('=')[1] column_headers = list() column_content = list() operators = list() # If last line of description doesn't have = or ~, it contains a date. if '=' not in description[-1] and '~' not in description[-1]: for i in range(1, len(description) - 1): if '=' in description[i]: column_headers.append(description[i].split('=')[0].upper().replace(' ', '_')) column_content.append(description[i].split('=')[1].upper()) operators.append('equals') elif '~' in description[i]: column_headers.append(description[i].split('~')[0].upper().replace(' ', '_')) column_content.append(description[i].split('~')[1].upper()) operators.append('contains') start_date = description[-1].split('-')[0] start_date = string_to_year(start_date) end_date = description[-1].split('-')[1] end_date = string_to_year(end_date) else: # If no date range included in description, have date range include everything. for i in range(1, len(description)): if '=' in description[i]: column_headers.append(description[i].split('=')[0].upper().replace(' ', '_')) column_content.append(description[i].split('=')[1].upper()) operators.append('equals') elif '~' in description[i]: column_headers.append(description[i].split('~')[0].upper().replace(' ', '_')) column_content.append(description[i].split('~')[1].upper()) operators.append('contains') start_date = string_to_year('111111') end_date = string_to_year('991111') return level, column_headers, column_content, start_date, end_date, operators if __name__ == '__main__': qiimecombine_redmine()
Java
UTF-8
1,969
4.0625
4
[]
no_license
package com.swj.ics.ThreadSimple; import java.util.concurrent.TimeUnit; /** * Created by swj on 2018/1/1.\ * 中断:其他线程通过调用该线程的interrupt方法对其进行中断操作。 * 线程通过检查自身是否被中断来进行响应。线程通过isInterrupted方法来进行判断 */ public class InterruptedDemo { public static void main(String[] args) throws InterruptedException { Thread sleepThread = new Thread(new SleepRunner(),"SleepThread"); Thread runThread = new Thread(new BusyRunner(),"runThread"); sleepThread.setDaemon(true); runThread.setDaemon(true); sleepThread.start(); runThread.start(); //主线程休眠5秒,让sleepThread和busyThread充分运行 TimeUnit.SECONDS.sleep(5); sleepThread.interrupt(); runThread.interrupt(); System.out.println("SleepThread interrupted is : "+ sleepThread.isInterrupted()); System.out.println("RunThread interrupted is : "+ runThread.isInterrupted()); /** * 输入结果为 * SleepThread interrupted is : false RunThread interrupted is : true */ //SleepThread在抛出InterruptedException之前,会先把该进程中的中断标示位清除 //然后抛出InterruptedException,此时调用isInterrupted()方法会返回false //而一直忙碌的BusyThread, } static class SleepRunner implements Runnable { @Override public void run() { while (true) { try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class BusyRunner implements Runnable { @Override public void run() { while (true) { } } } }
C++
UTF-8
583
2.671875
3
[]
no_license
#include "Arch/x86/Keyboard.h" #include <ncurses.h> bool Arch::x86::Keyboard::getState(Core::Keyboard::Key key) const { switch (key) { case Core::Keyboard::UP: return _currentKey == KEY_UP; case Core::Keyboard::DOWN: return _currentKey == KEY_DOWN; case Core::Keyboard::LEFT: return _currentKey == KEY_LEFT; case Core::Keyboard::RIGHT: return _currentKey == KEY_RIGHT; default: return false; } } void Arch::x86::Keyboard::setCurrentKey(int key) { _currentKey = key; }
C++
UTF-8
1,868
3.109375
3
[]
no_license
#include <fstream> #include <iostream> #include <utility> #include <vector> #include <limits.h> #include <algorithm> using std::cout; using std::vector; using std::ifstream; using std::pair; using std::min; using std::max; using std::sort; class Dsu { private: vector<long long> parent; public: Dsu() { } Dsu(long long n) { for (int i = 0; i < n; ++i) { parent.push_back(i); } } long long getParent(long long a) { if (parent[a] != a) { long long parentA = this->getParent(parent[a]); parent[a] = parentA; } return parent[a]; } bool join(long long a, long long b) { a = this->getParent(a); b = this->getParent(b); parent[a] = parent[b]; } }; void readData(vector<vector<long long>>& edges, int& cntVertex) { ifstream fin("input.txt"); int m = 0; fin >> cntVertex >> m; long long u = 0; long long v = 0; long long price = 0; for (int i = 0; i < m; ++i) { fin >> u >> v >> price; --u; --v; edges.push_back({price, u, v}); } sort(edges.begin(), edges.end()); fin.close(); } void mst(vector<vector<long long>>& edges, int cntVertex) { Dsu sets(cntVertex); int u = 0; int v = 0; long long price = 0; long long minCost = 0; for (vector<long long> edge : edges) { price = edge[0]; u = edge[1]; v = edge[2]; if (sets.getParent(u) != sets.getParent(v)) { minCost += price; sets.join(u, v); } } cout << minCost; } int main() { vector<vector<long long>> edges; int cntVertex = 0; readData(edges, cntVertex); mst(edges, cntVertex); return 0; }
Java
UTF-8
499
1.835938
2
[]
no_license
package com.wanlai.kafkatest; import com.wanlai.kafkatest.kafka.KafkaProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired KafkaProducer kafkaProducer; @RequestMapping("/test") public String sss() { kafkaProducer.send("this is message"); return "ok"; } }
Markdown
UTF-8
1,065
4.25
4
[]
no_license
# Reversing an Array Write a function arrayToList that builds up a list structure like the one shown when given [1, 2, 3] as argument. Also write a listToArray function that produces an array from a list. Then add a helper function prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list (with zero referring to the first element) or undefined when there is no such element. If you haven’t already, also write a recursive version of nth. ``` console.log(arrayToList([10, 20])); // → {value: 10, rest: {value: 20, rest: null}} console.log(listToArray(arrayToList([10, 20, 30]))); // → [10, 20, 30] console.log(prepend(10, prepend(20, null))); // → {value: 10, rest: {value: 20, rest: null}} console.log(nth(arrayToList([10, 20, 30]), 1)); // → 20 ``` ## To test Run `$ node index.js` ## Book solution [<https://eloquentjavascript.net/code/#4.3>](https://eloquentjavascript.net/code/#4.3)
PHP
UTF-8
566
4.4375
4
[]
no_license
<?php /* * A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. * * Find the largest palindrome made from the product of two 3-digit numbers. */ function maxpalindrome(){ $palindrome = array(); for($i=100; $i<=999; $i++){ for($j=999; $j>=100; $j--){ $prod = (string)$i*$j; if($prod == strrev($prod)){ $palindrome[] = (int)$prod; } } } return $palindrome; } echo "Largest palindrome made from the product of two 3-digit numbers : ".max(maxpalindrome()); ?>
Java
UTF-8
11,510
1.734375
2
[]
no_license
/* * Decompiled with CFR 0_124. * * Could not load the following classes: * javax.servlet.http.HttpServletRequest * javax.servlet.http.HttpSession * org.hibernate.HibernateException * org.hibernate.Query * org.hibernate.Session * org.hibernate.SessionFactory * org.springframework.beans.factory.annotation.Autowired * org.springframework.orm.hibernate4.HibernateCallback * org.springframework.orm.hibernate4.HibernateTemplate * org.springframework.orm.hibernate4.support.HibernateDaoSupport * org.springframework.stereotype.Component */ package com.trade.dao.impl; import com.gy.util.StringUtil; import com.manage.bean.OprInfo; import com.manage.bean.PageModle; import com.trade.bean.own.MerchantInf; import com.trade.bean.own.PayChannelInf; import com.trade.dao.MerchantInfDao; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate4.HibernateCallback; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.springframework.stereotype.Component; @Component public class MerchantInfDaoImpl extends HibernateDaoSupport implements MerchantInfDao { @Autowired private HttpSession session; @Autowired private HttpServletRequest request; @Override public MerchantInf getMchtInfo(String mchtNo) { return (MerchantInf)this.getHibernateTemplate().get(MerchantInf.class, (Serializable)((Object)mchtNo)); } @Override public PayChannelInf getChannelInf(String channelId, String channelMchtNo) { PayChannelInf param = new PayChannelInf(channelId, channelMchtNo); return (PayChannelInf)this.getHibernateTemplate().get(PayChannelInf.class, (Serializable)param); } @Override public PageModle<MerchantInf> listMchtInfoByPage(final Map<String, String> param, final int pageNum, final int perPageNum, final OprInfo oprInfo) { return (PageModle)this.getHibernateTemplate().execute((HibernateCallback)new HibernateCallback<PageModle<MerchantInf>>(){ public PageModle<MerchantInf> doInHibernate(Session session) throws HibernateException { HashMap<String, String> queryParam = new HashMap<String, String>(); StringBuffer where = new StringBuffer(" MerchantInf t, OprInfo c where t.company_id=c.company_id "); if (!StringUtil.isEmpty((String)param.get("company_id"))) { where.append("and t.company_id=:company_id "); queryParam.put("company_id", (String)param.get("company_id")); } if (!StringUtil.isEmpty((String)param.get("mchtNo"))) { where.append("and t.mchtNo=:mchtNo "); queryParam.put("mchtNo", (String)param.get("mchtNo")); } if (!StringUtil.isEmpty((String)param.get("identity_no"))) { where.append("and t.identity_no=:identity_no "); queryParam.put("identity_no", (String)param.get("identity_no")); } if (oprInfo == null || !"1".equals(oprInfo.getOpr_type())) { where.append(" and t.company_id='" + oprInfo.getCompany_id() + "' "); } where.append("order by t.crtTime desc"); String sql = "select distinct t,c.company_name from" + where.toString(); String countSql = "SELECT count(*) from " + where; Query query = session.createQuery(sql); Query queryCount = session.createQuery(countSql); for (Map.Entry entry : queryParam.entrySet()) { if (entry.getValue() == null || "".equals(entry.getValue())) continue; query.setParameter((String)entry.getKey(), entry.getValue()); queryCount.setParameter((String)entry.getKey(), entry.getValue()); } if (pageNum > 0 || perPageNum > 0) { query.setFirstResult((pageNum - 1) * perPageNum); query.setMaxResults(perPageNum); } List<Object[]> result = query.list(); ArrayList<MerchantInf> list = new ArrayList<MerchantInf>(); for (Object[] objs : result) { MerchantInf mcht = (MerchantInf)objs[0]; String companyName = (String)objs[1]; mcht.setCompanyName(companyName); list.add(mcht); } result = null; int total = Integer.valueOf(queryCount.uniqueResult().toString()); PageModle<MerchantInf> pageModle = new PageModle<MerchantInf>(); pageModle.setData(list); pageModle.setPerPageNum(perPageNum); pageModle.setCurrentPage(pageNum); pageModle.setTotalNum(total); pageModle.setTotalPage(total / perPageNum + (total % perPageNum == 0 ? 0 : 1)); return pageModle; } }); } @Override public List<MerchantInf> listAllMcht(final Map<String, String> param, final OprInfo oprInfo) { return (List)this.getHibernateTemplate().execute((HibernateCallback)new HibernateCallback<List<MerchantInf>>(){ public List<MerchantInf> doInHibernate(Session session) throws HibernateException { HashMap<String, String> queryParam = new HashMap<String, String>(); StringBuffer where = new StringBuffer(" MerchantInf t, OprInfo c where t.company_id=c.company_id "); if (!StringUtil.isEmpty((String)param.get("company_id"))) { where.append("and t.company_id=:company_id "); queryParam.put("company_id", (String)param.get("company_id")); } if (!StringUtil.isEmpty((String)param.get("mchtNo"))) { where.append("and t.mchtNo=:mchtNo "); queryParam.put("mchtNo", (String)param.get("mchtNo")); } if (!StringUtil.isEmpty((String)param.get("identity_no"))) { where.append("and t.identity_no=:identity_no "); queryParam.put("identity_no", (String)param.get("identity_no")); } if (oprInfo == null || !"1".equals(oprInfo.getOpr_type())) { where.append(" and t.company_id='" + oprInfo.getCompany_id() + "' "); } where.append("order by t.crtTime desc"); String sql = "select distinct t,c.company_name from " + where.toString(); Query query = session.createQuery(sql); for (Map.Entry entry : queryParam.entrySet()) { if (entry.getValue() == null || "".equals(entry.getValue())) continue; query.setParameter((String)entry.getKey(), entry.getValue()); } List<Object[]> result = query.list(); ArrayList<MerchantInf> list = new ArrayList<MerchantInf>(); for (Object[] objs : result) { MerchantInf mcht = (MerchantInf)objs[0]; String companyName = (String)objs[1]; mcht.setCompanyName(companyName); list.add(mcht); } result = null; return list; } }); } @Override public List<Map<String, String>> listAllMchtMap(Map<String, String> param, OprInfo oprInfo) { return (List)this.getHibernateTemplate().execute((HibernateCallback)new HibernateCallback<List<Map<String, String>>>(){ public List<Map<String, String>> doInHibernate(Session session) throws HibernateException { return null; } }); } @Override public PageModle<PayChannelInf> listChannelMchtInfoByPage(final Map<String, String> param, final int pageNum, final int perPageNum) { OprInfo oprInfo = (OprInfo)this.session.getAttribute("oprInfo"); return (PageModle)this.getHibernateTemplate().execute((HibernateCallback)new HibernateCallback<PageModle<PayChannelInf>>(){ public PageModle<PayChannelInf> doInHibernate(Session session) throws HibernateException { HashMap<String, String> queryParam = new HashMap<String, String>(); StringBuffer where = new StringBuffer(" PayChannelInf t where 1=1 "); if (!StringUtil.isEmpty((String)param.get("channel_mcht_no"))) { where.append("and t.channel_mcht_no=:channel_mcht_no "); queryParam.put("channel_mcht_no", (String)param.get("channel_mcht_no")); } if (!StringUtil.isEmpty((String)param.get("channel_id"))) { where.append("and t.channel_id=:channel_id "); queryParam.put("channel_id", (String)param.get("channel_id")); } where.append("order by t.crt_time desc"); String sql = "select t from " + where.toString(); String countSql = "SELECT count(*) from " + where; Query query = session.createQuery(sql); Query queryCount = session.createQuery(countSql); for (Map.Entry entry : queryParam.entrySet()) { if (entry.getValue() == null || "".equals(entry.getValue())) continue; query.setParameter((String)entry.getKey(), entry.getValue()); queryCount.setParameter((String)entry.getKey(), entry.getValue()); } if (pageNum > 0 || perPageNum > 0) { query.setFirstResult((pageNum - 1) * perPageNum); query.setMaxResults(perPageNum); } List list = query.list(); int total = Integer.valueOf(queryCount.uniqueResult().toString()); PageModle<PayChannelInf> pageModle = new PageModle<PayChannelInf>(); pageModle.setData(list); pageModle.setPerPageNum(perPageNum); pageModle.setCurrentPage(pageNum); pageModle.setTotalNum(total); pageModle.setTotalPage(total / perPageNum + (total % perPageNum == 0 ? 0 : 1)); return pageModle; } }); } @Override public void saveMchtInfo(MerchantInf mchtInfo) { this.getHibernateTemplate().save((Object)mchtInfo); } @Override public void updateMchtInfo(MerchantInf mchtInfo) { this.getHibernateTemplate().update((Object)mchtInfo); } @Resource(name="sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } @Override public void saveChannelInf(PayChannelInf channelInf) { this.getHibernateTemplate().save((Object)channelInf); } @Override public void updateChannelInf(PayChannelInf channelInf) { this.getHibernateTemplate().update((Object)channelInf); } }
PHP
UTF-8
4,565
2.765625
3
[]
no_license
<?php namespace App\Command; use App\Entity\InstagramAccount; use App\Entity\User; use App\Entity\VkAccount; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; /** * Class AddAccountsToUserCommand * @package App\Command */ class AddAccountsToUserCommand extends Command { const ADMIN_USERNAME = 'admin'; protected static $defaultName = 'app:add-accounts-to-user'; /** * @var EntityManagerInterface */ private $em; /** * @var ParameterBagInterface */ private $params; /** * @var array */ private $repos; /** * AddAccountsToUserCommand constructor. * @param EntityManagerInterface $em * @param ParameterBagInterface $params */ public function __construct(EntityManagerInterface $em, ParameterBagInterface $params) { parent::__construct(); $this->em = $em; $this->repos = [ InstagramAccount::class => $em->getRepository(InstagramAccount::class), VkAccount::class => $em->getRepository(VkAccount::class), ]; $this->params = $params; } /** * @{@inheritdoc} */ protected function configure() { $this ->addArgument('username', InputArgument::OPTIONAL, 'User name, default - main admin user') ->setDescription('Adding all instagram and vk accounts to needed user'); } /** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); if (!$username = $input->getArgument('username')) { $username = self::ADMIN_USERNAME; } try { /** @var User|null $user */ if (!$user = $this->em->getRepository(User::class)->findOneBy(['username' => $username])) { throw new \RuntimeException("User {$username} not found"); } $accountsDB = [ InstagramAccount::class => $this->getObjectsIds($this->repos[InstagramAccount::class]->findAll()), VkAccount::class => $this->getObjectsIds($this->repos[VkAccount::class]->findAll()), ]; $accountsUser = [ InstagramAccount::class => $this->getObjectsIds($user->getInstagramAccounts()->toArray()), VkAccount::class => $this->getObjectsIds($user->getVkAccounts()->toArray()), ]; $accountsNeed = [ InstagramAccount::class => array_diff($accountsDB[InstagramAccount::class], $accountsUser[InstagramAccount::class]), VkAccount::class => array_diff($accountsDB[VkAccount::class], $accountsUser[VkAccount::class]), ]; foreach ($accountsNeed as $type => $ids) { if (!$ids) { $output->writeln("New accounts $type for user not found"); continue; } $output->writeln("Found new accounts $type for user: " . implode(',', $ids)); $output->writeln('Adding accounts...'); $accounts = $this->repos[$type]->findBy(['id' => $ids]); foreach ($accounts as $account) { if ($account instanceof InstagramAccount) { $user->addInstagramAccount($account); } if ($account instanceof VkAccount) { $user->addVkAccount($account); } $this->em->persist($user); } $this->em->flush(); } $output->writeln('Done!'); } catch (\Throwable $e) { $io->error( 'An unexpected error occurred'.PHP_EOL.PHP_EOL. $e->getMessage() ); } } /** * Get array of object ids * * @param array $objects * * @return array */ private function getObjectsIds(array $objects) { return array_map(function ($object) {return $object->getId();}, $objects); } }
Python
UTF-8
2,251
3.953125
4
[ "Unlicense" ]
permissive
""" CHANGE Change calculator Port by Dave LeCompte """ PAGE_WIDTH = 64 def print_centered(msg): spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) print(spaces + msg) def print_header(title): print_centered(title) print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() print() print() def print_introduction(): print("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE") print("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100.") print() print() def pennies_to_dollar_string(p): d = p / 100 ds = f"${d:0.2f}" return ds def compute_change(): print("COST OF ITEM?") cost = float(input()) print("AMOUNT OF PAYMENT?") payment = float(input()) change_in_pennies = round((payment - cost) * 100) if change_in_pennies == 0: print("CORRECT AMOUNT, THANK YOU.") return if change_in_pennies < 0: short = -change_in_pennies / 100 print(f"SORRY, YOU HAVE SHORT-CHANGED ME ${short:0.2f}") print() return print(f"YOUR CHANGE, {pennies_to_dollar_string(change_in_pennies)}") d = change_in_pennies // 1000 if d > 0: print(f"{d} TEN DOLLAR BILL(S)") change_in_pennies -= d * 1000 e = change_in_pennies // 500 if e > 0: print(f"{e} FIVE DOLLAR BILL(S)") change_in_pennies -= e * 500 f = change_in_pennies // 100 if f > 0: print(f"{f} ONE DOLLAR BILL(S)") change_in_pennies -= f * 100 g = change_in_pennies // 50 if g > 0: print("ONE HALF DOLLAR") change_in_pennies -= g * 50 h = change_in_pennies // 25 if h > 0: print(f"{h} QUARTER(S)") change_in_pennies -= h * 25 i = change_in_pennies // 10 if i > 0: print(f"{i} DIME(S)") change_in_pennies -= i * 10 j = change_in_pennies // 5 if j > 0: print(f"{j} NICKEL(S)") change_in_pennies -= j * 5 if change_in_pennies > 0: print(f"{change_in_pennies} PENNY(S)") def print_thanks(): print("THANK YOU, COME AGAIN.") print() print() def main(): print_header("CHANGE") print_introduction() while True: compute_change() print_thanks() if __name__ == "__main__": main()
Java
UHC
818
3.796875
4
[]
no_license
package day4; import java.util.Scanner; public class Home { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Է"); // ̸ ϵ ̵ System.out.println("̸ :"); String name = sc.next(); System.out.println("e-mail : "); String email = sc.next(); System.out.println(" Է:"); int age = sc.nextInt(); System.out.println("\n " + "̸ : " + name + " " + "e-mail : " + email + " : " + age); Member m = new Member(); m.setName(name); m.setEmail(email); m.setAge(age); System.out.println("\n " + " ̸ : " + m.getName() + " e-mail : " + m.getEmail() + " : " + m.getAge()); } }
C#
UTF-8
1,883
2.703125
3
[ "Apache-2.0" ]
permissive
namespace NUnitRetrying.Environment { using log4net; using NUnit.Framework; using System; using System.Configuration; /// <summary> /// Environment Configuration /// </summary> public static class Configuration { /// <summary> /// The logger instance. /// </summary> private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The retry times number. /// </summary> public static int RetryTimes = GetInt("retryTimes", 1); /// <summary> /// Gets an int value from the configuration or the NUnit parameter. /// </summary> /// <param name="configurationPropertyName">The configuration name.</param> /// <param name="defaultValue">The default value if the configuration is not found.</param> /// <returns>returns .</returns> private static int GetInt(string configurationPropertyName, int defaultValue) { if (!string.IsNullOrEmpty(TestContext.Parameters.Get(configurationPropertyName))) { return int.Parse(TestContext.Parameters.Get(configurationPropertyName)); } else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[configurationPropertyName])) { try { return int.Parse(ConfigurationManager.AppSettings[configurationPropertyName]); } catch (Exception) { Console.Error.WriteLine(string.Format("Invalid value for property: [{0}]", configurationPropertyName)); return defaultValue; } } else { return defaultValue; } } } }
Python
UTF-8
9,483
2.59375
3
[ "Apache-2.0" ]
permissive
import math import torch import warnings import itertools import numbers from torch.nn.modules import Module from torch.nn.parameter import Parameter from torch.nn.utils.rnn import PackedSequence from torch.nn import init _VF = torch._C._VariableFunctions _rnn_impls = { 'LSTM': _VF.lstm, 'GRU': _VF.gru, 'RNN_TANH': _VF.rnn_tanh, 'RNN_RELU': _VF.rnn_relu, } class RNNBase(Module): def __init__(self, mode, input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0, bidirectional=False): super(RNNBase, self).__init__() self.mode = mode self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.bias = bias self.batch_first = batch_first self.dropout = dropout self.bidirectional = bidirectional num_directions = 2 if bidirectional else 1 if not isinstance(dropout, numbers.Number) or not 0 <= dropout <= 1 or \ isinstance(dropout, bool): raise ValueError("dropout should be a number in range [0, 1] " "representing the probability of an element being " "zeroed") if dropout > 0 and num_layers == 1: warnings.warn("dropout option adds dropout after all but last " "recurrent layer, so non-zero dropout expects " "num_layers greater than 1, but got dropout={} and " "num_layers={}".format(dropout, num_layers)) if mode == 'LSTM': gate_size = 4 * hidden_size elif mode == 'GRU': gate_size = 3 * hidden_size elif mode == 'RNN_TANH': gate_size = hidden_size elif mode == 'RNN_RELU': gate_size = hidden_size else: raise ValueError("Unrecognized RNN mode: " + mode) self._all_weights = [] for layer in range(num_layers): for direction in range(num_directions): layer_input_size = input_size if layer == 0 else hidden_size * num_directions w_ih = Parameter(torch.Tensor(gate_size, layer_input_size)) w_hh = Parameter(torch.Tensor(gate_size, hidden_size)) b_ih = Parameter(torch.Tensor(gate_size)) b_hh = Parameter(torch.Tensor(gate_size)) layer_params = (w_ih, w_hh, b_ih, b_hh) suffix = '_reverse' if direction == 1 else '' param_names = ['weight_ih_l{}{}', 'weight_hh_l{}{}'] if bias: param_names += ['bias_ih_l{}{}', 'bias_hh_l{}{}'] param_names = [x.format(layer, suffix) for x in param_names] for name, param in zip(param_names, layer_params): setattr(self, name, param) self._all_weights.append(param_names) self.flatten_parameters() self.reset_parameters() def flatten_parameters(self): """Resets parameter data pointer so that they can use faster code paths. Right now, this works only if the module is on the GPU and cuDNN is enabled. Otherwise, it's a no-op. """ any_param = next(self.parameters()).data if not any_param.is_cuda or not torch.backends.cudnn.is_acceptable(any_param): return # If any parameters alias, we fall back to the slower, copying code path. This is # a sufficient check, because overlapping parameter buffers that don't completely # alias would break the assumptions of the uniqueness check in # Module.named_parameters(). all_weights = self._flat_weights unique_data_ptrs = set(p.data_ptr() for p in all_weights) if len(unique_data_ptrs) != len(all_weights): return with torch.cuda.device_of(any_param): import torch.backends.cudnn.rnn as rnn # NB: This is a temporary hack while we still don't have Tensor # bindings for ATen functions with torch.no_grad(): # NB: this is an INPLACE function on all_weights, that's why the # no_grad() is necessary. torch._cudnn_rnn_flatten_weight( all_weights, (4 if self.bias else 2), self.input_size, rnn.get_cudnn_mode(self.mode), self.hidden_size, self.num_layers, self.batch_first, bool(self.bidirectional)) def _apply(self, fn): ret = super(RNNBase, self)._apply(fn) self.flatten_parameters() return ret def reset_parameters(self): stdv = 1.0 / math.sqrt(self.hidden_size) for weight in self.parameters(): init.uniform_(weight, -stdv, stdv) def check_forward_args(self, input, hidden, batch_sizes): is_input_packed = batch_sizes is not None expected_input_dim = 2 if is_input_packed else 3 if input.dim() != expected_input_dim: raise RuntimeError( 'input must have {} dimensions, got {}'.format( expected_input_dim, input.dim())) if self.input_size != input.size(-1): raise RuntimeError( 'input.size(-1) must be equal to input_size. Expected {}, got {}'.format( self.input_size, input.size(-1))) if is_input_packed: mini_batch = int(batch_sizes[0]) else: mini_batch = input.size(0) if self.batch_first else input.size(1) num_directions = 2 if self.bidirectional else 1 expected_hidden_size = (self.num_layers * num_directions, mini_batch, self.hidden_size) def check_hidden_size(hx, expected_hidden_size, msg='Expected hidden size {}, got {}'): if tuple(hx.size()) != expected_hidden_size: raise RuntimeError(msg.format(expected_hidden_size, tuple(hx.size()))) if self.mode == 'LSTM': check_hidden_size(hidden[0], expected_hidden_size, 'Expected hidden[0] size {}, got {}') check_hidden_size(hidden[1], expected_hidden_size, 'Expected hidden[1] size {}, got {}') else: check_hidden_size(hidden, expected_hidden_size) def forward(self, input, hx=None): is_packed = isinstance(input, PackedSequence) if is_packed: input, batch_sizes = input max_batch_size = int(batch_sizes[0]) else: batch_sizes = None max_batch_size = input.size(0) if self.batch_first else input.size(1) if hx is None: num_directions = 2 if self.bidirectional else 1 hx = input.new_zeros(self.num_layers * num_directions, max_batch_size, self.hidden_size, requires_grad=False) if self.mode == 'LSTM': hx = (hx, hx) self.check_forward_args(input, hx, batch_sizes) _impl = _rnn_impls[self.mode] if batch_sizes is None: result = _impl(input, hx, self._flat_weights, self.bias, self.num_layers, self.dropout, self.training, self.bidirectional, self.batch_first) else: result = _impl(input, batch_sizes, hx, self._flat_weights, self.bias, self.num_layers, self.dropout, self.training, self.bidirectional) output = result[0] hidden = result[1:] if self.mode == 'LSTM' else result[1] if is_packed: output = PackedSequence(output, batch_sizes) return output, hidden def extra_repr(self): s = '{input_size}, {hidden_size}' if self.num_layers != 1: s += ', num_layers={num_layers}' if self.bias is not True: s += ', bias={bias}' if self.batch_first is not False: s += ', batch_first={batch_first}' if self.dropout != 0: s += ', dropout={dropout}' if self.bidirectional is not False: s += ', bidirectional={bidirectional}' return s.format(**self.__dict__) def __setstate__(self, d): super(RNNBase, self).__setstate__(d) if 'all_weights' in d: self._all_weights = d['all_weights'] if isinstance(self._all_weights[0][0], str): return num_layers = self.num_layers num_directions = 2 if self.bidirectional else 1 self._all_weights = [] for layer in range(num_layers): for direction in range(num_directions): suffix = '_reverse' if direction == 1 else '' weights = ['weight_ih_l{}{}', 'weight_hh_l{}{}', 'bias_ih_l{}{}', 'bias_hh_l{}{}'] weights = [x.format(layer, suffix) for x in weights] if self.bias: self._all_weights += [weights] else: self._all_weights += [weights[:2]] @property def _flat_weights(self): return [p for layerparams in self.all_weights for p in layerparams] @property def all_weights(self): return [[getattr(self, weight) for weight in weights] for weights in self._all_weights] class LSTM(RNNBase): def __init__(self, *args, **kwargs): super(LSTM, self).__init__('LSTM', *args, **kwargs)
C++
UTF-8
1,179
3.15625
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <math.h> #include <time.h> using namespace std; bool check_prime(int n){ for(int i=2;i<n;i++){ if(n%i==0){ return false; } } return true; } int find_prims(int* &prim,int a,int b){ int primes_num=0; for(int i=a;i<b;i++){ if(check_prime(i)){ primes_num++; prim =(int*)realloc(prim,primes_num*sizeof(int)); prim[primes_num-1]=i; } } return primes_num; } int main(){ srand (time(NULL)); int* prim=(int*)malloc(0*sizeof(int)); int p = prim[rand() % find_prims(prim,64,128)], q = prim[rand() % find_prims(prim,32,256)]; int n = p*q, fn = (p-1)*(q-1); long int e = prim[rand() % find_prims(prim,2,fn)],d=0; while(1){ if(e*d % fn ==1) break; d++; } cout<< "P: "<< p << endl << "Q: " << q << endl << "FN: "<< fn << endl << endl; cout<<"Public key is: (N = "<<n<< ", E = "<< e << " );" << endl; cout<<"Private key is: (N = "<<n<< ", D = "<< d << " );"<< endl; return 0; }
Java
UTF-8
6,554
1.875
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package org.w3c.wai.accessdb.rest.resources; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.JAXBException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.wai.accessdb.om.Technique; import org.w3c.wai.accessdb.services.DBInitService; import org.w3c.wai.accessdb.services.TechniquesService; import org.w3c.wai.accessdb.services.TestResultsService; import org.w3c.wai.accessdb.services.TestingSessionService; import org.w3c.wai.accessdb.services.TestsService; import org.w3c.wai.accessdb.sync.TechniquesSpecParser; import org.w3c.wai.accessdb.utils.ASBPersistenceException; import org.w3c.wai.accessdb.utils.AuthenticationException; /** * @author evangelos.vlachogiannis * @since 30.05.12 */ @Path("admin") public class AdminResource { final static Logger logger = LoggerFactory .getLogger(AdminResource.class); //TODO: remove on production @Path("initdb") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response initDB() throws ASBPersistenceException { logger.info("starting init."); DBInitService.INSTANCE.initAll(); return Response.ok().build(); } @Path("export/tests") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response exportAllTests() { try { logger.info("Start export"); TestsService.INSTANCE.exportAllTests(); logger.info("done"); return Response.ok().build(); } catch(Exception e){ logger.error(e.getLocalizedMessage()); return Response.noContent().entity(e).build(); } } @Path("export/testresults") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response exportAllTestResults() { try { logger.info("Start export"); TestResultsService.INSTANCE.exportAllTestResults(); logger.info("done"); return Response.ok().build(); } catch(Exception e){ logger.error(e.getLocalizedMessage()); return Response.noContent().entity(e).build(); } } @Path("import/tests") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response importAllTests(@QueryParam("path") String path) { try { logger.info("Start import"); TestsService.INSTANCE.importTests(path); logger.info("done"); return Response.ok().build(); } catch(Exception e){ logger.error(e.getLocalizedMessage()); return Response.noContent().entity(e).build(); } } @Path("import/testresults") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response importAllTestResults(@QueryParam("path") String path) { try { logger.info("Start import"); TestResultsService.INSTANCE.importAllTestResults(path); logger.info("done"); return Response.ok().build(); }catch(ASBPersistenceException e){ logger.error(e.getLocalizedMessage()); return Response.serverError().entity(e.getLocalizedMessage()).build(); } catch (JAXBException e) { logger.error(e.getLocalizedMessage()); return Response.serverError().entity(e.getLocalizedMessage()).build(); } } @Path("techniques/{sessionId}") @POST @Produces({ MediaType.APPLICATION_JSON }) public Response doTechniquesSpecSyncFromUrl(@PathParam("sessionId") String sessionId, String url) { try { if (!TestingSessionService.INSTANCE.isAuthenticatedAsAdmin(sessionId)) { logger.info("not appropriate permission for doTechniquesSpecSyncFromUrl"); return Response.status(Response.Status.UNAUTHORIZED).build(); } } catch (AuthenticationException e) { return Response.status(e.getErrorStatus()).build(); } url = url.trim().replace("\"", ""); logger.info("OK you have permission."); logger.info("techniques url: " + url); try{ List<Technique> l = TechniquesSpecParser.parse(url); return Response.ok(l).build(); } catch(Exception e){ logger.error(e.getLocalizedMessage()); return Response.serverError().entity(e.getLocalizedMessage()).build(); } } @Path("tests/deepdelete/{sessionId}/{nameid}") @DELETE @Produces({ MediaType.APPLICATION_JSON }) public Response deleteDeepTest(@PathParam("sessionId") String sessionId, @PathParam("nameid") String nameid){ try { if (!TestingSessionService.INSTANCE.isAuthenticatedAsAdmin(sessionId)) { logger.info("not appropriate permission for doTechniquesSpecSyncFromUrl"); return Response.status(Response.Status.UNAUTHORIZED).build(); } } catch (AuthenticationException e) { return Response.status(e.getErrorStatus()).build(); } try{ TestsService.INSTANCE.deleteDeepTestUnitById(nameid); } catch(Exception e) { logger.warn(e.getLocalizedMessage()); return Response.notModified().build(); } return Response.ok().build(); } /*@Path("tests/deepdeletelist/{sessionId}") @DELETE @Produces({ MediaType.APPLICATION_JSON }) public Response deleteDeepTests(@PathParam("sessionId") String sessionId, List<String> nameids){ if (!TestingSessionService.INSTANCE.isAuthenticatedAsAdmin(sessionId)) { logger.info("not appropriate permission for doTechniquesSpecSyncFromUrl"); return Response.status(Response.Status.UNAUTHORIZED).build(); } try{ for (String nameId : nameids) { TestsService.INSTANCE.deleteDeepTestUnitById(nameId); } } catch(Exception e) { logger.warn(e.getLocalizedMessage()); return Response.notModified().build(); } return Response.ok().build(); }*/ @Path("techniques/deepdelete/{sessionId}/{nameid}") @DELETE @Produces({ MediaType.APPLICATION_JSON }) public Response deleteDeepTechnique(@PathParam("sessionId") String sessionId, @PathParam("nameid") String nameid){ try { if (!TestingSessionService.INSTANCE.isAuthenticatedAsAdmin(sessionId)) { logger.info("not appropriate permission for doTechniquesSpecSyncFromUrl"); return Response.status(Response.Status.UNAUTHORIZED).build(); } } catch (AuthenticationException e) { return Response.status(e.getErrorStatus()).build(); } Technique t = null; try{ t = TechniquesService.INSTANCE.deleteTestsAndResultsByTechniqueNameId(nameid); } catch(Exception e) { logger.warn(e.getLocalizedMessage()); return Response.notModified().entity(t).build(); } return Response.ok(t).build(); } @Path("echo") @GET @Produces({ MediaType.APPLICATION_JSON }) public Response echo() { return Response.ok("echo!!").build(); } }
Java
UTF-8
2,127
2.390625
2
[]
no_license
package org.ymdroid.rnb.event; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.ymdroid.rnb.R; import java.util.ArrayList; /** * Created by yj on 16. 5. 22.. */ public class ListMypageAdapter extends BaseAdapter { private Context mContext = null; public ArrayList<ListData2> mListData = new ArrayList<ListData2>(); public ListMypageAdapter(Context mContext) { super(); this.mContext = mContext; } @Override public int getCount() { return mListData.size(); } @Override public Object getItem(int position) { return mListData.get(position); } @Override public long getItemId(int position) { return position; } public void addItem(String mTitle, String mDate){ ListData2 addInfo = null; addInfo = new ListData2(); addInfo.mTitle = mTitle; addInfo.mDate = mDate; mListData.add(addInfo); } public void remove(int position){ mListData.remove(position); dataChange(); } public void dataChange(){ this.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder2 holder; if (convertView == null) { holder = new ViewHolder2(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.listview_userinfo, null); holder.mText = (TextView) convertView.findViewById(R.id.mText_userinfo); holder.mDate = (TextView) convertView.findViewById(R.id.mDate_userinfo); convertView.setTag(holder); }else{ holder = (ViewHolder2) convertView.getTag(); } ListData2 mData = mListData.get(position); holder.mText.setText(mData.mTitle); holder.mDate.setText(mData.mDate); return convertView; } }
Markdown
UTF-8
5,884
2.734375
3
[ "Apache-2.0" ]
permissive
[AmniXtension](../../index.md) / [com.amnix.xtension.extensions](../index.md) / [kotlin.String](./index.md) ### Extensions for kotlin.String | Name | Summary | |---|---| | [append](append.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.append(other: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Append String to Current | | [deCodeToBinary](de-code-to-binary.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.deCodeToBinary(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Decode the String from binary | | [decodeToBase64](decode-to-base64.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.decodeToBase64(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Decode to Base64 | | [decodeToUrl](decode-to-url.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.decodeToUrl(charSet: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)` = "UTF-8"): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Decode String to URL | | [decryptAES](decrypt-a-e-s.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.decryptAES(key: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Decrypt String to AES with the specific Key | | [encodeToBase64](encode-to-base64.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.encodeToBase64(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Encode To Base64 | | [encodeToBinary](encode-to-binary.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.encodeToBinary(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>encode The String to Binary | | [encodeToUrl](encode-to-url.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.encodeToUrl(charSet: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)` = "UTF-8"): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Encode String to URL | | [encryptAES](encrypt-a-e-s.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.encryptAES(key: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Encrypt String to AES with the specific Key | | [isEmail](is-email.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.isEmail(): `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)<br>True if Email | | [isNumeric](is-numeric.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.isNumeric(): `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)<br>True if Numeric | | [isPhone](is-phone.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.isPhone(): `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)<br>True if String is a Phone Number | | [md5](md5.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.md5(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>returns the md5 of the String | | [saveToFile](save-to-file.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.saveToFile(file: `[`File`](http://docs.oracle.com/javase/6/docs/api/java/io/File.html)`): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)<br>Save String to a Given File | | [sha1](sha1.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.sha1(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>return SHA1 of the String | | [splitSubStrings](split-sub-strings.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.splitSubStrings(maxLength: `[`Int`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)`): `[`Array`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)`<`[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`>`<br>Split String into Multiple SubStrings Based on the Value of [maxLength](split-sub-strings.md#com.amnix.xtension.extensions$splitSubStrings(kotlin.String, kotlin.Int)/maxLength) | | [toCamelCase](to-camel-case.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.toCamelCase(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Converts the String to Camel Case | | [toFile](to-file.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.toFile(): `[`File`](http://docs.oracle.com/javase/6/docs/api/java/io/File.html)<br>Returns a new File Object with the Current String as Its path | | [toTitleCase](to-title-case.md) | `fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.toTitleCase(): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)<br>Converts the String to Title Case |
Markdown
UTF-8
11,137
3.203125
3
[]
no_license
--- title: Python 虚拟环境全知道 date: 2018-01-09 tags: ["python", "pyenv", "virtualenv", "docker"] keywords: ["python", "pyenv", "virtualenv", "docker", "虚拟"] slug: python-virtualenv-all-know gitcomment: true bigimg: [{src: "/img/posts/photo-1500644970114-4ff3c3dfb61f.jpeg", desc: "Reach for the End."}] category: "python" --- 对于每个`python`项目依赖的库版本都有可能不一样,如果将依赖包都安装到公共环境的话显然是没法进行区分的,甚至是不同的项目使用的`python`版本都不尽相同,有的用`python2.7`,有的用`python3.6`,所以对于`python`项目的环境进行隔离管理就成为一个必然的需求了。 <!--more--> ## 需求 * 不同项目间能区分依赖包版本 * 不同项目间能区分`python`版本 * 方便自由切换 ## 解决方案 * 解决依赖包问题:`virtualenv` * 解决`python`版本问题:`pyenv` * 终极(也许吧)解决方案:`docker` ### virtualenv 运行`pip install virtualenv`即可安装`virtualenv`,当然了还可以用`easy_install`安装,即使是没有安装任何`Python`包管理器(比如**pip**),也可以直接获取[virtualenv.py](https://raw.github.com/pypa/virtualenv/master/virtualenv.py)并运行`python virtualenv.py`,效果也是一样的,当然我还是强烈推荐你安装包管理工具:`pip`,他一定能为你带来很多便利的(新版本的`virtualenv`也包含了`pip`管理工具)。 ```shell $ pip install virtualenv Collecting virtualenv Using cached virtualenv-15.1.0-py2.py3-none-any.whl Installing collected packages: virtualenv Successfully installed virtualenv-15.1.0 ``` 安装完成后,就可以直接创建一个虚拟环境了(**virtualenv 环境名称**): ```shell $ virtualenv env4test ``` 创建完成后,用下面的命令即可激活当前虚拟环境: ```shell $ source env4test/bin/activate (env4test)$ ``` 现在就可以随意的安装你的依赖包了,现在安装的包只会对当前环境`env4test`有效,比如安装`django2.0`: ```shell (env4test)$ pip install django ``` 要退出当前虚拟环境也是非常简单的,如下: ```shell $ deactivate ``` 现在我们用`pip list`命令可以发现已经没有`django`的身影了。 `virtualenv`还有很多高级的用法,可以[前往该文档查看](https://virtualenv-chinese-docs.readthedocs.io/en/latest/)。 ### virtualenvwrapper `virtualenvwrapper`是`virtualenv`的一个扩展包,可以让你更加方便的使用`virtualenv`,优点: * 将所有虚拟环境整合在一个目录下 * 管理(新增,删除,复制)虚拟环境 * 方便切换虚拟环境 安装也很方便,用包管理工具即可: ```shell $ pip install virtualenvwrapper ``` 安装完成以后还需要小小的配置一下才可以使用,首先我们找到`virtualenvwrapper.sh`的文章,通常会是:`/usr/local/bin/virtualenvwrapper.sh`: ```shell $ sudo find / -name virtualenvwrapper.sh Password: /usr/local/bin/virtualenvwrapper.sh ``` 然后我们可以在`.zshrc`(取决于你用的终端,我用的`zsh`)添加一行命令: ```txt source /usr/local/bin/virtualenvwrapper.sh ``` 然后让我们的配置生效: ```shell $ source ~/.zshrc ``` 现在我们就可以使用`virtualenvwrapper`的基本命令了: * 创建基本环境:**mkvirtualenv** [环境名] * 删除环境:**rmvirtualenv** [环境名] * 激活环境:**workon** [环境名] * 退出环境:**deactivate** * 列出所有环境:**workon**或者**lsvirtualenv -b** 参考文档:[https://virtualenvwrapper.readthedocs.io/en/latest/](https://virtualenvwrapper.readthedocs.io/en/latest/) ### pyenv `pyenv`是`Python`版本管理工具,可以改变全局的`Python`版本,安装多个版本的`Pytho`,设置目录级别的`Python`版本,还能创建和管理虚拟环境。所有的设置都是用户级别的操作,不需要`sudo`命令。 `pyenv`通过系统修改环境变量来实现`Python`不同版本的切换。而`virtualenv` 通过将`Python`包安装到一个目录来作为`Python` 包虚拟环境,通过切换目录来实现不同包环境间的切换。 如果你使用的`MAC`系统,推荐使用`homebrew`来安装: ```shell $ brew update $ brew install pyenv ``` 如果你使用的是其他系统,也不担心,`pyenv`官方提供了一键安装的方式: ```shell $ curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash ``` 安装完成以后,可以添加几条命令到`.zshrc`(同样的也可能是.bashrc,根据自己使用的终端进行配置)中开启自动补全功能: ```txt export PATH=$HOME/.pyenv/bin:$PATH eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" ``` 然后同样激活上面的配置: ```shell $ source ~/.zshrc ``` 现在我们就可以使用`pyenv`了: * 查看本机安装`Python`版本: ```shell $ pyenv versions ∗ system (set by /Users/ych/.pyenv/version) 3.6.4 3.6.4/envs/ops3.6.4 3.6.4/envs/talk3.6.4 ops3.6.4 talk3.6.4 ``` 星号表示当前正在使用的`Python`版本。 * 查看所有可安装的`Python`版本: ```shell $ pyenv install -l ``` * 安装与卸载: ```shell $ pyenv install 2.7.3 # 安装python $ pyenv uninstall 2.7.3 # 卸载python ``` * 版本切换: ```shell $ pyenv global 2.7.3 $ pyenv local 2.7.3 ``` `global`用于设置全局的`Python`版本,通过将版本号写入`~/.pyenv/version`文件的方式。`local`用于设置本地版本,通过将版本号写入当前目录下的`.python-version`文件的方式。通过这种方式设置的`Python`版本优先级比`global`高。 * `python`优先级:`shell > local > global` `pyenv`会从当前目录开始向上逐级查找`.python-version`文件,直到根目录为止。若找不到,就用`global`版本。 ```shell $ pyenv shell 2.7.3 # 设置面向 shell 的 Python 版本,通过设置当前 shell 的 PYENV_VERSION 环境变量的方式。这个版本的优先级比 local 和 global 都要高。 $ pyenv shell --unset # –unset 参数用于取消当前 shell 设定的版本。 ``` ### pyenv-virtualenv 自动安装`pyenv`后,它会自动安装部分插件,通过`pyenv-virtualenv`插件可以很好的和`virtualenv`进行结合: ```shell $ ls -la ~/.pyenv/plugins total 8 drwxr-xr-x 9 ych staff 288 12 26 16:27 . drwxr-xr-x 23 ych staff 736 12 26 17:44 .. -rw-r--r-- 1 ych staff 52 12 26 16:26 .gitignore drwxr-xr-x 11 ych staff 352 12 26 16:27 pyenv-doctor drwxr-xr-x 12 ych staff 384 12 26 16:27 pyenv-installer drwxr-xr-x 7 ych staff 224 12 26 16:27 pyenv-update drwxr-xr-x 13 ych staff 416 12 26 16:27 pyenv-virtualenv drwxr-xr-x 8 ych staff 256 12 26 16:27 pyenv-which-ext drwxr-xr-x 8 ych staff 256 12 26 16:26 python-build ``` 基本使用命令: * 列出当前虚拟环境:`pyenv virtualenvs` * 激活虚拟环境:`pyenv activate 环境名称` * 退出虚拟环境:`pyenv deactivate` * 删除虚拟环境:`pyenv uninstall 环境名称`或者`rm -rf ~/.pyenv/versions/环境名称` * 创建虚拟环境:`pyenv virtualenv 3.6.4 env3.6.4` > 若不指定python 版本,会默认使用当前环境python 版本。如果指定Python 版本,则一定要是已经安装过的版本,否则会出错。环境的真实目录位于`~/.pyenv/versions`下。 总结:利用`pyenv`和`pyenv-virtualenv`插件就能够简单方便的将`python`版本和依赖包进行环境隔离了,在实际开发过程中比较推荐这种方式。 参考文档:[https://github.com/pyenv/pyenv](https://github.com/pyenv/pyenv)。 ### Docker 有没有一种方式能够不按照这些工具来进行环境隔离的呢?当然有,那就是大名鼎鼎的`Docker`。如果你的服务都是容器化的话,应该对`Docker`不陌生,将当前项目跑在一个隔离的容器中,对系统中的其他服务或者项目是没有任何影响的,不用担心会污染环境,唯一不友好的地方是项目中的代码改变后需要重新构建镜像。 比如现在有一个`django`的项目,项目结构如下: ```shell $ testpyenv tree . ├── manage.py └── testpyenv ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ``` 在项目根目录下面新建文件`requirements.txt`: ```txt Django==2.0 ``` 然后我们在根目录下面创建一个`Dockerfile`文件: ```dockerfile FROM python:3.6.4 # 设置工作目录 RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # 添加依赖(利用Docker 的缓存) ADD ./requirements.txt /usr/src/app/requirements.txt # 安装依赖 RUN pip install -r requirements.txt # 添加应用 ADD . /usr/src/app # 运行服务 CMD python manage.py runserver 0.0.0.0:8000 ``` 因为`django2.0`只支持`python3`以上了,所以我们这里基础镜像使用`python:3.6.4`,然后是添加应用代码,安装依赖,运行服务等。然后我们构建一个镜像: ```shell $ docker build -t cnych/testpyenv:v0.1.1 . ``` 构建完成以后,在我们项目根目录中新建一个`start.sh`的脚本来启动容器: ```txt docker run -d -p 8000:8000 --name testpyenv cnych/testpyenv:v0.1.1 ``` 将本地的`8000`端口和容器的`8000`进行映射,执行我们的启动脚本: ```shell $ source start.sh ``` 启动完成后,我们就可以在本地通过`http://127.0.0.1:8000`进行访问了。 ![django-index](/img/posts/django2-index.jpg) 但是如果只这样配置的话,的确能够解决我们的环境隔离问题,但是现在有一个最大的一个问题是,每次代码更改过后都需要重新构建镜像才能生效,这对于开发阶段是非常不友好的,有什么解决方案呢?你是否还记得当你更改了代码后`django`项目会自动加载的,要是每次更改了项目代码后,容器中的代码也变化的话那岂不是容器中的服务也自动加载了?是不是? 幸好`Docker`为我们提供了`volume`挂载的概念,我们只需要将我们的代码挂载到容器中的工作目录就行了,现在来更改`start.sh`脚本: ```txt work_path=$(pwd) docker run -d -p 8000:8000 --name testpyenv -v ${work_path}:/usr/src/app cnych/testpyenv:v0.1.1 ``` 然后激活启动脚本,随意更改一次代码,看看是否能够及时生效,怎样查看呢?查看日志就行了: ```shell $ docker logs -f testpyenv ``` 最后,如果是生产环境记得把代码挂载给去掉,因为线上不需要这样做,只需要构建一次就行。 ## 参考资料: * [https://virtualenv-chinese-docs.readthedocs.io/en/latest/](https://virtualenv-chinese-docs.readthedocs.io/en/latest/) * [https://virtualenvwrapper.readthedocs.io/en/latest/](https://virtualenvwrapper.readthedocs.io/en/latest/) * [https://github.com/pyenv/pyenv](https://github.com/pyenv/pyenv) * [TDD开发容器化的Python微服务应用(一)](/post/tdd-develop-python-microservice-app) 扫描下面的二维码(或微信搜索`iEverything`)添加我微信好友(注明`python`),然后可以加入到我们的`python`讨论群里面共同学习 ![qrcode](/img/posts/wexin-qrcode.jpeg)
Java
UTF-8
2,480
2.015625
2
[ "Apache-2.0" ]
permissive
/* * 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 com.facebook.presto.plugin.blackhole; import com.facebook.presto.common.Page; import com.facebook.presto.spi.ConnectorPageSink; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import io.airlift.slice.Slice; import io.airlift.units.Duration; import java.util.Collection; import java.util.concurrent.CompletableFuture; import static com.facebook.airlift.concurrent.MoreFutures.toCompletableFuture; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; class BlackHolePageSink implements ConnectorPageSink { private static final CompletableFuture<Collection<Slice>> NON_BLOCKED = CompletableFuture.completedFuture(ImmutableList.of()); private final ListeningScheduledExecutorService executorService; private final long pageProcessingDelayMillis; private CompletableFuture<Collection<Slice>> appendFuture = NON_BLOCKED; public BlackHolePageSink(ListeningScheduledExecutorService executorService, Duration pageProcessingDelay) { this.executorService = requireNonNull(executorService, "executorService is null"); this.pageProcessingDelayMillis = requireNonNull(pageProcessingDelay, "pageProcessingDelay is null").toMillis(); } @Override public CompletableFuture<?> appendPage(Page page) { appendFuture = scheduleAppend(); return appendFuture; } private CompletableFuture<Collection<Slice>> scheduleAppend() { if (pageProcessingDelayMillis > 0) { return toCompletableFuture(executorService.schedule(() -> ImmutableList.of(), pageProcessingDelayMillis, MILLISECONDS)); } return NON_BLOCKED; } @Override public CompletableFuture<Collection<Slice>> finish() { return appendFuture; } @Override public void abort() {} }