language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
17,369
2.734375
3
[]
no_license
# FTP Server was implmented by Kavilan Nair (1076342) import socket import threading import os import random import platform # FTP server class that inherits from the threading module class FTPServer (threading.Thread): def __init__(self, connection_socket, address_ip): threading.Thread.__init__(self) # initialise member variables to be used later in the codde self.command_connection = connection_socket self.data_connection = None self.address_ip = address_ip self.data_connection = None self.type = None self.isConnectionTerminated = False self.isActiveMode = None self.cwd = os.getcwd() self.user = ' ' def run(self): print("Connection from: ", str(self.address_ip)) self.command_connection.send('220 Welcome to the FTP server\r\n'.encode()) # infinite for loop to continuously preceive commands from client while True: # commands available that have been implemented and can be used by a client commands_available = ['USER', 'PASS', 'PASV', 'LIST', 'PWD', 'CWD', 'TYPE', 'SYST', 'RETR', 'STOR', 'NOOP', 'QUIT', 'PORT', 'DELE', 'MKD', 'RMD', 'CDUP'] if self.isConnectionTerminated: break # formatting of client commands to split into command and argument client_message = self.command_connection.recv(1024).decode() print("From connected client " + self.user + ": " + client_message) command = client_message[:4].strip() argument = client_message[4:].strip() if command in commands_available: # call function based off string supplied through client command ftp_command = getattr(self, command) if argument == '': ftp_command() else: ftp_command(argument) elif command not in commands_available: self.command_connection.send("502 Command not implemented \r\n".encode()) # Function to handle USER command def USER(self, argument): if argument == "group18" or argument == "group19": self.user = argument reply = "331 Please Specify Password\r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: reply = "530 Login incorrect\r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) self.command_connection.close() # Function to handle password associated with username def PASS(self, argument): if (self.user == "group18" and argument == "dan") or (self.user == "group19" and argument == "mat"): reply = "230 Login successful\r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: reply = "530 Login incorrect\r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) self.command_connection.close() # Function to handle passive connection from client def PASV(self): self.isActiveMode = False # Randomly generate port numbers for client to connect to port_number1 = random.randint(47, 234) port_number2 = random.randint(0, 255) server_address = socket.gethostbyname(socket.gethostname()) # string manipulation to format in appropriate server_address = server_address.split(".") server_address = ','.join(server_address) server_address = "(" + server_address + "," + str(port_number1) + "," + str(port_number2) + ")" data_port = (port_number1 * 256) + port_number2 host = socket.gethostbyname(socket.gethostname()) try: # Attempt to establish data connection self.data_connection = self.data_establish(host, data_port) reply = "227 Entering passive mode" + str(server_address) + '\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) except socket.error: reply = "425 Cannot open Data connection \r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to handle active connection to client def PORT(self, argument): self.isActiveMode = True # string handling argument = argument.split(',') data_host = '.'.join(argument[0:4]) port_number = argument[-2:] data_port = (int(port_number[0]) * 256) + int(port_number[1]) data_port = int(data_port) self.data_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Attempt to establish data connection self.data_connection.connect((data_host, data_port)) reply = "225 Entering Active mode \r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) except socket.error: reply = "425 Cannot open Data connection \r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to handle directory listing def LIST(self): reply = "150 File status okay; about to open data connection.\r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) if not self.isActiveMode: data_sock, data_address = self.data_connection.accept() directory_list = os.listdir(self.cwd) for item in directory_list: # Uncomment to see what list contents are being sent # print('sending: ' + str(item)) if not self.isActiveMode: data_sock.sendall((str(item) + '\r\n').encode()) else: self.data_connection.sendall((str(item) + '\r\n').encode()) reply = '226 Closing data connection. Requested transfer action successful\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) if not self.isActiveMode: data_sock.close() self.data_connection.close() # Function to obtain current working directory def PWD(self): reply = '257' + ' "' + self.cwd + '" ' + 'is the working directory\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to obtain change working directory def CWD(self, argument): path = argument self.cwd = self.cwd + '/' + str(path) if os.path.exists(self.cwd): reply = '250 Requested file action okay, completed.\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: reply = '550 Requested action not taken. File/Directory unavailable\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to choose ASCII or Binary mode def TYPE(self, argument): if argument == 'A': reply = '200 ASCII mode enabled\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) self.type = 'A' elif argument == 'I': reply = '200 binary mode enabled\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) self.type = 'I' else: reply = '501 Syntax error in parameters or arguments\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to obtain the operating system def SYST(self): reply = "215 " + platform.system() + "\r\n" print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to download file from server def RETR(self, argument): reply = '150 File status okay; about to open data connection.\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) if not self.isActiveMode: data_sock, data_address = self.data_connection.accept() filename = self.cwd + '/' + argument if self.type == 'A': file = open(filename, 'r') reading = file.read(8192) while reading: print('reading file') if not self.isActiveMode: data_sock.send((reading + '\r\n').encode()) else: self.data_connection.send((reading + '\r\n').encode()) reading = file.read(8192) file.close() if not self.isActiveMode: data_sock.close() self.data_connection.close() reply = '226 Closing data connection. Requested transfer action successful \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) elif self.type == 'I': file = open(filename, 'rb') reading = file.read(8192) while reading: print('reading file') if not self.isActiveMode: data_sock.send(reading) else: self.data_connection.send(reading) reading = file.read(8192) file.close() if not self.isActiveMode: data_sock.close() self.data_connection.close() reply = '226 Closing data connection. Requested transfer action successful \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # should I close the data_connection # Function to upload file to server def STOR(self, argument): reply = '150 File status okay; about to open data connection.\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) if not self.isActiveMode: data_sock, data_address = self.data_connection.accept() filename = self.cwd + '/' + argument if self.type == 'A': file = open(filename, 'w') if not self.isActiveMode: file_data = data_sock.recv(8192).decode() else: file_data = self.data_connection.recv(8192).decode() while file_data: print('writing file') file.write(file_data) if not self.isActiveMode: file_data = data_sock.recv(8192).decode() else: file_data = self.data_connection.recv(8192).decode() file.close() if not self.isActiveMode: data_sock.close() self.data_connection.close() reply = '226 Closing data connection. Requested transfer action successful \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) elif self.type == 'I': file = open(filename, 'wb') if not self.isActiveMode: file_data = data_sock.recv(8192) else: file_data = self.data_connection.recv(8192) while file_data: print('writing file') file.write(file_data) if not self.isActiveMode: file_data = data_sock.recv(8192) else: file_data = self.data_connection.recv(8192) file.close() if not self.isActiveMode: data_sock.close() self.data_connection.close() reply = '226 Closing data connection. Requested transfer action successful \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) file.close() # Function to check if connection is still active def NOOP(self): reply = '200 NOOP OK \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to delete specific file def DELE(self, argument): file_name = argument file_path = self.cwd + '/' + str(file_name) if os.path.exists(file_path): os.remove(file_path) reply = '250 Requested file action okay, completed.\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: reply = '550 Could not execute delete, file not found\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to obtain create a directory def MKD(self, argument): directory_name = argument directory_path = self.cwd + '/' + str(directory_name) if os.path.exists(directory_path): reply = '550 Requested action not taken. File/Directory unavailable\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: os.makedirs(directory_path) reply = '257 Folder has been successfully created\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to delete specified working directory def RMD(self, argument): directory_name = argument directory_path = self.cwd + '/' + str(directory_name) if os.path.exists(directory_name): os.rmdir(directory_path) reply = '250 Requested file action okay, completed. \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: reply = '550 Requested action not taken. File/Directory unavailable\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to change to parent directory def CDUP(self): print('Here') print(self.cwd) parent_directory = self.cwd.split('/') parent_directory = parent_directory[:-1] parent_directory = '/'.join(parent_directory) print(parent_directory) if os.path.exists(parent_directory): self.cwd = parent_directory reply = '200 Changed directory successfully \r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) else: reply = '550 Requested action not taken. File/Directory unavailable\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) # Function to end FTP session def QUIT(self): reply = '221 Goodbye\r\n' print('Response sent to connected client ' + self.user + ': ' + reply) self.command_connection.send(reply.encode()) self.command_connection.close() self.isConnectionTerminated = True # establish data connection in passive mode def data_establish(self, host, port): data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) data_socket.bind((host, port)) data_socket.listen(5) return data_socket def main(): # Local Machine IP and port host = socket.gethostbyname(socket.gethostname()) port = 6000 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host, port)) print('FTP Server initialized at ' + host) print("Awaiting a connection from a client") # infinite loop to accept multiple client conenction and run them in separate threads while True: server_socket.listen(1) connection_socket, address_ip = server_socket.accept() thread = FTPServer(connection_socket, address_ip) thread.start() if __name__ == '__main__': main()
PHP
UTF-8
782
2.859375
3
[]
no_license
<?php function secondvalidate($email) { $domains = array('yahoo.com', 'gmail.com', 'usc.edu', 'hotmail.com', 'aol.com'); $num = 0; foreach ($domains as $domain) { if (strpos($email, $domain)) { echo "<p>Thank you for your submission.</p>"; break; } else { $num++; if ($num == 5) { echo "<p>Please <a href='form.php'>go back</a> and try again using a valid email provider.</p>"; } } } } function validate($email) { if(strpos($email,"@")) { secondvalidate($email); } else { echo "Please enter a valid email address."; } } if (strlen($message) > 0 && strlen($email) > 0 && strlen($name) > 0) { validate($email); } else { echo "<p>Please <a href='form.php'>go back</a> and fill out all the fields.</p>"; } ?>
Java
UTF-8
303
2.859375
3
[]
no_license
public abstract class AnagramFinder { public abstract String[] search(String word); public void createDictionary(String[] words) { for(String s : words){ if(s!=null){ add(s); } } } protected String getBaseFormOf(String word){ return ""; } public abstract void add(String w); }
Java
UTF-8
197
1.96875
2
[ "Unlicense" ]
permissive
package Domain.Users; public class RefereeStub extends Referee{ public RefereeStub(SystemUser systemUser, RefereeQualification training) { super(systemUser, training, true); } }
C
UTF-8
194
2.921875
3
[]
no_license
#include "holberton.h" char *_memcpy(char *dest, char *src, unsigned int n) { unsigned int i; char *d = dest; char *s = src; for (i = 0; i < n; i++) { *d++ = *s++; } return (dest); }
Java
UTF-8
5,781
2.015625
2
[]
no_license
/*********************************************************************************************************************** * * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.sopremo.serialization; import it.unimi.dsi.fastutil.ints.IntSet; import eu.stratosphere.pact.common.type.PactRecord; import eu.stratosphere.pact.common.type.Value; import eu.stratosphere.sopremo.ISerializableSopremoType; import eu.stratosphere.sopremo.expressions.EvaluationExpression; import eu.stratosphere.sopremo.type.IJsonNode; /** * The schema-interface can be implemented to provide the functionality to convert between {@link PactRecord}s and * {@link IJsonNode}s. * * @author Arvid Heise */ public interface Schema extends ISerializableSopremoType { // public static Schema Default = new Default(); /** * Returns the indices of all values that are especially separated to be used as keys.<br> * The index of the payload should not be returned. * * @return the indices */ public IntSet getKeyIndices(); /** * Specifies the expected classes of the fields of the {@link PactRecord}. * * @return the classes of the {@link PactRecord} */ public Class<? extends Value>[] getPactSchema(); /** * Determines the index of the given expression within this schema. * * @param expression * the expressionthat should be used * @return the index */ public IntSet indicesOf(EvaluationExpression expression); // public static class Default implements Schema { // /** // * // */ // private static final long serialVersionUID = 4142913511513235355L; // // private static final Class<? extends Value>[] PactSchema = SchemaUtils.combineSchema(JsonNodeWrapper.class); // // /* // * (non-Javadoc) // * @see eu.stratosphere.sopremo.type.Schema#getPactSchema() // */ // @Override // public Class<? extends Value>[] getPactSchema() { // return PactSchema; // } // // /* // * (non-Javadoc) // * @see eu.stratosphere.sopremo.type.Schema#jsonToRecord(eu.stratosphere.sopremo.type.IJsonNode, // * eu.stratosphere.pact.common.type.PactRecord) // */ // @Override // public PactRecord jsonToRecord(final IJsonNode value, PactRecord target) { // if (target == null) // target = new PactRecord(new JsonNodeWrapper()); // else if (target.getNumFields() < 1) { // target.setField(0, new JsonNodeWrapper()); // } // target.getField(0, JsonNodeWrapper.class).setValue(value); // // if (value instanceof IArrayNode) { // // target.getField(0, JsonNodeWrapper.class).setValue(((IArrayNode) value).get(0)); // // target.getField(1, JsonNodeWrapper.class).setValue(((IArrayNode) value).get(1)); // // } else { // // target.getField(0, JsonNodeWrapper.class).setValue(NullNode.getInstance()); // // target.getField(1, JsonNodeWrapper.class).setValue(value); // // } // return target; // } // // /* (non-Javadoc) // * @see // eu.stratosphere.sopremo.serialization.Schema#indicesOf(eu.stratosphere.sopremo.expressions.EvaluationExpression) // */ // @Override // public int[] indicesOf(EvaluationExpression expression) { // if (expression == EvaluationExpression.KEY) // return new int[] { 0 }; // return new int[] { 1 }; // } // // /* // * (non-Javadoc) // * @see eu.stratosphere.sopremo.type.Schema#recordToJson(eu.stratosphere.pact.common.type.PactRecord, // * eu.stratosphere.sopremo.type.IJsonNode) // */ // @Override // public IJsonNode recordToJson(final PactRecord record, final IJsonNode target) { // return record.getField(0, JsonNodeWrapper.class).getValue(); // // final JsonNodeWrapper key = record.getField(0, JsonNodeWrapper.class); // // final JsonNodeWrapper value = record.getField(1, JsonNodeWrapper.class); // // return JsonUtil.asArray(key.getValue(), value.getValue()); // // IJsonNode.Type type = IJsonNode.Type.values()[record.getField(0, JsonNodeWrapper.class).getValue()]; // // if (target == null || target.getType() != type) // // target = InstantiationUtil.instantiate(type.getClazz(), IJsonNode.class); // // record.getFieldInto(1, target); // // return target; // } // } /** * Converts the given {@link IJsonNode} to a {@link PactRecord}. If possible the given target-record will be reused. * * @param value * the {@link IJsonNode}, which shall be transformed into a {@link PactRecord} using this Schema * @param target * the target {@link PactRecord} or <code>null</code>, when it shall be created * @param context * TODO * @return the converted {@link IJsonNode} */ public PactRecord jsonToRecord(IJsonNode value, PactRecord target); /** * Converts the given {@link PactRecord} to an appropriate {@link IJsonNode}. If possible the given target-node will * be reused. * * @param record * which shall be transformed to a matching {@link IJsonNode} using this Schema * @param target * in which the record shall be transformed into or <code>null</code>, when target shall be created * @return transfomed Record */ public IJsonNode recordToJson(PactRecord record, IJsonNode target); }
Java
UTF-8
4,442
2.4375
2
[]
no_license
package com.gcit.lms.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; import com.gcit.lms.entity.BookCopies; import com.gcit.lms.entity.LibraryBranch; @SuppressWarnings({ "rawtypes" }) public class BookCopiesDAO extends BaseDAO implements ResultSetExtractor<List<BookCopies>>{ public void saveBookCopies(BookCopies bookcopies) throws SQLException { template.update("INSERT INTO tbl_book_copies (bookId,branchId,noOfCopies) VALUES (?,?,?)", new Object[] { bookcopies.getBookId(),bookcopies.getBranchId(),bookcopies.getCopies() }); } // public void saveBookBookCopies(BookCopies bookcopies) throws SQLException { // for(Book b: bookcopies.getBooks()){ // save("INSERT INTO tbl_book VALUES (?, ?,?)", new Object[] { b.getBookId(), b.getTitle(),bookcopies.getPublisherId()}); // } // } public Integer saveBookCopiesWithID(BookCopies bookcopies) throws SQLException { KeyHolder holder = new GeneratedKeyHolder(); final String sql = "INSERT INTO tbl_book_copies (bookId,branchId,noOfCopies) VALUES (?,?,?)"; template.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS); ps.setInt(1, bookcopies.getBookId()); ps.setInt(2, bookcopies.getBranchId()); ps.setInt(3, bookcopies.getCopies()); return ps; } }, holder); return holder.getKey().intValue(); } public void updateBookCopies(BookCopies bookcopies) throws SQLException { template.update("UPDATE tbl_book_copies SET noOfCopies = ? WHERE bookId = ? AND branchId = ?", new Object[] { bookcopies.getCopies(),bookcopies.getBookId(),bookcopies.getBranchId() }); } public void deleteBookCopies(BookCopies bookcopies) throws SQLException { template.update("DELETE FROM tbl_book_copies WHERE bookId = ? AND branchId = ?", new Object[] { bookcopies.getBookId(),bookcopies.getBranchId() }); } public List<BookCopies> readBookCopies(BookCopies bookcopies) throws SQLException { if(bookcopies.getBookId() !=0 && bookcopies.getBranchId()!=0 ){ return template.query("SELECT * FROM tbl_book_copies WHERE bookId = ? AND branchId = ?", new Object[]{bookcopies.getBookId(),bookcopies.getBranchId()},this); } else if(bookcopies.getBookId()!=0 && bookcopies.getBranchId() ==0) { return template.query("SELECT * FROM tbl_book_copies WHERE bookId = ? ", new Object[]{bookcopies.getBookId()},this); } else if(bookcopies.getBookId() ==0 && bookcopies.getBranchId() !=0) { return template.query("SELECT * FROM tbl_book_copies WHERE branchId = ? ", new Object[]{bookcopies.getBranchId()},this); } else { return template.query("SELECT * FROM tbl_book_copies",this); } } public List<BookCopies> readBookCopiesbyCond(BookCopies bookcopies) throws SQLException { return template.query("SELECT * FROM tbl_book_copies WHERE branchId = ? AND noOfCopies > 0 ", new Object[]{bookcopies.getBranchId()},this); } public List<BookCopies> readAllBookCopiesByBranch(LibraryBranch lib) throws SQLException { return template.query("SELECT * FROM tbl_book_copies where branchId IN (select branchId from library.tbl_book_copies where branchId = ?)", new Object[]{lib.getBranchId()}, this); } public BookCopies readBookCopiesByPK(Integer bookId, Integer branchId) throws SQLException { List<BookCopies> bookCopies = template.query("SELECT * FROM tbl_book_copies WHERE bookId = ? AND branchId = ?", new Object[]{bookId,branchId},this); if(bookCopies!=null){ return bookCopies.get(0); } return null; } @Override public List<BookCopies> extractData(ResultSet rs) throws SQLException { List<BookCopies> bookcopiess = new ArrayList<>(); while(rs.next()){ BookCopies a = new BookCopies(); a.setBookId(rs.getInt("bookId")); a.setBranchId(rs.getInt("branchId")); a.setCopies(rs.getInt("noOfCopies")); bookcopiess.add(a); } return bookcopiess; } }
JavaScript
UTF-8
755
2.59375
3
[]
no_license
import axios from 'axios'; const baseURL = 'https://rich-kid.herokuapp.com/'; const axiosInstance = axios.create({ baseURL, timeout: 30000, headers: {'Content-Type': 'application/json'}, }); class HttpLayer { static Axios = axiosInstance; constructor() {} #prepareUrl = (url) => { return url.includes('http') ? url : `${baseURL}${url}`; }; get(url, params) { const uri = this.#prepareUrl(url); return axiosInstance.get(uri, params); } post(url, params) { const uri = this.#prepareUrl(url); return axiosInstance.post(uri, params); } put(url, params) { console.log('put params: ', params); } delete(url, params) { console.log('delete params: ', params); } } export default new HttpLayer();
Python
UTF-8
963
3.140625
3
[]
no_license
# 用法 # python simple_thresholding.py --image coins01.png import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) # 加载图片,转为灰度,做一下模糊 image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (7, 7), 0) cv2.imshow("Image", image) cv2.imshow("Blurred", blurred) # 使用基础的翻转二值化方法,第一个参数是我们要处理的图片,第二个参数是我们要处理的阈值 (T, threshInv) = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY_INV) cv2.imshow("Threshold Binary Inverse", threshInv) # 使用不同不翻转的二值化. (T, thresh) = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY) cv2.imshow("Threshold Binary", thresh) # 最后进行掩模操作 cv2.imshow("Output", cv2.bitwise_and(image, image, mask=threshInv)) cv2.waitKey(0)
Markdown
UTF-8
1,095
2.78125
3
[]
no_license
## Welcome This is meant as a boilerplate for a simple coding task. ## How to run terminal 1: ``` cd server yarn run seeds # creates seeds yarn run start # runs dev server ``` terminal 2: ``` cd client yarn run start ``` open in browser: http://localhost:3000 ## Asks * Build a simple filter form for the user list * Add a simple case-insensitive string search that filters results by name and bio * Eg if i'd search for "Pete" i would find "Peter Lastname" and "i was born in St Spetersburg" * Add a second search form that allows filtering for admins and non-admins * Feel free to not worry about scalability concerns * Implement a simple infinite scrolling pagination for the results * Feel free to ignore scalability concerns * General Qs: * How can we improve the setup of this app? * What changes would need to be done to allow simple integration tests in CI with this application? * eg via Cypress * How would you solve scalability for the full text search? * What kind of scalability issues could happen for the infinite scroll pagination?
PHP
UTF-8
2,738
3.015625
3
[]
no_license
<?php /** * @author Xethilos */ class Settings implements ArrayAccess { /** @var array */ protected $values = array(); /** @var string */ protected $filePath; /** @var string */ protected $namespace; /** @var Nette\Caching\Cache */ protected $cache = NULL; /** * @param array $values * @param string $filePath * @param string $namespace * @param Nette\Caching\Cache|null $cache */ public function __construct(array $values, $filePath, $namespace, $cache) { $this->values = $values; $this->filePath = $filePath; $this->namespace = $namespace; $this->cache = $cache; } /** * @param string $offset */ public function offsetExists($offset) { return isset($this->values[$offset]); } /** * @param string $offset */ public function offsetGet($offset) { return $this->values[$offset]; } /** * @param string $offset * @param mixed $value * @throws ConfigException */ public function offsetSet($offset, $value) { throw new ConfigException('You can change array with function change().'); } /** * @param string $offset * @throws ConfigException */ public function offsetUnset($offset) { throw new ConfigException('You cannot unset value.'); } /** * Merge and check changes * * @param array $array * @param string $path * @throws ConfigException */ protected function merge(array $array, $path) { foreach ($array as $index => $value) { if (!isset($this->values[$index])) { throw new ConfigException("Key '$index' does not exist in path '$path'"); } if (is_array($value)) { $this->merge($value, $index); } else { $this->values[$index] = $value; } } } /** * Save changes to neon * * @param array $array */ public function change(array $array) { $this->merge($array, $this->namespace); $neon = new Neon($this->filePath); $neon->encode(array('parameters' => $this->values) + $neon->decode()); $this->changeCache($this->namespace, $this); } /** * Save changes to cache */ public function changeCache() { if ($this->cache === NULL) { return; } $data = $this->cache->load('_configLoader'); $data['parameters'][$this->namespace] = $this; $this->cache->save('_configLoader', $data); } }
Java
UTF-8
2,030
2.546875
3
[]
no_license
import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class LockFreeSetImplTest { private LockFreeSet<Integer> set; @Before public void setUp() { set = new LockFreeSetImpl<>(); } @Test public void add() throws Exception { Assert.assertTrue(set.add(10)); Assert.assertTrue(set.contains(10)); Assert.assertTrue(set.add(20)); Assert.assertTrue(set.contains(20)); Assert.assertTrue(set.add(5)); Assert.assertTrue(set.contains(5)); Assert.assertFalse(set.add(5)); Assert.assertFalse(set.add(10)); Assert.assertFalse(set.add(20)); Assert.assertTrue(set.contains(5)); Assert.assertTrue(set.contains(10)); Assert.assertTrue(set.contains(20)); } @Test public void remove() throws Exception { add(); Assert.assertTrue(set.add(40)); Assert.assertTrue(set.contains(40)); Assert.assertTrue(set.add(1)); Assert.assertTrue(set.contains(1)); Assert.assertTrue(set.remove(10)); Assert.assertFalse(set.contains(10)); Assert.assertTrue(set.remove(1)); Assert.assertFalse(set.contains(1)); Assert.assertTrue(set.remove(40)); Assert.assertFalse(set.contains(40)); Assert.assertTrue(set.remove(5)); Assert.assertFalse(set.contains(5)); Assert.assertTrue(set.remove(20)); Assert.assertFalse(set.contains(20)); Assert.assertFalse(set.remove(20)); } @Test public void contains() throws Exception { Assert.assertFalse(set.contains(0)); } @Test public void isEmpty() throws Exception { Assert.assertTrue(set.isEmpty()); add(); Assert.assertFalse(set.isEmpty()); Assert.assertTrue(set.remove(5)); Assert.assertTrue(set.remove(10)); Assert.assertTrue(set.remove(20)); Assert.assertTrue(set.isEmpty()); remove(); Assert.assertTrue(set.isEmpty()); } }
Python
UTF-8
385
3.71875
4
[]
no_license
smallest = None largest = None while True: a=input("Enter the Number: ") if a=="done": break try: b=int(a) except: print("Invalid input") if smallest is None: smallest = b if largest is None: largest = b if b > largest : largest = b elif b < smallest : smallest = b print(largest) print(smallest)
Java
UTF-8
392
1.875
2
[]
no_license
package com.springboot.jpa; import com.springboot.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * Created by ghost on 2018/12/10. */ public interface UserJpa extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> { public User findByUsername(String username); }
Markdown
UTF-8
2,850
2.53125
3
[ "MIT" ]
permissive
# eChat eChat is a cross-platfrom instant chat application built with Flutter. ## Features - Send and recieve realtime messages - Send photos and videos - Seen status - Online status - Reply messages - Make voice and video calls (to be added soon) # Demo <p float="left"> <img src="https://user-images.githubusercontent.com/48331678/91775664-44615b00-ebf4-11ea-945d-436b210f4294.gif" width="40%" height="50%" alt="flutter chat app instant chat app"/> <img src="https://user-images.githubusercontent.com/48331678/91775854-d23d4600-ebf4-11ea-8eb8-084fec6042c0.gif" width="40%" height="50%" alt="flutter chat app instant send image"/> </p> <p float="left"> <img src="https://user-images.githubusercontent.com/48331678/91776037-4a0b7080-ebf5-11ea-835b-7de0acd8dfea.png" width="30%" height="50%" alt="flutter chat app instant messages screen"/> <img src="https://user-images.githubusercontent.com/48331678/91776207-948ced00-ebf5-11ea-9c15-869b9eeb1429.png" width="30%" height="50%" alt="flutter chat app instant chat screen"/> <img src="https://user-images.githubusercontent.com/48331678/91776248-ad959e00-ebf5-11ea-84ed-abbe8c1d8cfc.gif" width="30%" height="50%" alt="flutter chat app instant voice call"/> </p> #### Installation **Note:** Make sure your Flutter environment is setup. [help](https://flutter.dev/docs/get-started/install) In the command line: $ git clone https://github.com/melhamin/eChat.git $ cd eChat/ $ flutter run ### For running on Android or IOS emulator Make sure you have an emulator installed and running. Run the following command in your terminal. $ flutter run ##### Check out Flutter’s [documentation](http://flutter.io/) for help getting start with your Flutter project. # License ``` MIT License Copyright (c) 2020 Elham Amin 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. ```
Python
UTF-8
1,652
3.046875
3
[]
no_license
import java.lang.*; import java.io.*; import java.lang.*; public class Main { public static int[] array = null; public static int n, m; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line = null; String[] separatedLine = null; int max = 0; while((line = reader.readLine()) != null) { separatedLine = line.split("\\s+"); max = 0; n = Integer.valueOf(separatedLine[0]); m = Integer.valueOf(separatedLine[1]); separatedLine = reader.readLine().split("\\s+"); array = new int[n]; for(int i = 0; i < n; i++) { array[i] = Integer.valueOf(separatedLine[i]); } System.out.println(simulate((int) 1e9 + 5)); } } public static int simulate(int max) { int lo = 1, hi = max, mid = 0, ans = 0; while(lo <= hi) { mid = (lo + hi) / 2; if (can(mid)) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } public static boolean can(int capacity) { int currentCapacity = capacity; int counter = 1; for(int i = 0; i < n; i++) { if (array[i] > capacity) // if any vessel is bigger than provided capacity container { return false; } if (array[i] <= currentCapacity) // if any vessel is lesser than provided capacity then using ONE CAPACITY CONTAINER { currentCapacity -= array[i]; // decrementing capacity } else { currentCapacity = capacity - array[i]; // USING NEXT CAPACITY CONTAINER counter++; } } if (counter > m) return false; return true; } }
Markdown
UTF-8
766
2.546875
3
[]
no_license
--- nav_order: 4 --- # Translations To [translate Epoptes in your language](https://translations.launchpad.net/epoptes) you only need a web browser and a launchpad account. Usually less than half an hour is needed to complete the process. Once you've finished your translation, it will be automatically included in the next epoptes version. Please note that currently there's no native english speaker in Epoptes development team, so if you see some english text that contains syntax or grammatical errors or could be expressed in a more appropriate way, don't hesitate to contact the developers about it. Extensive help for translators is available [in this page](https://help.launchpad.net/Translations/StartingToTranslate). ![Translations](translations.png)
JavaScript
UTF-8
589
2.515625
3
[]
no_license
import React, { Component } from 'react'; class Player extends Component { constructor(props) { super(props); this.audio = new Audio(); } clicked(){ this.audio.play() //console.log("Hey I worked!"); }; render() { this.audio.src = this.props.src; return ( <div className="Player"> <button id="Buttons" onMouseDown={this.clicked.bind(this)} type="button">{this.props.label}</button> </div> ); } } //dont forget to export otherwise, all this is useless!!// export default Player;
C
GB18030
2,185
2.609375
3
[]
no_license
#include <stm32f10x_lib.h> #include "sys.h" #include "usart.h" #include "delay.h" #include "led.h" #include "key.h" #include "exti.h" #include "wdg.h" #include "timer.h" #include "lcd.h" #include "rtc.h" #include "wkup.h" #include "adc.h" #include "dma.h" #include "24cxx.h" //Mini STM32巶16 //IIC ʵ //ԭ@ALIENTEK //2010.6.8 //Ҫд뵽24c02ַ const u8 TEXT_Buffer[]={"MiniSTM32 IIC TEST"}; #define SIZE sizeof(TEXT_Buffer) int main(void) { u8 key; u16 i=0; u8 datatemp[SIZE]; Stm32_Clock_Init(9);//ϵͳʱ delay_init(72); //ʱʼ uart_init(72,9600); //1ʼ LED_Init(); //LEDʼ KEY_Init(); //ʼ LCD_Init(); //TFTLCDҺʼ AT24CXX_Init(); //IICʼ POINT_COLOR=RED;//Ϊɫ LCD_ShowString(60,50,"Mini STM32"); LCD_ShowString(60,70,"IIC TEST"); LCD_ShowString(60,90,"ATOM@ALIENTEK"); LCD_ShowString(60,110,"2010/6/10"); while(AT24CXX_Check())//ⲻ24c02 { LCD_ShowString(60,130,"24C02 Check Failed!"); delay_ms(500); LCD_ShowString(60,130,"Please Check! "); delay_ms(500); LED0=!LED0;//DS0˸ } LCD_ShowString(60,130,"24C02 Ready!"); //ʾʾϢ LCD_ShowString(60,150,"KEY0:Write KEY2:Read"); POINT_COLOR=BLUE;//Ϊɫ while(1) { key=KEY_Scan(); if(key==1)//KEY0,д24C02 { LCD_Fill(0,170,239,319,WHITE);// LCD_ShowString(60,170,"Start Write 24C02...."); AT24CXX_Write(0,(u8*)TEXT_Buffer,SIZE); LCD_ShowString(60,170,"24C02 Write Finished!");//ʾ } if(key==3)//KEY1,ȡַʾ { LCD_ShowString(60,170,"Start Read 24C02.... "); AT24CXX_Read(0,datatemp,SIZE); LCD_ShowString(60,170,"The Data Readed Is: ");//ʾ LCD_ShowString(60,190,datatemp);//ʾַ } i++; delay_ms(1); if(i==200) { LED0=!LED0;//ʾϵͳ i=0; } } }
PHP
UTF-8
672
2.765625
3
[]
no_license
<?php header('content-type:text/html;charset="utf-8"'); error_reporting(0); //接收数据 $username = $_GET['username']; $age = $_GET['age']; $sex = $_GET['sex']; //打开文件 $file_n = fopen("student.txt","a") or exit("Unable to open file!"); $file_a = fopen("age.txt","a") or exit("Unable to open file!"); $file_s = fopen("sex.txt","a") or exit("Unable to open file!"); //写数据 fwrite($file_n,"{$username}"."\r\n"); fwrite($file_a,"{$age}"."\r\n"); fwrite($file_s,"{$sex}"."\r\n"); //关闭文件 fclose($file_n); fclose($file_a); fclose($file_s); ?> <script> (function() { window.location="http://www.php.com/sf/form/index.html"; })(); </script>
Java
UTF-8
3,737
1.945313
2
[]
no_license
package com.smapley.powerwork.fragment; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; 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.Toast; import com.smapley.powerwork.R; import com.smapley.powerwork.activity.Login; import com.smapley.powerwork.application.LocalApplication; import com.smapley.powerwork.db.entity.UserEntity; import com.smapley.powerwork.utils.ActivityStack; import org.xutils.DbManager; import org.xutils.ex.DbException; import org.xutils.x; import cn.pedant.SweetAlert.SweetAlertDialog; /** * Created by smapley on 15/10/22. */ public abstract class BaseFragment extends Fragment { private boolean injected = false; private Context context; protected DbManager dbUtils; protected SharedPreferences sp_user; protected SharedPreferences sp_set; protected SweetAlertDialog dialog; protected UserEntity userEntity = null; @Override public void onAttach(Context context) { super.onAttach(context); this.context = context; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = x.view().inject(this, inflater, container); dbUtils = LocalApplication.getInstance().dbUtils; sp_user = LocalApplication.getInstance().sp_user; sp_set = LocalApplication.getInstance().sp_set; try { userEntity = dbUtils.findById(UserEntity.class, sp_user.getInt("id", 0)); } catch (DbException e) { e.printStackTrace(); } dialog = new SweetAlertDialog(context); initParams(view); injected = true; return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (!injected) { x.view().inject(this, this.getView()); } } /** * 设置参数 */ protected abstract void initParams(View view); public abstract void getDataForDb(); public abstract void getDataForWeb(); protected void showToast(int data) { Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show(); } protected void showToast(String data) { Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show(); } protected void showOutLoginDialog(final Context context, String details) { SweetAlertDialog dialog = new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE); dialog.showText(details) .showConfirmButton(R.string.login) .showCancelButton() .setOnSweetClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onConfirmClick(SweetAlertDialog dialog) { SharedPreferences.Editor editor = LocalApplication.getInstance().sp_user.edit(); editor.putBoolean("islogin", false); editor.commit(); ActivityStack.getInstance().finishAllActivity(); startActivity(new Intent(context, Login.class)); dialog.dismiss(); } @Override public void onFirstClick(SweetAlertDialog dialog) { } @Override public void onCancelClick(SweetAlertDialog dialog) { dialog.dismiss(); } }).show(); } }
JavaScript
UTF-8
2,037
3.515625
4
[]
no_license
//http://data.fixer.io/api/latest?access_key=3f144bb3405456657ec931bfe187002e //https://restcountries.eu/rest/v2/currency/USD const axios = require('axios'); // const getExchangeRate = (from,to) => { // return axios.get('http://data.fixer.io/api/latest?access_key=3f144bb3405456657ec931bfe187002e') // .then(response =>{ // const euro = 1/ response.data.rates[from]; // const rate = euro * response.data.rates[to]; // return rate; // }); // } const getExchangeRate = async (from,to) => { try{ const response = await axios.get('http://data.fixer.io/api/latest?access_key=3f144bb3405456657ec931bfe187002e') const euro = 1/ response.data.rates[from]; const rate = euro * response.data.rates[to]; if(isNaN(rate)){ throw new Error(); } return rate; }catch(e){ throw new Error('UNable to get exchange rate') } }; const getCountries = async (currencyCode) => { try { const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`) return response.data.map(country => country.name) } catch(e) { throw new Error ('Unable to get countries') } } // const convertCurrency = (from, to ,amount) => { // let convertedAmt; // getExchangeRate(from, to).then(rate => { // convertedAmt = (amount * rate.toFixed(2)); // return getCountries(to); // }).then( countries => { // return `${amount} ${from} is worth ${convertedAmt} ${to}. You can spend it in the following countries: ${countries.join(', ')}` // }) // } const convertCurrency = async ( from, to, amount) => { const rate = await getExchangeRate(from,to); const countries = await getCountries(to); const convertedAmt = (amount * rate.toFixed(2)); return `${amount} ${from} is worth ${convertedAmt} ${to}. You can spend it in the following countries: ${countries.join(', ')}` ; } convertCurrency('USD','EUR', 20).then(message =>{ console.log(message); });
PHP
UTF-8
2,521
2.703125
3
[ "CC0-1.0", "MIT" ]
permissive
<?php namespace YabaCon\Paystack\Routes; use YabaCon\Paystack\Contracts\RouteInterface; /** * Customer * Insert description here * * @category * @package * @author * @copyright * @license * @version * @link * @see * @since */ class Customer implements RouteInterface { /** Root * @param=> first_name, last_name, email, phone */ public static function root() { return '/customer'; } /** Create customer * @param=> first_name, last_name, email, phone */ public static function create() { return [ RouteInterface::METHOD_KEY => RouteInterface::POST_METHOD, RouteInterface::ENDPOINT_KEY => Customer::root(), RouteInterface::PARAMS_KEY => ['first_name', 'last_name', 'email', 'phone' ], RouteInterface::REQUIRED_KEY => [ RouteInterface::PARAMS_KEY => ['first_name', 'last_name', 'email' ] ] ]; } /** Get customer */ public static function getOne() { return [ RouteInterface::METHOD_KEY => RouteInterface::GET_METHOD, RouteInterface::ENDPOINT_KEY => Customer::root() . '/{id}', RouteInterface::ARGS_KEY => ['id' ], RouteInterface::REQUIRED_KEY => [RouteInterface::ARGS_KEY => ['id' ] ] ]; } /** List customers */ public static function getList() { return [ RouteInterface::METHOD_KEY => RouteInterface::GET_METHOD, RouteInterface::ENDPOINT_KEY => Customer::root(), RouteInterface::PARAMS_KEY => ['perPage', 'page' ] ]; } /** Update customer * @param=> first_name, last_name, email, phone */ public static function update() { return [ RouteInterface::METHOD_KEY => RouteInterface::PUT_METHOD, RouteInterface::ENDPOINT_KEY => Customer::root() . '/{id}', RouteInterface::PARAMS_KEY => ['first_name', 'last_name', 'email', 'phone' ], RouteInterface::ARGS_KEY => ['id' ], RouteInterface::REQUIRED_KEY => [ RouteInterface::ARGS_KEY => ['id' ], RouteInterface::PARAMS_KEY => ['first_name', 'last_name' ] ] ]; } }
Java
UTF-8
311
2.296875
2
[]
no_license
package com.ws.design.template; /** * @author Jun * data 2019-09-23 23:23 */ public abstract class AbstractProcess { abstract void firstStep(); abstract void secondStep(); abstract void last(); public void process() { firstStep(); secondStep(); last(); } }
Swift
UTF-8
2,692
2.609375
3
[]
no_license
// // Profile.swift // PicFlow // // Created by Antonio Hernandez on 7/2/17. // Copyright © 2017 Antonio Hernandez . All rights reserved. // import ObjectMapper import FacebookCore import TwitterKit import GoogleSignIn class Profile { //MARK: - Enumerations enum ProfileType : Int { case facebook case google case twitter case none } //MARK: - Singleton static let shared = Profile() //MARK: - Variable properties var type: ProfileType = .none { didSet { setUserProfile() } } var me: User = User() { didSet { if let didLoggedIn = didLoggedIn?(true) { didLoggedIn } } } var didLoggedIn: ((_ loggedIn: Bool) -> Void)? //MARK: - Life cycle private init() { } //MARK: - Private methods private func setUserProfile(){ switch type { case .facebook: getFacebookProfile() break case .google: getGoogleProfile() break case .twitter: getTwitterProfile() break default: break } } private func getFacebookProfile() { FBLogin.shared.setCurrentUser(success: { (user) in self.me = user }, error: { (error) in print(error) }) } private func getTwitterProfile() { TwitterLogin.shared.setCurrentUser(success: { (user) in self.me = user }, error: { (error) in print(error) }) } private func getGoogleProfile() { me = GoogleLogin.shared.currentUser } //MARK - Public Methods public func loggedIn() -> Bool { if let _ = GIDSignIn.sharedInstance().currentUser { type = .google return true } if let _ = AccessToken.current { type = .facebook return true } if let _ = Twitter.sharedInstance().sessionStore.session() { type = .twitter return true } return false } public func logOut() { switch type { case .facebook: FBLogin.shared.logOut() break case .google: GoogleLogin.shared.logOut() break case .twitter: TwitterLogin.shared.logOut() break default: break } } }
Java
UTF-8
2,736
3.5
4
[]
no_license
//implements a generic M by N matrix data structure //eli f. public class Matrix { private int rows; private int columns; private double[][] elements; //creates a matrix of zeros public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.elements = new double[rows][columns]; } // create matrix based on 2d array public Matrix(double[][] data) { rows = data.length; columns = data[0].length; this.elements = new double[rows][columns]; for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) this.elements[i][j] = data[i][j]; } public Matrix clone(Matrix B) { return new Matrix(this.elements); } public int getColumns() { return this.columns; } public int getRows() { return this.rows; } //gets the array storing all the info for this matrix public double[][] getElements() { return this.elements; } //TODO //method to get specific elements of a matrix //changes the value of this matrix to the dot product of itself and another matrix public void dot(Matrix B){ double[][] BElements = B.getElements(); //iterating over all rows for(int i = 0; i < this.rows; i++){ //iterating over all columns in second matrix for(int j = 0; j < B.getColumns(); j++){ //iterating over columns in arg1 for(int k = 0; k < this.columns; k++){ this.elements[i][j] = this.elements[i][k]*BElements[k][j]; } } } } //cacluates the transpose for a matrix does not actually alter this matrix, just generates the transpose public Matrix T(){ double[][] transpose = new double[this.rows][this.columns]; for(int i = 0; i < this.rows; i++){ for(int j = 0; j < this.columns; j++){ transpose[j][i] = this.elements[i][j]; } } return new Matrix(transpose); } //subtracts the second matrix from the first matrix public void minus(Matrix B){ if(B.getRows() != this.rows || B.getColumns() != this.columns) { throw new IllegalArgumentException("Matrix for subtraction has incorrect size"); } double[][] BElements = B.getElements(); for( int i = 0; i < this.rows; i++){ for( int j = 0; j < this.columns;j++){ this.elements[i][j] = this.elements[i][j] - BElements[i][j]; } } } public void multiply(double scalar){ for(int i = 0; i < this.rows;i++){ for(int j = 0; j < this.columns; j++){ this.elements[i][j] = this.elements[i][j]*scalar; } } } }
Python
UTF-8
7,568
2.546875
3
[ "MIT", "GPL-3.0-only" ]
permissive
# coding=utf-8 """ Various helper functions """ import datetime import os import shutil import typing from pathlib import Path import pefile import pkg_resources import requests from esst import LOGGER from esst.core import Status # from esst.core.fs_paths import FS from .arg import arg from .find_port import assign_ports from .github import get_latest_release from .remove_old_files import clean_all_folder def external_ip(): """ Returns: external IP of this machine """ try: return requests.get('https://api.ipify.org').text except requests.ConnectionError: LOGGER.error('unable to obtain external IP') return 'unknown' def sanitize_path(path: typing.Union[str, Path]) -> str: """ Sanitize a filesystem path Args: path: path to sanitize Returns: sanitized path as a string """ return str(path).replace('\\', '/') def check_path(*path: typing.Union[str, Path], must_exist: bool = True) -> Path: """ Verifies a Path object :param path: path to check :type path: Path :param must_exist: set to True if Path must exist :type must_exist: bool :return: verified Path :rtype: Path :raises : FileNotFoundError if Path must exist but isn't found """ _path = Path(*path).absolute() if must_exist and not _path.exists(): raise FileNotFoundError(str(_path)) return _path.absolute() def check_file(*file_path: typing.Union[str, Path], must_exist: bool = True) -> Path: """ Verifies a Path object as a file :param file_path: path to check :type file_path: Path :param must_exist: set to True if Path must exist :type must_exist: bool :return: verified Path :rtype: Path :raises : FileNotFoundError if Path must exist but isn't found :raises : TypeError if Path isn't a file """ _file_path = check_path(*file_path, must_exist=must_exist) if _file_path.exists(): if not _file_path.is_file(): raise TypeError(f'not a file: {str(_file_path.absolute())}') return _file_path def check_dir(*dir_path: typing.Union[str, Path], must_exist: bool = True, create: bool = False) -> Path: """ Verifies a Path object as a directory :param dir_path: path to check :type dir_path: Path :param must_exist: set to True if Path must exist :type must_exist: bool :param create: set to True if the Path should be created :type create: bool :return: verified Path :rtype: Path :raises : FileNotFoundError if Path must exist but isn't found :raises : TypeError if Path isn't a directory """ must_exist = not create if create else must_exist _dir_path = check_path(*dir_path, must_exist=must_exist) if _dir_path.exists(): if not _dir_path.is_dir(): raise TypeError(f'not a directory: {str(_dir_path.absolute())}') else: if create: _dir_path.mkdir(parents=True) return _dir_path def _do_backup(original: Path, backup: Path): LOGGER.debug('%s: checking for backup', original.absolute()) if not original.exists(): LOGGER.debug('%s: original does no exist, skipping backup', original.absolute()) return if not backup.exists(): LOGGER.debug('%s: creating backup: %s', original.absolute(), backup.absolute()) shutil.copy2(str(original.absolute()), str(backup.absolute())) else: LOGGER.debug('%s: backup already exists', backup.absolute()) def create_versioned_backup(file_path: typing.Union[str, Path], file_must_exist: bool = True): """ Creates a backup of a file, with a "_backup_DCS-VERSION" suffix, if the backup does not exist yet Args: file_must_exist: fails if the file to be backed up does not exist file_path: file to backup """ file_path_as_path = check_file(file_path, must_exist=file_must_exist) backup_file = Path(file_path_as_path.parent, f'{file_path_as_path.name}_backup_{Status.dcs_version}') _do_backup(file_path_as_path, backup_file) def create_simple_backup(file_path: typing.Union[str, Path], file_must_exist: bool = True): """ Creates a backup of a file, with a "_backup_DCS-VERSION" suffix, if the backup does not exist yet Args: file_path: file to backup file_must_exist: fails if the file to be backed up does not exist """ file_path_as_path = check_file(file_path, must_exist=file_must_exist) backup_file = Path(file_path_as_path.parent, f'{file_path_as_path.name}_backup') _do_backup(file_path_as_path, backup_file) def now(): """ Returns: epoch """ return datetime.datetime.now().timestamp() def read_template(template_name: str) -> str: """ Reads a template file, getting it from the local install or from the package Args: template_name: name of the template file Returns: template file content """ LOGGER.debug('reading template: %s', template_name) template_path = os.path.join(os.path.dirname(__file__), 'templates', template_name) if not os.path.exists(template_path): LOGGER.debug('template not found, trying from pkg_resource') template_path = pkg_resources.resource_filename('esst', f'/dcs/templates/{template_name}') if not os.path.exists(template_path): raise FileNotFoundError(template_path) with open(template_path) as handle_: LOGGER.debug('returning template content') return handle_.read() def get_esst_changelog_path() -> str: """ Returns: changelog path """ changelog_path = os.path.join(os.path.dirname(__file__), 'CHANGELOG.rst') if not os.path.exists(changelog_path): LOGGER.debug('changelog not found, trying from pkg_resource') changelog_path = pkg_resources.resource_filename( 'esst', 'CHANGELOG.rst') if not os.path.exists(changelog_path): LOGGER.error('changelog not found') return '' return changelog_path def get_dcs_log_file_path() -> str: """ Returns: path to DCS log file """ from esst import FS _log_dir_path = str(FS.dcs_logs_dir.absolute()) # type: ignore return os.path.join(_log_dir_path, 'dcs.log') def _parse_file_info(file_info_list) -> typing.Optional[str]: for _file_info in file_info_list: if _file_info.Key == b'StringFileInfo': # pragma: no branch for string in _file_info.StringTable: # pragma: no branch if b'FileVersion' in string.entries.keys(): # pragma: no branch file_version = string.entries[b'FileVersion'].decode('utf8') return file_version return None # pylint: disable=inconsistent-return-statements def get_product_version(path: typing.Union[str, Path]) -> str: """ Get version info from executable Args: path: path to the executable Returns: VersionInfo """ path = Path(path).absolute() pe_info = pefile.PE(str(path)) try: for file_info in pe_info.FileInfo: # pragma: no branch if isinstance(file_info, list): result = _parse_file_info(file_info) if result: return result else: result = _parse_file_info(pe_info.FileInfo) if result: return result raise RuntimeError(f'unable to obtain version from {path}') except (KeyError, AttributeError) as exc: raise RuntimeError(f'unable to obtain version from {path}') from exc
Markdown
UTF-8
3,045
2.90625
3
[]
permissive
# Case 37: Traffic Lights ## Introduction In our daily life, many traffic accidents should have been avoided. These traffic accidents are often caused by people not observing the traffic rules, thus, we must understand the traffic rules. For example, the common traffic lights in our lives, red light means not passing, yellow light means warning, and green light means permission to pass. Let's make a traffic light controlled by the micro:bit. ![](./images/case_01_01.png) ## Quick Start ### Materials Required Nezha expansion board × 1 micro:bit × 1 LED-red × 1 LED-green × 1 LED-yellow × 1 RJ11 wires × 3 ***Tips: You may need to purchase [Nezha Inventor's Kit](https://shop.elecfreaks.com/products/elecfreaks-micro-bit-nezha-48-in-1-inventors-kit-without-micro-bit-board?_pos=2&_sid=ed1b6fbd2&_ss=r) if you want all the above compoents.*** ### Connection Diagram Connect the red LED to J1, yellow LED to J2 and green LED to J3 on the Nezha expansion board as the picture shows. ![](./images/case_01_03.png) ### Assembly Video Video reference:[https://youtu.be/TmsDDWLcgcs](https://youtu.be/TmsDDWLcgcs) <iframe width="560" height="315" src="https://www.youtube.com/embed/TmsDDWLcgcs" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> ### Assembly Steps ![](./images/case_step_01_01.png) ![](./images/case_step_01_02.png) ![](./images/case_step_01_03.png) ![](./images/case_step_01_04.png) ![](./images/case_step_01_05.png) ![](./images/case_step_01_06.png) ![](./images/case_step_01_07.png) ![](./images/case_step_01_08.png) ![](./images/case_step_01_09.png) ![](./images/case_step_01_10.png) ## Makecode Programming ### Step 1 Click "Advanced" in the MakeCode to see more choices. ![](./images/case_01_10.png) For programming, we need to add a package: click "Extensions" at the bottom of the MakeCode drawer and search with "PlanetX" in the dialogue box to download it. ![](./images/case_01_11.png) ***Notice:*** If you met a tip indicating that some codebases would be deleted due to incompatibility, you may continue as the tips say or create a new project in the menu. ### Step 2 ### Code as below: ![](./images/case_01_12.png) ### Reference Link:[https://makecode.microbit.org/_M6RiKA642WPP](https://makecode.microbit.org/_M6RiKA642WPP) You may also download it directly below: <div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="https://makecode.microbit.org/#pub:_M6RiKA642WPP" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div> ### Result The red LED lights on for 5 seconds and then lights off; the yellow LED lights on for 2 seconds and off then; the green LED lights on for 5 seconds and off then. ![](./images/case-gif-01.gif)
JavaScript
UTF-8
3,996
2.71875
3
[]
no_license
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var VotingSchemaObj = mongoose.model('Voting'); router.param('candidate', function(req, res, next, id) { var query = VotingSchemaObj.findById(id); query.exec(function (err, candidate){ if (err) { return next(err); } if (!candidate) { return next(new Error("can't find candidate")); } req.candidate = candidate; return next(); }); }); router.get('voting/:candidate', function(req, res){ console.log('voting/:candidate route') res.json(req.candidate); }); router.put('/voting/:candidate/upvote', function(req, res, next) { console.log("Put Route "+req.candidate.Name); req.candidate.upvote(function(err, candidate){ if (err) { return next(err); } res.json(candidate); }); }); router.delete('/voting/:candidate',function(req,res) { req.candidate.remove(); res.sendStatus(200); }); router.get('/voting', function(req, res, next) { console.log("Get Route"); VotingSchemaObj.find(function(err, candidates){ if(err){ console.log("Error"); return next(err); } res.json(candidates); console.log("res.json Get Route"); }); console.log("returningGet Route"); }); router.post('/voting', function(req, res, next) { console.log("Post Route"); var candidate = new VotingSchemaObj(req.body); console.log("Post Route"); console.log(candidate); candidate.save(function(err, candidate){ console.log("Error "+err); if(err){ return next(err); } console.log("Post Route before json"); res.json(candidate); }); }); router.delete('/voting', function(req, res, next) { console.log('in the delete all route') VotingSchemaObj.find({}).remove(function(err, votingList) { if (err) return console.error(err); //If there's an error, print it out else { res.sendStatus(200); } }); }); // /* GET comments from database */ // router.get('/voting', function(req, res, next) { // console.log("request query", req.query.name); // var name = req.query.name; // if(name) //anything exists in the name field // { // VotingSchemaObj.find({Name : req.query.name}, function(err,votingList) { //Calls the find() method on your database // if (err) return console.error(err); //If there's an error, print it out // else { // console.log(votingList); //Otherwise console log the comments you found // res.json(votingList); //Then send the comments // } // }) // } // else{ // console.log("In the GET route?"); // VotingSchemaObj.find(function(err,votingList) { //Calls the find() method on your database // if (err) return console.error(err); //If there's an error, print it out // else { // console.log(votingList); //Otherwise console log the comments you found // res.json(votingList); //Then send the comments // } // }) // } // }); // router.get('/voting/',function(req,res) { // res.json(req.candidate); // }); // router.delete('/voting/:candidate',function(req,res) { // req.candidate.remove(); // res.sendStatus(200); // }); // // router.delete('/voting', function(req, res, next) { // // VotingSchemaObj.find({}).remove(function(err, votingList) { // // if (err) return console.error(err); //If there's an error, print it out // // else { // // res.sendStatus(200); // // } // // }); // //}); // // router.get('/comment', function(req, res, next) { // // console.log("In the GET route?"); // // Comment.find(function(err,commentList) { //Calls the find() method on your database // // if (err) return console.error(err); //If there's an error, print it out // // else { // // console.log(commentList); //Otherwise console log the comments you found // // res.json(commentList); //Then send the comments // // } // // }) // // }); module.exports = router;
PHP
UTF-8
987
2.640625
3
[]
no_license
<?php function getAll($tbl){ include('connect.php'); $queryAll = 'SELECT * FROM '.$tbl; $runAll = $pdo->query($queryAll); if($runAll){ return $runAll; }else{ $error = 'There was a problem accessing this info.'; return $error; } } function getSingle($tbl, $col, $value){ include('connect.php'); $querySingle = 'SELECT * FROM '.$tbl.' WHERE '.$col.' = '.$value; $runSingle = $pdo->query($querySingle); if($runSingle){ return $runSingle; }else{ $error = 'There was a problem'; return $error; } } function filterResults($tbl, $tbl_2, $tbl_3, $col, $col_2, $col_3, $filter){ include('connect.php'); $filterQuery = 'SELECT * FROM '.$tbl.' as a, '.$tbl_2.' as b, '.$tbl_3.' as c WHERE a.'.$col.' = c.'.$col.' AND b.'.$col_2.' = c.'.$col_2.' AND b.'.$col_3.' = "'.$filter.'"'; $runQuery = $pdo->query($filterQuery); if($runQuery){ return $runQuery; }else{ $error = 'There was a problem'; return $error; } } ?>
C#
UTF-8
979
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Yaar.Objects.Reference { class Wolfram { public Wolfram(string query) { var url = "http://api.wolframalpha.com/v2/query?input={0}&appid=2PWVJ9-9XEHHYT93V".Template(query); var doc = new XmlDocument(); doc.LoadXml(new BrowserClient().DownloadString(url)); Result = "I don't know."; Images = new List<string>(); foreach (XmlNode node in doc.SelectNodes("//pod/subpod/img")) Images.Add(node.Attributes["src"].Value); try { Result = doc.SelectSingleNode("//pod[@title='Result']/subpod/plaintext").InnerText; } catch{} } public List<string> Images { get; private set; } public string Result { get; private set; } } }
Java
UTF-8
1,958
2.1875
2
[]
no_license
/* * Copyright 2004 - 2013 Wayne Grant * 2013 - 2016 Kai Kramer * * This file is part of KeyStore Explorer. * * KeyStore Explorer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * KeyStore Explorer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeyStore Explorer. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.keystore_explorer.crypto.secretkey; import net.sf.keystore_explorer.crypto.CryptoException; import net.sf.keystore_explorer.crypto.KeyInfo; import net.sf.keystore_explorer.crypto.TestCaseCrypto; import org.junit.Test; import javax.crypto.SecretKey; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestCaseSecretKeyUtil extends TestCaseCrypto { @Test public void testAllSecretKeyTypes() throws CryptoException { for (SecretKeyType secretKeyType : SecretKeyType.values()) { testSecretKeyType(secretKeyType); } } @Test private void testSecretKeyType(SecretKeyType secretKeyType) throws CryptoException { for (int keySize = secretKeyType.minSize(); keySize <= secretKeyType.maxSize(); keySize += secretKeyType .stepSize()) { SecretKey secretKey = SecretKeyUtil.generateSecretKey(secretKeyType, keySize); KeyInfo keyInfo = SecretKeyUtil.getKeyInfo(secretKey); assertTrue(secretKeyType.jce().equalsIgnoreCase(keyInfo.getAlgorithm())); assertEquals(secretKeyType, SecretKeyType.resolveJce(keyInfo.getAlgorithm())); assertEquals(keySize, keyInfo.getSize().intValue()); } } }
Python
UTF-8
2,221
2.90625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 17 16:23:32 2020 @author: user """ import re import string import random import glob import operator import heapq from collections import defaultdict, Counter, defaultdict import math from functools import reduce import csv from pprint import pprint from functools import lru_cache from datetime import datetime sentences = [ "今天可能下雨", "中華民國於一九九五年三月一日開始實施全民健保", "孫中山先生推翻滿清建立中華民國", "教授應該要為辛苦的助教加薪", "火鍋是四川的特色", "波士頓茶葉事件促使美國革命", "羅馬帝國皇帝遭到殺害", ] """ WC """ mydict=dict() def gramfreqdict(text): for word in text: word = word.split("|")[0] if type(mydict.get(word,0)) == "NoneType": mydict[word] = 1 else : mydict[word]=mydict.get(word,0)+1 #return mydict file = open("COCT.small.txt", 'r', encoding='UTF-8') while True: line = file.readline() if not line: break split_line = line.split() gramfreqdict(split_line) #print(line, end='', sep = ' ') file.close() """ 分詞 """ def returnSum(myDict): sum = 0 for i in myDict: sum = sum + myDict[i] return sum def splits(text, L): return [(text[:i+1], text[i+1:]) for i in range(min(len(text), L))] def getword(sentence,l,total): if l == 0 : print(total) return 0 exist = [] sp_sentence = splits(sentence,l) h=0 for i in sp_sentence: if i[0] in mydict: exist.append(1) elif i[0] not in mydict: exist.append(0) for j in range(l): if exist[j] == 1 : count = j print(sentence[h:h+count+1]) voc = sentence[h:h+count+1] total = total + unigram(voc) #print(total) getword(sentence[h+count+1:l],l-count-1,total) def my_word(sentence): l = len(sentence) getword(sentence,l,0) def unigram(word): p = (mydict[word] + 1) / (len(mydict) + returnSum(mydict)) return math.log(p) #my_word(sentences[0]) for i in sentences: my_word(i)
Java
UTF-8
434
2.359375
2
[]
no_license
/** * @author 许瑞锐 * @date 2020/9/4 11:04 * @description {java类描述} */ public class Resource { private int id; public Resource(int id) { this.id = id; } @Override public String toString() { return "Resource{" + "id=" + id + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
Python
UTF-8
79
2.78125
3
[]
no_license
import math def calculate_area(radius): return math.pi * radius * radius
JavaScript
UTF-8
4,815
2.65625
3
[]
no_license
const fs = require('fs'); const { ungzip } = require('node-gzip'); const colors = require('colors'); const Path = require('path'); const scriptName = Path.basename(__filename); const movies_id = require('../models/movies_id.js'); const serials_id = require('../models/serials_id.js'); const { contentDownloader } = require('../service/contentDownloader'); const { getFullDayBackup } = require('../service/dailyBackup'); const { getCurrentDate } = require('../utils'); // Function that start parsing all Movies exports.startParsing = async (count, delay, type) => { try { // Get current date const date = await getCurrentDate(); // Get backup of current day await getFullDayBackup(date, type); // Get compressed Day import for the prev day const data = fs.readFileSync(`./download/${date}_${type}.json.gz`); // Decompressed data and make them to string const decompressed = await ungzip(data); const stringData = await decompressed.toString(); console.log("[PARSER]: Start decompressed data and convert them..".green); // Convert string of objects to array of objects const arr = stringData.split("\n"); console.log("[PARSER]: Decompressed data length is: ".green, colors.cyan(arr.length)); // Create array for most popular content const mostPopular = []; // Run cycle and filter the prev data array (sort by popularity) arr.forEach(item => { if (item) { const obj = JSON.parse(item); if (obj.popularity > 1) { // Save only ID's on array mostPopular.push(obj.id) } } }); console.log("[PARSER]: Filtered (popularity > 1.00) data array length is: ".green, colors.cyan(mostPopular.length)); // Call downloader function for parsing or update if (type === 'movie') { await contentDownloader(mostPopular, count, delay, type, '../img_movie_posters', '../img_movie_backdrops'); } if (type === 'serial') { await contentDownloader(mostPopular, count, delay, type, '../img_serial_posters', '../img_serial_backdrops'); } } catch (e) { console.log(colors.yellow(scriptName) , colors.red(e.message)) } }; // Function that start updating database with new Movies exports.startUpdate = async (count, delay, type) => { try { // Get current date const date = await getCurrentDate(); // Get backup of current day await getFullDayBackup(date, type); // Get compressed Day import for the prev day const data = fs.readFileSync(`./download/${date}_${type}.json.gz`); // Decompressed data and make them to string const decompressed = await ungzip(data); const stringData = await decompressed.toString(); console.log("[UPDATER]: Start decompressed data and convert them..".green); // Convert string of objects to array of objects const arr = stringData.split("\n"); console.log("[UPDATER]: Decompressed data length is: ".green, colors.cyan(arr.length)); // Array with new data const newData = []; arr.forEach(item => { if (item) { const obj = JSON.parse(item); if(obj.popularity > 1) { // Save only ID's on array newData.push(obj.id) } } }); console.log("[UPDATER]: Filtered (popularity > 1.00) data array length is:".green, colors.cyan(newData.length)); // Array with old data from database (only ID's) let oldData; if (type === 'movie') { oldData = await movies_id.find({}); } if (type === 'serial') { oldData = await serials_id.find({}); } console.log("[UPDATER]: Previous period data array (from database) length is:".green, colors.cyan(oldData[0].items.length)); // Array with difference between New Data and Old data from database const difference = newData.filter(x => !oldData[0].items.includes(x)); console.log("[UPDATER]: Difference between new data and array with id's (from database) is:".green, colors.cyan(difference.length)); // Call downloader function for parsing or update if (type === 'movie') { await contentDownloader(difference, count, delay, type, '../img_movie_posters', '../img_movie_backdrops'); } if (type === 'serial') { await contentDownloader(difference, count, delay, type, '../img_serial_posters', '../img_serial_backdrops'); } } catch (e) { console.log(colors.yellow(scriptName) , colors.red(e.message)) } };
Markdown
UTF-8
2,231
2.671875
3
[]
no_license
# Store.Categories Property (Outlook) Returns a **[Categories](319efa26-269d-9f2f-c8ec-33082e80a9e2.md)** collection that represents all of the categories that are defined for the **[Store](1eb22fe9-8849-7476-5388-2515b48591b9.md)** . Read-only. ## Syntax _expression_ . **Categories** _expression_ A variable that represents a **Store** object. ## Remarks This property is similar to the **[Categories](3963afca-3a7e-38d7-1347-7e1467be3a10.md)** property of the **[NameSpace](f0dcaa19-07f5-5d42-a3bf-2e42b7885644.md)** object, except that the **Store.Categories** property applies to a session profile that specifies one or more accounts and **Store.Categories** specifies the categories for the store that an account is associated with, whereas **NameSpace.Categories** applies to a session profile that defines only one account and the **NameSpace.Categories** property specifies the Master Category List for that session. For certain secondary delivery stores such as an IMAP store, the **Categories** property returns the **Categories** collection for the primary store. IMAP stores do not actually support a separate categories collection. ## Example The following code sample in Microsoft Visual Basic for Applications (VBA) displays the name of each **[Category](143ef095-54b0-cbe2-e356-632029061ac2.md)** object that is contained in the **Categories** collection associated with each **Store** object in the **[Stores](8915a8e4-9c22-21d5-c492-051d393ce5f7.md)** collection for the session. ```vb Sub EnumerateCategoriesForStores() Dim oStores As Outlook.Stores Dim oStore As Outlook.Store Dim oCategories As Outlook.Categories Dim oCategory As Outlook.Category Set oStores = Application.Session.Stores For Each oStore In oStores Debug.Print oStore.DisplayName Debug.Print "--------------Categories-----------------" Set oCategories = oStore.Categories For Each oCategory In oCategories Debug.Print Chr(9) &amp; oCategory.Name Next Debug.Print "" Next End Sub ``` ## See also #### Concepts [Store Object](1eb22fe9-8849-7476-5388-2515b48591b9.md) #### Other resources [Store Object Members](84c1d423-e507-0b3b-6570-33829b94be04.md)
Java
UTF-8
191
1.695313
2
[ "Apache-2.0" ]
permissive
package de.arthurpicht.cli.common; public class CLISpecificationException extends RuntimeException { public CLISpecificationException(String message) { super(message); } }
Markdown
UTF-8
1,819
2.640625
3
[ "MIT" ]
permissive
# APL Language Server Client This extension implements the client for an APL Language Server. The server is embedded with the extension, but has its own repository on [APL Language Server](https://github.com/optimasystems/apl-language-server). Please report issues or feature requests to that project. The language server requires a copy of Dyalog v17.0. Get your copy on [Download Dyalog](https://www.dyalog.com/download-zone.htm). ## Features This Language Server works for apl files. It has the following language features: ### Tool tips on primitives ![tooltips](images/tooltips.gif) ### Prefix completion Prefix completion to simplify typing APL primitives without an IME. ![prefixComplete](images/prefixComplete.gif) ## Configuration This extension has the configuration options listed below: ```json { "apl.server.executablePath": "dyalog.exe", "apl.server.maxWS": "4G", "apl.server.prefixCompleteCharacters": "`", "apl.server.wsPath": "/my/own/apl-language-server.dws" } ``` The language server requires a copy of Dyalog v17.0. You can provide a path to the executable in `apl.server.executablePath` to ensure the correct version of Dyalog is used (if you have more than one). You control the memory limit of the language server by setting `apl.server.maxWS` to a number followed by `[M|G]` (eg. 256M). To change the character(s) used for prefix completion, set the `apl.server.prefixCompleteCharacters` to one or more characters. The extension comes with an embedded copy of the [APL Language Server](https://github.com/optimasystems/apl-language-server). You can download a copy of the language server and then set the path to the dws in `apl.server.wsPath` to make use of an external language server. ## Copyright The logo is Copyright © 2004 - 2018 Dyalog Ltd.
Markdown
UTF-8
3,423
3.671875
4
[ "MIT" ]
permissive
###### Core > object # {{LIB_NAME}}.object > 객체 관련 코어 확장 기능을 사용할 수 있습니다. ## 확장기능 - [keys()](#keys) - [values()](#values) - [map()](#map) - [hasObject()](#hasobject) - [toQueryString()](#toquerystring) - [traverse()](#traverse) - [remove()](#remove) - [stringify()](#stringify) <br> ## keys() 객체의 열거가능한 속성 및 메서드 이름을 배열로 반환 합니다. API | 설명 --- | --- @param {Object} | 객체 @return {Array} | 객체의 열거가능한 속성의 이름이 포함된 배열 ```js {{LIB_NAME}}.object.keys({name: 'Axl rose', age: 50}); // ['name', 'age'] ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## values() 객체의 열거가능한 속성의 값을 배열로 반환 합니다. API | 설명 --- | --- @param {Object} | 객체 @return {Array} | 객체의 열거가능한 속성의 값들이 포함된 배열 ```js {{LIB_NAME}}.object.values({name: 'Axl rose', age: 50}); // ['Axl rose', 50] ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## map() 객체 요소를 콜백함수로 하여금 각 요소를 가공 합니다. API | 설명 --- | --- @param {Object} | 객체 @param {Function} | 콜백함수 @return {Object} | 가공된 객체 ```js {{LIB_NAME}}.object.map({1; 'one', 2: 'two', 3: 'three'}, function(item, key) { return item + '__'; }); // {1: 'one__', 2: 'two__', 3: 'three__'} ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## hasObject() 요소가 있는 json 객체인지 체크 합니다. API | 설명 --- | --- @param {Object} | 객체 @return {Boolean} | 요소가 하나라도 있는지 여부 ```js var obj1 = {}; {{LIB_NAME}}.object.hasObject(obj1); // false ``` ```js var obj2 = {a: 'A'}; {{LIB_NAME}}.object.hasObject(obj2); // true ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## toQueryString() 객체를 쿼리스크링으로 변환 합니다. API | 설명 --- | --- @param {Object} | 객체 @param {Boolean} | URL 인코딩할지 여부 (optional) @return {String} | 결과 문자열 ```js {{LIB_NAME}}.object.toQueryString({a:1, b: 2, c: {d: 4}}); // 'a=1&b=2&c[d]=4' ``` ```js {{LIB_NAME}}.object.toQueryString({google:'https://www.google.co.kr/'}, true); // 'google=https%3A%2F%2Fwww.google.co.kr%2F' ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## traverse() 주어진 객체의 키값와 요소를 맞바꿔 줍니다. API | 설명 --- | --- @param {Object} | 객체 @return {Object} | 맞바꾼 객체 ```js {{LIB_NAME}}.object.traverse({1:'a', 2:'b', 3:'c', 4:'d'}); // {a:1, b:2, c:3, d:4} ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## remove() 주어진 리터럴에서 key에 해당하는 요소를 삭제 합니다. API | 설명 --- | --- @param {Object} | 객체 @param {String} | 삭제할 키값 @return | 지정한 요소가 삭제된 객체 ```js var obj = {a: 'A', b: 'B'}; {{LIB_NAME}}.object.remove(obj, 'b'); // {a: 'A'} // delete obj.b 네이티브 삭제 기능 권장 ``` [▲ 확장기능 목록 이동](#확장기능) <br> ## stringify() 객체를 문자열로 변환 합니다.(JSON을 지원하는 브라우저에서는 내장 JSON.stringify를 사용 합니다.) API | 설명 --- | --- @param {Object} | 객체 @return {String} | 변환된 문자 ```js {{LIB_NAME}}.object.stringify({a: 'A'}); // '{"a": "A"}' ``` [▲ 확장기능 목록 이동](#확장기능)
Shell
UTF-8
593
3.40625
3
[]
no_license
#!/bin/bash # Run from this project's root directory(typically FuzMusic/) # Get tags from all files in a directory with some default settings if [[ -z $1 ]]; then echo "[!] Please specify a directory" elif [[ -z $2 ]] && [[ -n $1 ]]; then echo "[!] Reading in jsons from $1" echo "[!] Please input new pickle filename(.pik): " read PICKLEFILE python preprocess/get_tags_from_jsonfiles.py $1 $PICKLEFILE --limit 100 echo "[!] Extracted all tags" echo "[!] Running clustering algorithm" python eval/predict_user.py "$1" "$PICKLEFILE" preprocessed_data/test/user_000001.json fi
Rust
UTF-8
5,190
3.578125
4
[]
no_license
use rand::prelude::*; use rand::distributions::WeightedIndex; // Quality // // An integer from 0-5 indicating how easily the information was remembered today. This could correspond to a button such as "Difficult" or "Very Easy." // // The official algorithm description explains the meaning of each number: #[derive(Copy,Clone,PartialEq,PartialOrd,Debug)] pub enum Quality { Five = 5, // perfect response Four = 4, // correct response after a hesitation Three = 3, // correct response recalled with serious difficulty Two = 2, // incorrect response; where the correct one seemed easy to recall One = 1, // incorrect response; the correct one remembered Zero = 0, // complete blackout. } use Quality::*; impl Quality { pub fn weighted_random() -> Quality { let mut rng = thread_rng(); let weights = [2,4,3,1,1,1]; let dist = WeightedIndex::new(&weights).unwrap(); let items = [Five, Four, Three, Two, One, Zero]; items[dist.sample(&mut rng)] } } // ## Repetitions (integer) // // The number of times the information has been reviewed prior to this review. `repetitions` should equal zero for the first review. // // SM-2 uses this value to define specific intervals for the first and second reviews. SM-2 will also reset this value to zero when `quality` is less than 3. type Repetitions = u32; static DEFAULT_REPETITIONS: Repetitions = 0; // ## Ease factor (float) // // A floating point number (≥ 1.3) generated by the last iteration of the SM-2 algorithm. `previous ease factor` should equal 2.5 for the first review. // // The ease factor is used to determine the number of days to wait before reviewing again. Each call to SM-2 adjusts this number up or down based on `quality`. type EaseFactor = f32; static DEFAULT_EASE_FACTOR: EaseFactor = 2.5; // ## Interval (integer) // // Generated by the last iteration of the SM-2 algorithm. Indicates the number of days to wait between reviews. // // This previous interval is used when calculating the new interval. `previous interval` should equal zero for the first review. type Interval = u32; static DEFAULT_INTERVAL: Interval = 0; pub fn sm2(quality: Quality, previous_ease_factor: EaseFactor, previous_repetitions: Repetitions, previous_interval: Interval) -> (Interval, Repetitions, EaseFactor) { let interval: Interval; let mut ease_factor: EaseFactor; let repetitions: Repetitions; // If `quality` is greater than or equal to 3, indicating a correct response: if quality as u32 >= 3 { interval = match previous_repetitions { // 1. If `repetitions` is 0 (first review), set `interval` to 1 day. 0 => 1, // 2. If `repetitions` is 1 (second review), set `interval` to 6 days. 1 => 6, // 3. If `repetitions` is greater than 1 (subsequent reviews), set `interval` to `previous interval * previous ease factor`. (See note about recursion below.) // 4. Round `interval` up to the next whole number. _ => (previous_interval as f32 * previous_ease_factor).ceil() as u32 }; // 5. Increment `repetitions` by 1. repetitions = previous_repetitions + 1; // 6. Set `ease factor` to result of ease_factor formula ease_factor = calculate_ease_factor(previous_ease_factor, quality); } else { // If `quality` is less than 3, indicating an incorrect response: // 1. Set `repetitions` to 0. repetitions = 0; // 2. Set `interval` to 1. interval = 1; // 3. Set `ease factor` to `previous ease factor` (no change). ease_factor = previous_ease_factor } if ease_factor < 1.3 { ease_factor = 1.3; } (interval, repetitions, ease_factor) } fn calculate_ease_factor(previous_ease_factor: EaseFactor, quality: Quality) -> EaseFactor { // # Ease factor formula // // After the first two reviews, `ease factor` is adjusted using this formula: // // The magic numbers come from the official algorithm description. // // This increases `ease factor` when `quality` is 5, makes no change when `quality` is 4, and decreases `ease factor` by varying amounts when `quality` is lower than 4. The lower `quality` is, the more `ease factor` is decreased. previous_ease_factor + (0.1 - ((5 - quality as u32) as f32) * (0.08 + ((5 - quality as u32) as f32) * 0.02)) } #[derive(Debug)] pub struct Fact { name: String, interval: Interval, repetitions: Repetitions, ease_factor: EaseFactor, } impl Fact { pub fn default(name: String) -> Fact { Fact { name, interval: DEFAULT_INTERVAL, repetitions: DEFAULT_REPETITIONS, ease_factor: DEFAULT_EASE_FACTOR, } } pub fn update(old: Fact, quality: Quality) -> Fact { let (new_interval, new_repetitions, new_ease_factor) = sm2(quality, old.ease_factor, old.repetitions, old.interval); Fact { name: old.name, interval: new_interval, repetitions: new_repetitions, ease_factor: new_ease_factor, } } }
Python
UTF-8
548
2.96875
3
[]
no_license
import tkinter as tk from tkinter import Text root = tk.Tk() frame = tk.Frame(root) frame.pack() def show_WIT(): T=Text(root) T.pack() T.insert(tk.END,"This is my CV app") #root.mainloop() def show_AM(): T=Text(root) T.pack() T.insert(tk.END,"I am Miguel Ramos, a Systems Engineer") #root.mainloop() btn_about_me=tk.Button(frame,text='About Me',fg='blue',command = show_AM) btn_what_is_this=tk.Button(frame,text='What is this',fg='green',command=show_WIT) btn_about_me.pack(side=tk.LEFT) btn_what_is_this.pack(side=tk.LEFT) root.mainloop()
JavaScript
UTF-8
1,988
3.90625
4
[]
no_license
// 3.6 Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first // out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at the shelter, // or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of // that type). They cannot select which specific animal they would like. Create the data structures to // maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, // and dequeueCat. You may use the built-in LinkedList data structure. //I like my solution: check l8r function AnimalShelter() { this.dogQueue = new Queue(); this.catQueue = new Queue(); this.count=0 } function dog (name){ this.name = name ; this.serialNumber; } function cat (name){ this.name = name ; this.serialNumber; } AnimalShelter.prototype.enqueue = function(animal) { if (animal typeof dog) { animal.serialNumber=this.count; this.dogQueue.enqueue (animal); this.count++; } if (animal typeof cat) { animal.serialNumber=this.count; this.catQueue.enqueue (animal); this.count++; } }; AnimalShelter.prototype.dequeueAny = function (){ return this.dogQueue.peek().serialNumber < this.catQueue.peek().serialNumber? this.dogQueue.dequeue(): this.catQueue.dequeue(); } function Queue() { this._storage = {}; this._oldestIndex = 1; this._newestIndex = 1; } // Understand why this is being done Queue.prototype.size = function() { return this._newestIndex - this._oldestIndex; } Queue.prototype.enqueue = function(val) { this._storage[this._newestIndex] = data; this._newestIndex++; }; Queue.prototype.dequeue = function() { var oldestIndex = this._oldestIndex; if (this.size()) { var deQ = this._storage[oldestIndex]; delete this._storage[oldestIndex]; this._oldestIndex++; return deQ; } }; Queue.prototype.peek = function (){ return this._storage[oldestIndex]; }
Markdown
UTF-8
2,327
3.5
4
[]
no_license
### Go 的动态类型 https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/11.12.md 在经典的面向对象语言(像 C++,Java 和 C#)中数据和方法被封装为 类 的概念:类包含它们两者,并且不能剥离。 Go 没有类:数据(结构体或更一般的类型)和方法是一种松耦合的正交关系。 Go 中的接口跟 Java/C# 类似:都是必须提供一个指定方法集的实现。但是更加灵活通用:任何提供了接口方法实现代码的类型都隐式地实现了该接口,而不用显式地声明。 和其它语言相比,Go 是唯一结合了接口值,**静态类型检查(是否该类型实现了某个接口)**,运行时动态转换的语言,并且不需要显式地声明类型是否满足某个接口。该特性允许我们在不改变已有的代码的情况下定义和使用新接口。 **Go 的动态类型** **接收一个(或多个)接口类型作为参数的函数,其实参可以是任何实现了该接口的类型的变量。 实现了某个接口的类型可以被传给任何以此接口为参数的函数 。** 静态(编译时期)类型检查 底层具体是怎么做的??? Go通常需要编译器静态检查的支持:当变量被赋值给一个接口类型的变量时,编译器会检查其是否实现了该接口的所有函数。如果方法调用作用于像 interface{} 这样的“泛型”上,你可以通过类型断言(参见 11.3 节)来检查变量是否实现了相应接口。 因此 Go 提供了动态语言的优点,却没有其他动态语言在运行时可能发生错误的缺点。 ### 函数重载 https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/11.12.md 在 6.1 节中, 我们看到函数重载是不被允许的。 在 Go 语言中函数重载可以用可变参数 ...T 作为函数最后一个参数来实现(参见 6.3 节)。如果我们把 T 换为空接口,那么可以知道任何类型的变量都是满足 T (空接口)类型的,这样就允许我们传递任何数量任何类型的参数给函数,即重载的实际含义。 函数 fmt.Printf 就是这样做的: fmt.Printf(format string, a ...interface{}) (n int, errno error) ### 接口继承 https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/11.12.md
C#
UTF-8
4,854
3.4375
3
[]
no_license
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; namespace Task_1 { /*Объявить класс ConsoleSimbol, описывающий символ, расположенный в определённой позиции консольного окна. Поля: simb – символ x – целочисленная координата y – целочисленная координата Для получения значений полей использовать свойства. Инициализация полей выполняется конструктором с параметрами типов char, int, int. Создать наследника ColorConsoleSimbol, у которого есть доп. поле - color (можно string, можно Сolor) В основной программе создать массив состоящий как из ColorConsoleSimbol, так и ConsoleSimbol, со случайными координатами, символами и цветами. Сериализовать и десериализовать массив 2-мя разными типами сериализаций.*/ [Serializable] public class ConsoleSymbol { [XmlIgnore] private char symb; public ConsoleSymbol() { } public ConsoleSymbol(char symbol, int x, int y) { symb = symbol; X = x; Y = y; } public int X { get; set; } public int Y { get; set; } public override string ToString() { return $"X: {X} , Y: {Y}"; } } [Serializable] public class ColorConsoleSymbol : ConsoleSymbol { private Color _color; public ColorConsoleSymbol() { } public ColorConsoleSymbol(char symbol, int x, int y, Color color) : base(symbol, x, y) => _color = color; public override string ToString() => $"Цвет: {_color}"; } internal class Program { private static Random rnd = new Random(); private static void Main(string[] args) { List<Color> listOfColors = new List<Color>() { Color.AliceBlue, Color.IndianRed, Color.AntiqueWhite, Color.Aquamarine, Color.Black, Color.Brown, Color.DarkBlue }; ColorConsoleSymbol[] colorConsole = new ColorConsoleSymbol[10]; List<ConsoleSymbol> listColor = new List<ConsoleSymbol>(); for (int i = 0; i < 10; i++) { var temp = new ColorConsoleSymbol( (char) rnd.Next(97, 123), rnd.Next(1, 100), rnd.Next(1, 50), listOfColors[rnd.Next(1, 7)]); colorConsole[i] = temp; listColor.Add(temp); } var xmlSerialize = new XmlSerializer(typeof(List<ConsoleSymbol>), new[] {typeof(ColorConsoleSymbol)}); using (var fileStreamWriter = new FileStream("Data.xml", FileMode.Create, FileAccess.Write)) { using var streamWriter = new StreamWriter(fileStreamWriter); xmlSerialize.Serialize(streamWriter, listColor); } Console.WriteLine(Environment.NewLine + "XML десереализация: "); using (var fsReader = new FileStream("Data.xml", FileMode.Open, FileAccess.Read)) { using var sReader = new StreamReader(fsReader); var symbolsDeserialize = (List<ConsoleSymbol>)xmlSerialize.Deserialize(sReader); foreach (var p in symbolsDeserialize) { Console.WriteLine($"X: {p.X}, Y: {p.Y}"); Console.WriteLine(p); } } BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream("people.dat", FileMode.OpenOrCreate)) { formatter.Serialize(fs, colorConsole); } Console.WriteLine(Environment.NewLine + "Бинарная десереализация: "); using (FileStream fs = new FileStream("people.dat", FileMode.OpenOrCreate)) { ColorConsoleSymbol[] deserilizePeople = (ColorConsoleSymbol[])formatter.Deserialize(fs); foreach (var p in deserilizePeople) { Console.WriteLine($"X: {p.X}, Y: {p.Y}"); Console.WriteLine(p); } } } } }
Java
UTF-8
1,448
2.109375
2
[]
no_license
package com.ceiba.cliente.adaptador.dao; import java.util.List; import com.ceiba.cliente.modelo.dto.DtoCliente; import com.ceiba.cliente.puerto.dao.DaoCliente; import com.ceiba.infraestructura.jdbc.CustomNamedParameterJdbcTemplate; import com.ceiba.infraestructura.jdbc.sqlstatement.SqlStatement; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Component; @Component public class DaoClienteMysql implements DaoCliente { private final CustomNamedParameterJdbcTemplate customNamedParameterJdbcTemplate; @SqlStatement(namespace="cliente", value="listar") private static String sqlListar; @SqlStatement(namespace="cliente", value="obtener") private static String sqlObtener; public DaoClienteMysql(CustomNamedParameterJdbcTemplate customNamedParameterJdbcTemplate) { this.customNamedParameterJdbcTemplate = customNamedParameterJdbcTemplate; } @Override public List<DtoCliente> listar() { return this.customNamedParameterJdbcTemplate.getNamedParameterJdbcTemplate().query(sqlListar, new MapeoCliente()); } @Override public DtoCliente obtener(Long id) { MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("id", id); return this.customNamedParameterJdbcTemplate.getNamedParameterJdbcTemplate().query(sqlObtener, paramSource, new MapeoCliente()).iterator().next(); } }
JavaScript
UTF-8
467
2.546875
3
[]
no_license
class SlingShot { constructor(body1,body2){ var options = { bodyA : body1, bodyB : body2, stiffness : 0.04, length : 10 } this.sling = Constraint.create(options) World.add(world,this.sling) } display(){ strokeWeight(4) line(this.sling.bodyA.position.x,this.sling.bodyA.position.y,this.sling.bodyB.position.x,this.sling.bodyB.position.y) } }
PHP
UTF-8
1,640
3.015625
3
[]
no_license
<?php /** * MiniLibLBC BadPinkChicken */ class LBCRequest { public $url; public $options; private $page_content; private $content_tab; private $parsed_content; function __construct($url, $options) { // Options -> Array -> "date", "title", "price", "place" ,"image" $this->url = $url; $this->options = $options; } function parseRequest() { $this->page_content = file_get_contents($this->url); $this->content_tab = explode(PHP_EOL, $this->page_content); $i=0; if (isset($this->parsed_content)) unset($this->parsed_content); while (!strstr($this->content_tab[$i], '<div class="list-lbc">')) $i++; while(!strstr($this->content_tab[$i], '<div class="list-gallery">')) { if (strstr($this->content_tab[$i], "date") && !in_array("date", $this->options)) $i = $i + 4; else if (strstr($this->content_tab[$i], "image") && !in_array("image", $this->options)) $i = $i + 16; else if (strstr($this->content_tab[$i], "title") &&!in_array("title", $this->options)) $i++; else if (strstr($this->content_tab[$i], "category") && !in_array("category", $this->options)) $i++; else if (strstr($this->content_tab[$i], "placement") && !in_array("place", $this->options)) $i++; else if (strstr($this->content_tab[$i], "price") && !in_array("price", $this->options)) $i++; else { $this->parsed_content .= $this->content_tab[$i]; $i++; } } return $this->parsed_content; } } ?>
Java
UTF-8
539
2.359375
2
[]
no_license
package postgstats.websocketserver; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.group.ChannelGroup; class JoinGroupHandler extends ChannelInboundHandlerAdapter { private final ChannelGroup channelGroup; JoinGroupHandler(ChannelGroup channelGroup) { this.channelGroup = channelGroup; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channelGroup.add(ctx.channel()); super.channelActive(ctx); } }
C#
UTF-8
1,137
2.875
3
[ "MIT" ]
permissive
 namespace System.Extensions.Http { using System.Text; using System.Threading.Tasks; [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class ReadJsonAttribute : Attribute { #region private private static int _MaxLength = 2 << 20;//2M private int _maxLength; #endregion public ReadJsonAttribute() { _maxLength = _MaxLength; } public ReadJsonAttribute(int maxLength) { _maxLength = maxLength; } public async Task<object> ReadAsync<T>(HttpRequest request) { if (request == null) return null; //TODO? ContentType var encoding = FeaturesExtensions.GetEncoding(request) ?? Encoding.UTF8; var content = request.Content.AsBounded(_maxLength); //try //{ //} //catch //{ // return null; //} return await content.ReadJsonAsync<T>(encoding); } } }
C#
UTF-8
9,986
2.921875
3
[]
no_license
using System; namespace Com.ChinaSoft.DataAcquisition { /// <summary> /// Connection Builder class handles connecting and disconnecting from the Historian. Use this library as /// an example on how to establish a connection with Historian 11 /// </summary> public class ConnectionBuilder { #region --Variables-- private ArchestrA.HistorianAccessError mLastError; private ArchestrA.HistorianConnectionStatus mStatus; private ArchestrA.HistorianAccess mHistorianAccess; private System.Threading.Thread connectionthread; /// <summary> /// Historian Connection Arguments. You can set this directly prior to calling the Connect function /// </summary> public ArchestrA.HistorianConnectionArgs HistorianConnection = new ArchestrA.HistorianConnectionArgs(); /// <summary> /// Provides the last error from performing historian operations. /// </summary> public ArchestrA.HistorianAccessError LastError { get { return mLastError; } } /// <summary> /// Provides the status of the Historian connection /// </summary> public ArchestrA.HistorianConnectionStatus Status { get { return mStatus; } } /// <summary> /// Provides the currect connection object. /// </summary> public ArchestrA.HistorianAccess HistorianAccess => mHistorianAccess; /// <summary> /// Connection attempts provides the number of times the connectionbuilder will try to check the status of the connection. /// This actaully is not necessary because the Historian will automatically connect after calling the OpenConnection command. /// </summary> public int ConnectionAttempts = 10; #endregion /// <summary> /// Constructor /// </summary> public ConnectionBuilder() { HistorianConnection = new ArchestrA.HistorianConnectionArgs(); mHistorianAccess = new ArchestrA.HistorianAccess(); } /// <summary> /// Connect function will try to establish a connection with the historian using current HistorianConnection arguments /// </summary> /// <returns>Returns the connection status after having tried the connection attempts.</returns> public ArchestrA.HistorianConnectionStatus Connect() { mStatus = new ArchestrA.HistorianConnectionStatus(); mLastError = null; //It takes several seconds before a connection is established. You can use a for loop and wait //or you can just continue the operation of adding tags and storing data in offline mode. Once a connection is //established, any tags you have added or stored will automatically be synchronized with the historian. if (HistorianAccess.OpenConnection(HistorianConnection, out mLastError)) { for (int i = 0; i < ConnectionAttempts; i++) { HistorianAccess.GetConnectionStatus(ref mStatus); if (Status.ConnectedToServer) { return Status; } System.Threading.Thread.Sleep(1000); } } else { return null; } return Status; } /// <summary> /// Connect function for async thread. Will continue to monitor connection /// </summary> public void ConnectAsyncThreadFunc() { mStatus = new ArchestrA.HistorianConnectionStatus(); mLastError = null; //We will open connection then continue to monitor status if (HistorianAccess.OpenConnection(HistorianConnection, out mLastError)) { while (true) { HistorianAccess.GetConnectionStatus(ref mStatus); UpdateStatus(mStatus); System.Threading.Thread.Sleep(5000); } } else { UpdateStatus(null); } } /// <summary> /// Connect function will try to establish a connection with the historian. Minimum parameters are passed to the connection arguments. /// </summary> /// <param name="MinStoreForwardDuration">Minimum time client remains in storeforward after a disconnect</param> /// <param name="Password">Windows Authenticated password for the Historian</param> /// <param name="ReadOnly">Readonly disables ability to addtags or store. Set to false if you need to store values.</param> /// <param name="ServerName">Historian's server name</param> /// <param name="StoreForwardFreeDiskSpace">Minimum disk space before storeforward starts to delete the oldest block</param> /// <param name="StoreForwardPath">Path of the storeforward directory. This must be unique to each connection if the historian is the same.</param> /// <param name="TcpPort">WCF port to connect to. This is the same port that is seen in the parameters section of the SMC on the historian</param> /// <param name="UserName">Windows Authenticated username for the Historian</param> /// <returns>Returns the connection status after having tried the connection attempts.</returns> public ArchestrA.HistorianConnectionStatus Connect(uint MinStoreForwardDuration, String Password, Boolean ReadOnly, String ServerName, uint StoreForwardFreeDiskSpace, String StoreForwardPath, ushort TcpPort, String UserName) { //Set connection arguments prior to connecting. HistorianConnection.MinStoreForwardDuration = MinStoreForwardDuration; HistorianConnection.Password = Password; HistorianConnection.ReadOnly = ReadOnly; HistorianConnection.ServerName = ServerName; HistorianConnection.StoreForwardFreeDiskSpace = StoreForwardFreeDiskSpace; HistorianConnection.StoreForwardPath = StoreForwardPath; HistorianConnection.TcpPort = TcpPort; HistorianConnection.UserName = UserName; return Connect(); } /// <summary> /// Connect function will try to establish a connection with the historian asynchronously. Minimum parameters are passed to the connection arguments. /// </summary> /// <param name="MinStoreForwardDuration">Minimum time client remains in storeforward after a disconnect</param> /// <param name="Password">Windows Authenticated password for the Historian</param> /// <param name="ReadOnly">Readonly disables ability to addtags or store. Set to false if you need to store values.</param> /// <param name="ServerName">Historian's server name</param> /// <param name="StoreForwardFreeDiskSpace">Minimum disk space before storeforward starts to delete the oldest block</param> /// <param name="StoreForwardPath">Path of the storeforward directory. This must be unique to each connection if the historian is the same.</param> /// <param name="TcpPort">WCF port to connect to. This is the same port that is seen in the parameters section of the SMC on the historian</param> /// <param name="UserName">Windows Authenticated username for the Historian</param> public void ConnectAsync(uint MinStoreForwardDuration, String Password, Boolean ReadOnly, String ServerName, uint StoreForwardFreeDiskSpace, String StoreForwardPath, ushort TcpPort, String UserName) { //Set connection arguments prior to connecting. HistorianConnection.MinStoreForwardDuration = MinStoreForwardDuration; HistorianConnection.Password = Password; HistorianConnection.ReadOnly = ReadOnly; HistorianConnection.ServerName = ServerName; HistorianConnection.StoreForwardFreeDiskSpace = StoreForwardFreeDiskSpace; HistorianConnection.StoreForwardPath = StoreForwardPath; HistorianConnection.TcpPort = TcpPort; HistorianConnection.UserName = UserName; connectionthread = new System.Threading.Thread(ConnectAsyncThreadFunc) { IsBackground = true }; connectionthread.Start(); } /// <summary> /// UpdateStatus event updates the status of Historian connection /// </summary> public event ConnectionStatusChanged UpdateStatus; public delegate void ConnectionStatusChanged(ArchestrA.HistorianConnectionStatus status); /// <summary> /// Disconnect from the Historian /// </summary> public void Disconnect() { if (connectionthread != null) connectionthread.Abort(); mLastError = null; mHistorianAccess.CloseConnection(out mLastError); } } }
Markdown
UTF-8
2,198
3.375
3
[]
no_license
## Section List Adapter ## I based this project off of the [Amazing-ListView][1]. The work is fairly divergent at this point, but some of the basic techniques are used from that implementation. *Note: Still working on the documentation and a sticky header implementation* This project was created to make a simpler and easier version of a sectioned ListView. I found several examples that were entirely to complicated to implement. All you need to do is extend `SectionListAdapter` in your own adapter and implement the following **two** (You read that correct only **TWO** methods !!!!!) methods: View getHeaderView(Section section, View convertView, View parent) View getItemView(Item item, View convertView, View parent); You may notice that these are similar to the getView(int position, View convertView, View parent) method in the `Adapter` interface. You can use them just as you did in a normal `getView()` implementation. The main difference is that you do not need to be worried about the position of the Item or Header that is being called. That is handled by the super class. You will have an easier time with just the Item and not the index. The reason for not having to worry about the item index is because of how the super class in implemented. The `SectionListAdapter` has a special constructor: SectionListAdapter(Map<Section, List<Item>> items, Context context) you **MUST** call the `super()` constructor in your subclass. The `Map` is really critical to how the `Adapter` works. This is why you get to only worry about the item and not the index. The class uses two generic types. The `Section` is the Object that represent the section object that will be used as the header for that section. The `Item` is a item in the `ListView` that will be displayed. The type of `Map` that you use will determine the order that the sections are displayed. I suggest using the `LinkedHashMap` if you want to perserve insertion order for the sections. You will have to break up your items into separate `List`s and insert them into the map with the `Section` object as the key. [1]: http://code.google.com/p/android-amazing-listview/
Java
UTF-8
3,254
2.15625
2
[]
no_license
package com.example.nthucs.prototype.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import com.example.nthucs.prototype.R; /** * Created by user on 2016/9/24. */ public class DisplayAsMetricImperialActivity extends AppCompatActivity { private SharedPreferences sharedPreferences; // Back button private Button backButton; private RadioButton metric; private RadioButton imperial; private RadioGroup rgroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_as_metric_imperial); // custom view in action bar getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.display_as_metric_imperial_menu); // process back button processBackControllers(); init(); rgroup.setOnCheckedChangeListener(listener); } @Override protected void onResume() { super.onResume(); } // process back button listener private void processBackControllers() { // initialize back button backButton = (Button)findViewById(R.id.back_button); // avoid all upper case backButton.setTransformationMethod(null); // set button listener backButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent back = new Intent(); back.setClass(DisplayAsMetricImperialActivity.this, SettingsActivity.class); startActivity(back); finish(); // origin activity slide to right, new activity slide from left overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } }); } private void init(){ sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); rgroup = (RadioGroup) findViewById(R.id.rgroup); metric = (RadioButton) findViewById(R.id.unit2metric); imperial = (RadioButton) findViewById(R.id.unit2imperial); int radioId = sharedPreferences.getInt("checkedIndex",0); if(radioId!=0){ RadioButton rbtn=(RadioButton) findViewById(radioId); rbtn.setChecked(true); } } private RadioGroup.OnCheckedChangeListener listener = new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { sharedPreferences.edit().putInt("checkedIndex", i).apply(); switch (i){ case R.id.unit2metric: MainActivity.metricFlag = true; break; case R.id.unit2imperial: MainActivity.metricFlag = false; break; } } }; }
Python
UTF-8
5,851
2.71875
3
[]
no_license
from PIL import Image, ImageFilter, ImageOps, ImageChops, ImageEnhance from abc import abstractmethod, ABC import numpy from Dataset import Entry, Split class Transformation: def __init__(self, func, name, origin, keys): self._func = func self._name = name self._origin = origin self._keys = keys @property def keys(self): return self._keys @property def func(self): return self._func @property def name(self): return self._name @property def origin(self): return self._origin def apply(self, entry): return self._func(entry) class Transformer: def __init__(self): self._transformations = [] self._Transformation = Transformation self._Entry = Entry def __str__(self): info = [] separator = '\n' for transformation in self.transformations: info.append('Transformation - Name: {0}, Origin: {1}'.format(transformation.name, transformation.origin)) info = separator.join(info) return info def __iter__(self): return iter(self._transformations) @property def transformations(self): return self._transformations @property def n_transformations(self): return len(self._transformations) def transform(self, origin): raise NotImplementedError class ImageTransformer(Transformer): def __init__(self, image_size=None): super(ImageTransformer, self).__init__() self._image_size = image_size self._split_transformations = None @property def image_size(self): return self._image_size @staticmethod def _sample2object(sample): return Image.open(sample) @staticmethod def _img2aray(img): return numpy.asarray(img, dtype=numpy.uint8) def _expand_labels(self, label, n_copies): return numpy.array([label for _ in range(n_copies)]) def build_transformations(self, split: Split): self._split_transformations = [transformation for transformation in self._transformations if split.spec.key in transformation.keys] def transform(self, entry: Entry): sample = self._sample2object(entry.sample) transformed = [] for transformation in self._split_transformations: img = transformation.apply(sample) if transformation.origin is True: sample = img else: transformed.append(img) transformed.append(sample) labels = self._expand_labels(entry.label, len(transformed)) entries = [Entry(sample=self._img2aray(img), label=label) for img, label in zip(transformed, labels)] return entries def add_unsharp_masking(self, keys, radius=2, scale=1, origin=False): name ='unsharp_masking' def unsharp_masking(img, rad=radius, sc=scale): gauss_img = img.filter(ImageFilter.GaussianBlur(radius=rad)) return ImageChops.add(img, ImageChops.subtract(img, gauss_img, scale=sc)) transformation = self._Transformation(unsharp_masking, name, origin, keys) self._transformations.append(transformation) def add_histogram_equalization(self, keys, origin=False): name = 'histogram_equalization' transformation = self._Transformation(ImageOps.equalize, name, origin, keys) self._transformations.append(transformation) def add_median_filter(self, keys, size=3, origin=False): name = 'median_filter' def median_filter(img): return img.filter(ImageFilter.MedianFilter(size=size)) transformation = self._Transformation(median_filter, name, origin, keys) self._transformations.append(transformation) def add_resize(self, size, keys, origin=False): self._image_size = size name = 'resize' def resize(img, s=size): return img.resize(s) transformation = self._Transformation(resize, name, origin, keys) self._transformations.append(transformation) def add_grayscale(self, keys, origin=False): name = 'grayscale' def grayscale(img): return img.convert('L') transformation = self._Transformation(grayscale, name, origin, keys) self._transformations.append(transformation) def add_rotation(self, angles, keys, origin=False): name = 'rotation' for angle in angles: def rotate(img, angl=angle): return img.rotate(angl) transformation = self._Transformation(rotate, name, origin, keys) self._transformations.append(transformation) def add_brightening(self, brightnesses, keys, origin=False): name = 'brightening' for brightness in brightnesses: def brighten(img, br=brightness): return ImageEnhance.Brightness(img).enhance(br) transformation = self._Transformation(brighten, name, origin, keys) self._transformations.append(transformation) def add_contrast(self, contrasts, keys, origin=False): name = 'contrast' for contrast in contrasts: def contrasting(img, con=contrast): return ImageEnhance.Contrast(img).enhance(con) transformation = self._Transformation(contrasting, name, origin, keys) self._transformations.append(transformation) def add_sharpening(self, sharpenings, keys, origin=False): name = 'sharpen' for sharpening in sharpenings: def sharpen(img, sh=sharpening): return ImageEnhance.Contrast(img).enhance(sh) transformation = self._Transformation(sharpen, name, origin, keys) self._transformations.append(transformation)
Markdown
UTF-8
21,684
3.625
4
[]
no_license
# 声明文件 - 当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。 - 在了解声明文件之前,需要先了解什么是**声明语句** ## 什么是声明语句 - 假如我们想使用第三方库 jQuery,一种常见的方式是在 html 中通过 `<script>` 标签引入 jQuery,然后就可以使用全局变量 `$` 或 `jQuery` 了。 - 我们通常这样获取一个 `id` 是 `foo` 的元素: ~~~typescript $('#foo'); // or jQuery('#foo'); ~~~ - 但是在 ts 中,编译器并不知道 `$` 或 `jQuery` 是什么东西 ~~~ jQuery('#foo'); // ERROR: Cannot find name 'jQuery'. ~~~ - 这时,我们需要使用 `declare var` 来定义它的类型[2](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/02-declare-var): ~~~typescript declare var jQuery: (selector: string) => any; jQuery('#foo'); ~~~ - 上例中,`declare var` 并没有真的定义一个变量,只是定义了全局变量 `jQuery` 的类型,仅仅会用于编译时的检查,在编译结果中会被删除。它编译结果是: ~~~ jQuery('#foo'); ~~~ - 除了 `declare var` 之外,还有其他很多种声明语句,将会在后面详细介绍。 ## 什么是声明文件 - **通常我们会把声明语句放到一个单独的文件(`jQuery.d.ts`)中,这就是声明文件[3](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/03-jquery-d-ts)** ~~~ // src/jQuery.d.ts declare var jQuery: (selector: string) => any; ~~~ ~~~ // src/index.ts jQuery('#foo'); ~~~ - 声明文件必需以 `.d.ts` 为后缀。 - 一般来说,ts 会解析项目中所有的 `.ts` 文件,当然也包含以 `.d.ts` 结尾的文件。所以当我们将 `jQuery.d.ts` 放到项目中时,其他所有 `*.ts` 文件就都可以获得 `jQuery` 的类型定义了。 ~~~ /path/to/project ├── src | ├── index.ts | └── jQuery.d.ts └── tsconfig.json ~~~ - 假如仍然无法解析,那么可以检查下 `tsconfig.json` 中的 `files`、`include` 和 `exclude` 配置,确保其包含了 `jQuery.d.ts` 文件。 - 这里只演示了全局变量这种模式的声明文件,假如是通过模块导入的方式使用第三方库的话,那么引入声明文件又是另一种方式了,将会在后面详细介绍。 ## 第三方声明文件 - 当然,jQuery 的声明文件不需要我们定义了,推荐的是使用 `@types` 统一管理第三方库的声明文件。 `@types` 的使用方式很简单,直接用 npm 安装对应的声明模块即可,以 jQuery 举例: ~~~ npm install @types/jquery --save-dev ~~~ - 可以在[这个页面](https://microsoft.github.io/TypeSearch/)搜索你需要的声明文件。 ## 书写声明文件 - 当一个第三方库没有提供声明文件时,我们就需要自己书写声明文件了。前面只介绍了最简单的声明文件内容,而真正书写一个声明文件并不是一件简单的事,以下会详细介绍如何书写声明文件。 - 在不同的场景下,声明文件的内容和使用方式会有所区别。 - 库的使用场景主要有以下几种: - [全局变量]():通过 `<script>` 标签引入第三方库,注入全局变量 - [npm 包]():通过 `import foo from 'foo'` 导入,符合 ES6 模块规范 - [UMD 库]():既可以通过 `<script>` 标签引入,又可以通过 `import` 导入 - [直接扩展全局变量]():通过 `<script>` 标签引入后,改变一个全局变量的结构 - [在 npm 包或 UMD 库中扩展全局变量]():引用 npm 包或 UMD 库后,改变一个全局变量的结构 - [模块插件]():通过 `<script>` 或 `import` 导入后,改变另一个模块的结构 ### 全局变量 - 全局变量是最简单的一种场景,之前举的例子就是通过 `<script>` 标签引入 jQuery,注入全局变量 `$` 和 `jQuery`。 - 使用全局变量的声明文件时,如果是以 `npm install @types/xxx --save-dev` 安装的,则不需要任何配置。如果是将声明文件直接存放于当前项目中,则建议和其他源码一起放到 `src` 目录下(或者对应的源码目录下): ~~~ /path/to/project ├── src | ├── index.ts | └── jQuery.d.ts └── tsconfig.json ~~~ - 如果没有生效,可以检查下 `tsconfig.json` 中的 `files`、`include` 和 `exclude` 配置,确保其包含了 `jQuery.d.ts` 文件。 - 全局变量的声明文件主要有以下几种语法: - [`declare var`]() 声明全局变量 - [`declare function`]() 声明全局方法 - [`declare class`]() 声明全局类 - [`declare enum`]() 声明全局枚举类型 - [`declare namespace`]() 声明(含有子属性的)全局对象 - [`interface` 和 `type`]() 声明全局类型 #### declare var - 在所有的声明语句中,`declare var` 是最简单的,如之前所学,它能够用来定义一个全局变量的类型。与其类似的,还有 `declare let` 和 `declare const`,使用 `let` 与使用 `var` 没有什么区别: ~~~typescript // src/jQuery.d.ts declare let jQuery: (selector: string) => any; ~~~ ~~~typescript // src/index.ts jQuery('#foo'); // 使用 declare let 定义的 jQuery 类型,允许修改这个全局变量 jQuery = function(selector) { return document.querySelector(selector); }; ~~~ - 而当我们使用 `const` 定义时,表示此时的全局变量是一个常量,不允许再去修改它的值了 ~~~typescript // src/jQuery.d.ts declare const jQuery: (selector: string) => any; jQuery('#foo'); // 使用 declare const 定义的 jQuery 类型,禁止修改这个全局变量 jQuery = function(selector) { return document.querySelector(selector); }; // ERROR: Cannot assign to 'jQuery' because it is a constant or a read-only property. ~~~ - 一般来说,全局变量都是禁止修改的常量,所以大部分情况都应该使用 `const` 而不是 `var` 或 `let` 。 - 需要注意的是,声明语句中只能定义类型,切勿在声明语句中定义具体的实现 ~~~typescript declare const jQuery = function(selector) { return document.querySelector(selector); }; // ERROR: An implementation cannot be declared in ambient contexts. ~~~ #### declare function - `declare function` 用来定义全局函数的类型。jQuery 其实就是一个函数,所以也可以用 `function` 来定义: ~~~typescript // src/jQuery.d.ts declare function jQuery(selector: string): any; ~~~ ~~~typescript // src/index.ts jQuery('#foo'); ~~~ - **在函数类型的声明语句中,函数重载也是支持的** ~~~typescript // src/jQuery.d.ts declare function jQuery(selector: string): any; declare function jQuery(domReadyCallback: () => any): any; ~~~ ~~~typescript // src/index.ts jQuery('#foo'); jQuery(function() { alert('Dom Ready!'); }); ~~~ #### declare class - 当全局变量是一个类的时候,我们用 `declare class` 来定义它的类型 ~~~typescript // src/Animal.d.ts declare class Animal { name: string; constructor(name: string); sayHi(): string; } ~~~ ~~~typescript // src/index.ts let cat = new Animal('Tom'); ~~~ - 同样的,`declare class` 语句也只能用来定义类型,不能用来定义具体的实现,比如定义 `sayHi` 方法的具体实现则会报错: ~~~typescript // src/Animal.d.ts declare class Animal { name: string; constructor(name: string); sayHi() { return `My name is ${this.name}`; }; // ERROR: An implementation cannot be declared in ambient contexts. } ~~~ #### declare enum - 使用 `declare enum` 定义的枚举类型也称作外部枚举(Ambient Enums),举例如下 ~~~typescript // src/Directions.d.ts declare enum Directions { Up, Down, Left, Right } ~~~ ~~~typescript // src/index.ts let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]; ~~~ - 与其他全局变量的类型声明一致,`declare enum` 仅用来定义类型,而不是具体的值。 - `Directions.d.ts` 仅仅会用于编译时的检查,声明文件里的内容在编译结果中会被删除。它编译结果是: ~~~ var directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]; ~~~ - 其中 `Directions` 是由第三方库定义好的全局变量。 #### declare namespace - `namespace` 是 ts 早期时为了解决模块化而创造的关键字,中文称为命名空间。 - 由于历史遗留原因,在早期还没有 ES6 的时候,ts 提供了一种模块化方案,使用 `module` 关键字表示内部模块。但由于后来 ES6 也使用了 `module` 关键字,ts 为了兼容 ES6,使用 `namespace` 替代了自己的 `module`,更名为命名空间。 - 随着 ES6 的广泛应用,现在已经不建议再使用 ts 中的 `namespace`,而推荐使用 ES6 的模块化方案了,故我们不再需要学习 `namespace` 的使用了。 - `namespace` 被淘汰了,但是在声明文件中,`declare namespace` 还是比较常用的,它用来表示全局变量是一个对象,包含很多子属性。 - 比如 `jQuery` 是一个全局变量,它是一个对象,提供了一个 `jQuery.ajax` 方法可以调用,那么我们就应该使用 `declare namespace jQuery` 来声明这个拥有多个子属性的全局变量。 ~~~ // src/jQuery.d.ts declare namespace jQuery { function ajax(url: string, settings?: any): void; } ~~~ ~~~ // src/index.ts jQuery.ajax('/api/get_something'); ~~~ - 注意,在 `declare namespace` 内部,我们直接使用 `function ajax` 来声明函数,而不是使用 `declare function ajax`。类似的,也可以使用 `const`, `class`, `enum` 等语句 ~~~typescript // src/jQuery.d.ts declare namespace jQuery { function ajax(url: string, settings?: any): void; const version: number; class Event { blur(eventType: EventType): void } enum EventType { CustomClick } } ~~~ ~~~typescript // src/index.ts jQuery.ajax('/api/get_something'); console.log(jQuery.version); const e = new jQuery.Event(); e.blur(jQuery.EventType.CustomClick); ~~~ ##### 嵌套的命名空间 - 如果对象拥有深层的层级,则需要用嵌套的 `namespace` 来声明深层的属性的类型 ~~~typescript // src/jQuery.d.ts declare namespace jQuery { function ajax(url: string, settings?: any): void; namespace fn { function extend(object: any): void; } } ~~~ ~~~typescript // src/index.ts jQuery.ajax('/api/get_something'); jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); } }); ~~~ - 假如 `jQuery` 下仅有 `fn` 这一个属性(没有 `ajax` 等其他属性或方法),则可以不需要嵌套 `namespace` ~~~typescript // src/jQuery.d.ts declare namespace jQuery.fn { function extend(object: any): void; } ~~~ ~~~typescript // src/index.ts jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); } }); ~~~ #### interface和 type - 除了全局变量之外,可能有一些类型我们也希望能暴露出来。在类型声明文件中,我们可以直接使用 `interface` 或 `type` 来声明一个全局的接口或类型 ~~~typescript // src/jQuery.d.ts interface AjaxSettings { method?: 'GET' | 'POST' data?: any; } declare namespace jQuery { function ajax(url: string, settings?: AjaxSettings): void; } ~~~ - 这样的话,在其他文件中也可以使用这个接口或类型了 ~~~typescript // src/index.ts let settings: AjaxSettings = { method: 'POST', data: { name: 'foo' } }; jQuery.ajax('/api/post_something', settings); ~~~ - `type` 与 `interface` 类似,不再赘述。 #### 防止命名冲突 - 暴露在最外层的 `interface` 或 `type` 会作为全局类型作用于整个项目中,我们应该尽可能的减少全局变量或全局类型的数量。故最好将他们放到 `namespace` 下: ~~~typescript // src/jQuery.d.ts declare namespace jQuery { interface AjaxSettings { method?: 'GET' | 'POST' data?: any; } function ajax(url: string, settings?: AjaxSettings): void; } ~~~ - 注意,在使用这个 `interface` 的时候,也应该加上 `jQuery` 前缀: ~~~typescript // src/index.ts let settings: jQuery.AjaxSettings = { method: 'POST', data: { name: 'foo' } }; jQuery.ajax('/api/post_something', settings); ~~~ #### 声明合并 - 假如 jQuery 既是一个函数,可以直接被调用 `jQuery('#foo')`,又是一个对象,拥有子属性 `jQuery.ajax()`(事实确实如此),那么我们可以组合多个声明语句,它们会不冲突的合并起来 ~~~typescript // src/jQuery.d.ts declare function jQuery(selector: string): any; declare namespace jQuery { function ajax(url: string, settings?: any): void; } ~~~ ~~~typescript // src/index.ts jQuery('#foo'); jQuery.ajax('/api/get_something'); ~~~ - 关于声明合并的更多用法,可以查看[声明合并]()章节。 ### npm 包 - 一般我们通过 `import foo from 'foo'` 导入一个 npm 包,这是符合 ES6 模块规范的。 - 在我们尝试给一个 npm 包创建声明文件之前,需要先看看它的声明文件是否已经存在。一般来说,npm 包的声明文件可能存在于两个地方: 1. 与该 npm 包绑定在一起。判断依据是 `package.json` 中有 `types` 字段,或者有一个 `index.d.ts` 声明文件。这种模式不需要额外安装其他包,是最为推荐的,所以以后我们自己创建 npm 包的时候,最好也将声明文件与 npm 包绑定在一起。 2. 发布到 `@types` 里。我们只需要尝试安装一下对应的 `@types` 包就知道是否存在该声明文件,安装命令是 `npm install @types/foo --save-dev`。这种模式一般是由于 npm 包的维护者没有提供声明文件,所以只能由其他人将声明文件发布到 `@types` 里了。 - 假如以上两种方式都没有找到对应的声明文件,那么我们就需要自己为它写声明文件了。由于是通过 `import` 语句导入的模块,所以声明文件存放的位置也有所约束,一般有两种方案: 1. 创建一个 `node_modules/@types/foo/index.d.ts` 文件,存放 `foo` 模块的声明文件。这种方式不需要额外的配置,但是 `node_modules` 目录不稳定,代码也没有被保存到仓库中,无法回溯版本,有不小心被删除的风险,故不太建议用这种方案,一般只用作临时测试。 2. 创建一个 `types` 目录,专门用来管理自己写的声明文件,将 `foo` 的声明文件放到 `types/foo/index.d.ts` 中。这种方式需要配置下 `tsconfig.json` 中的 `paths` 和 `baseUrl` 字段。 目录结构: ~~~ /path/to/project ├── src | └── index.ts ├── types | └── foo | └── index.d.ts └── tsconfig.json ~~~ `tsconfig.json` 内容: ~~~ { "compilerOptions": { "module": "commonjs", "baseUrl": "./", "paths": { "*": ["types/*"] } } } ~~~ - 如此配置之后,通过 `import` 导入 `foo` 的时候,也会去 `types` 目录下寻找对应的模块的声明文件了 - 注意 `module` 配置可以有很多种选项,不同的选项会影响模块的导入导出模式。这里我们使用了 `commonjs` 这个最常用的选项,后面的教程也都默认使用的这个选项。 - npm 包的声明文件主要有以下几种语法: #### export - npm 包的声明文件与全局变量的声明文件有很大区别。在 npm 包的声明文件中,使用 `declare` 不再会声明一个全局变量,而只会在当前文件中声明一个局部变量。只有在声明文件中使用 `export` 导出,然后在使用方 `import` 导入后,才会应用到这些类型声明。 - `export` 的语法与普通的 ts 中的语法类似,区别仅在于声明文件中禁止定义具体的实现 ~~~typescript // types/foo/index.d.ts export const name: string; export function getName(): string; export class Animal { constructor(name: string); sayHi(): string; } export enum Directions { Up, Down, Left, Right } export interface Options { data: any; } ~~~ - 对应的导入和使用模块应该是这样: ~~~typescript // src/index.ts import { name, getName, Animal, Directions, Options } from 'foo'; console.log(name); let myName = getName(); let cat = new Animal('Tom'); let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]; let options: Options = { data: { name: 'foo' } }; ~~~ #### **混用 declare 和 export** - 我们也可以使用 `declare` 先声明多个变量,最后再用 `export` 一次性导出。上例的声明文件可以等价的改写为[16](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/16-declare-and-export): ~~~typescript // types/foo/index.d.ts declare const name: string; declare function getName(): string; declare class Animal { constructor(name: string); sayHi(): string; } declare enum Directions { Up, Down, Left, Right } interface Options { data: any; } export { name, getName, Animal, Directions, Options }; ~~~ - 注意,与全局变量的声明文件类似,`interface` 前是不需要 `declare` 的。 #### export namespace - 与 `declare namespace` 类似,`export namespace` 用来导出一个拥有子属性的对象[17](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/17-export-namespace): ~~~typescript // types/foo/index.d.ts export namespace foo { const name: string; namespace bar { function baz(): string; } } ~~~ ~~~typescript // src/index.ts import { foo } from 'foo'; console.log(foo.name); foo.bar.baz(); ~~~ #### export default - 在 ES6 模块系统中,使用 `export default` 可以导出一个默认值,使用方可以用 `import foo from 'foo'` 而不是 `import { foo } from 'foo'` 来导入这个默认值。 - 在类型声明文件中,`export default` 用来导出默认值的类型[18](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/18-export-default): ~~~ // types/foo/index.d.ts export default function foo(): string; ~~~ ~~~ // src/index.ts import foo from 'foo'; foo(); ~~~ - 注意,只有 `function`、`class` 和 `interface` 可以直接默认导出,其他的变量需要先定义出来,再默认导出[19](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/19-export-default-enum-error): ~~~typescript // types/foo/index.d.ts export default enum Directions { // ERROR: Expression expected. Up, Down, Left, Right } ~~~ - 上例中 `export default enum` 是错误的语法,需要使用 `declare enum` 定义出来,然后使用 `export default` 导出: ~~~typescript // types/foo/index.d.ts declare enum Directions { Up, Down, Left, Right } export default Directions; ~~~ - 针对这种默认导出,我们一般会将导出语句放在整个声明文件的最前面[20](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/20-export-default-enum): ~~~typescript // types/foo/index.d.ts export default Directions; declare enum Directions { Up, Down, Left, Right } ~~~ #### export = - 在 commonjs 规范中,我们用以下方式来导出一个模块: ~~~ // 整体导出 module.exports = foo; // 单个导出 exports.bar = bar; ~~~ - 在 ts 中,针对这种模块导出,有多种方式可以导入,第一种方式是 `const ... = require`: ~~~ // 整体导入 const foo = require('foo'); // 单个导入 const bar = require('foo').bar; ~~~ - 第二种方式是 `import ... from`,注意针对整体导出,需要使用 `import * as` 来导入: ~~~ // 整体导入 import * as foo from 'foo'; // 单个导入 import { bar } from 'foo'; ~~~ - 第三种方式是 `import ... require`,这也是 ts 官方推荐的方式: ~~~ // 整体导入 import foo = require('foo'); // 单个导入 import bar = foo.bar; ~~~ - 对于这种使用 commonjs 规范的库,假如要为它写类型声明文件的话,就需要使用到 `export =` 这种语法了[21](https://github.com/xcatliu/typescript-tutorial/tree/master/examples/declaration-files/21-export-equal): ~~~ // types/foo/index.d.ts export = foo; declare function foo(): string; declare namespace foo { const bar: number; } ~~~ - 需要注意的是,上例中使用了 `export =` 之后,就不能再单个导出 `export { bar }` 了。所以我们通过声明合并,使用 `declare namespace foo` 来将 `bar` 合并到 `foo` 里。 - 准确地讲,`export =` 不仅可以用在声明文件中,也可以用在普通的 ts 文件中。实际上,`import ... require` 和 `export =` 都是 ts 为了兼容 AMD 规范和 commonjs 规范而创立的新语法,由于并不常用也不推荐使用,所以这里就不详细介绍了,感兴趣的可以看[官方文档](https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require)。 - 由于很多第三方库是 commonjs 规范的,所以声明文件也就不得不用到 `export =` 这种语法了。但是还是需要再强调下,相比与 `export =`,我们更推荐使用 ES6 标准的 `export default` 和 `export`。
Shell
UTF-8
1,795
2.84375
3
[ "MIT" ]
permissive
#! /bin/bash cat src/LocalStorage.js > /tmp/pre-bundle.js cat src/constants.js >> /tmp/pre-bundle.js cat src/Activities.js >> /tmp/pre-bundle.js cat src/Activity.js >> /tmp/pre-bundle.js cat src/App.js >> /tmp/pre-bundle.js cat src/CantButton.js >> /tmp/pre-bundle.js cat src/EditActivity.js >> /tmp/pre-bundle.js cat src/idealTimesToTimes.js >> /tmp/pre-bundle.js cat src/What.js >> /tmp/pre-bundle.js cat src/About.js >> /tmp/pre-bundle.js cat src/Settings.js >> /tmp/pre-bundle.js cat src/TimeLeft.js >> /tmp/pre-bundle.js cat src/minutesLeftInActivity.js >> /tmp/pre-bundle.js cat src/minutesToHumanString.js >> /tmp/pre-bundle.js cat src/index.js >> /tmp/pre-bundle.js grep -Ev "^(im|ex)port " /tmp/pre-bundle.js > build/static/js/simpleBuildBundle.js cp -f src/App.css build/static/css/simpleBuildBundle.css cp -f public/favicon.png build/favicon.png echo " <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <title>KyaKarun</title> <!-- Favicon --> <link rel='shortcut icon' href='./favicon.png'/> <!-- CSS --> <link rel='stylesheet' href='./static/css/simpleBuildBundle.css'/> </head> <body> <div id='root'></div> <script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js'></script> <!-- JS --> <script src='./static/js/simpleBuildBundle.js' type='text/babel'></script> </body> </html> " > build/index.html echo "Okay try starting a local server in the top-level folder and opening in browser."
Java
UTF-8
619
2.453125
2
[ "Apache-2.0" ]
permissive
package org.opensha.refFaultParamDb.calc.sectionDists; import java.io.Serializable; import java.util.Comparator; public class RecordIDsComparator implements Comparator<FaultSectDistRecord>, Serializable { /** * */ private static final long serialVersionUID = 1L; @Override public int compare(FaultSectDistRecord o1, FaultSectDistRecord o2) { if (o1.getID1() < o2.getID1()) return -1; else if (o1.getID1() > o2.getID1()) return 1; // they're equal if (o1.getID2() < o2.getID2()) return -1; else if (o1.getID2() > o2.getID2()) return 1; return 0; } }
Java
UTF-8
1,770
2.796875
3
[]
no_license
package cz.muni.fi.pv168.hotelmanager.backend; public class Guest { private Long id; private String name; private String phone; private String address; public Long getID() { return id; } public void setID(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Guest() { } public Guest(String name, String phone, String address) { this.name = name; this.phone = phone; this.address = address; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Guest guest = (Guest) o; if (address != null ? !address.equals(guest.address) : guest.address != null) return false; if (id != null ? !id.equals(guest.id) : guest.id != null) return false; if (name != null ? !name.equals(guest.name) : guest.name != null) return false; if (phone != null ? !phone.equals(guest.phone) : guest.phone != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (phone != null ? phone.hashCode() : 0); result = 31 * result + (address != null ? address.hashCode() : 0); return result; } @Override public String toString() { return "Guest{" + "\n id=" + id + "\n name=" + name + "\n phone=" + phone + "\n address=" + address + "\n}"; } }
JavaScript
UTF-8
1,197
3.234375
3
[]
no_license
class Item { constructor(element) { this.element = element; } } class RightLink { constructor(element, parent){ this.element = element; this.carousels = parent; this.carouselItem = parent.getItem(this.element.dataset.item); this.carouselItem = new Item(this.carouselItem); } } class LeftLink { constructor(element, parent){ this.element = element; this.carousels = parent; // this.carouselItem = parent.getItem(this.element.dataset.item); // this.carouselItem = new Item(this.carouselItem); } } class Carousel { constructor(element){ this.element = element; this.rightLink = element.querySelector(".Carousel__arrow-right"); this.rightLink = new RightLink(this.rightLink, this); this.leftLink = element.querySelector(".Carousel__arrow-left"); this.leftLink = new LeftLink(this.leftLink, this); } getItem(data) { return this.element.querySelector(`.Carousel__item[data-item="${data}"]`); } } let carousels = document.querySelectorAll(".Carousel"); carousels = Array.from(carousels).map(carousel => new Carousel(carousel)); console.log(carousels);
C
UTF-8
1,190
2.890625
3
[]
no_license
#include "includes/fractol.h" #include "includes/julia_set.h" #include <stdio.h> void put_square(t_image image, t_point where, int side, int color) { int x; int y; y = where.y; while(y < side) { x = where.x; while(x < side) { put_pixel_to_image(image, x, y, color); x++; } y++; } } void put_losange(t_image image, t_point where, int side, int color) { int x; int y; int n; double diagonale; diagonale = side * 1.4142; n = 0; while(n < side) { y = where.y; while(y < (int)diagonale) { x = 0; while(x - n < (int)diagonale) { put_pixel_to_image(image, x, y, color); x++; } y++; } n++; } } typedef struct s_leaf { t_point pos; t_point sommet1; t_point sommet1; double side; } t_leaf; int recursive_draw(t_env *env, t_leaf square, int n) { t_leaf new_square; if(n == 50) return (0); if(!(n % 2)) { new_square.pos = square.sommet1; new_square.side = (0.5 * 1.4142); put_losange(env->image, new_square.pos, , 0x0018C459); recursive_draw(env, n++); } else { } put_square(); return (0); } void *pythagore_three(void *env) { int n; double old_side; double new_side; return (NULL); }
Java
UTF-8
579
1.75
2
[]
no_license
package com.gms.web.member; import java.util.*; import org.springframework.stereotype.Component; import com.gms.web.command.CommandDTO; @Component public interface MemberService { public String add(Map<String,Object> map); public List<?> list(CommandDTO cmd); public List<?> findByNames(CommandDTO cmd); public StudentDTO findById(CommandDTO cmd); public String countMembers(CommandDTO cmd); public String modify(MemberDTO member); public String remove(CommandDTO cmd); public Map<String, Object> login(MemberDTO bean); //MemberBean[] list=new MemberBean[4]; }
Java
UTF-8
4,663
2.265625
2
[]
no_license
package com.security.admin.model; import com.anjuxing.platform.common.base.ValidateData; import com.anjuxing.platform.common.crud.CrudModel; import com.anjuxing.platform.common.util.CodeUtils; import com.anjuxing.platform.common.util.DateUtils; import com.anjuxing.platform.common.util.ValidateUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * 后台用户角色表 */ public class UmsRole extends CrudModel<UmsRole> { private static final long serialVersionUID = 1L; private Long id; // private String name; // 名称 private String description; // 描述 private Integer adminCount; // 后台用户数量 private Object createTime; // 创建时间 private Integer status; // 启用状态:0->禁用;1->启用 private Integer sort; // /************************************************自定义字段***********************************************/ public UmsRole() { } /** * 获取 * @return Long */ public Long getId() { return id; } /** * 设置 * @param id */ public void setId(Long id) { this.id = id; } /** * 获取名称 * @return String */ public String getName() { return name; } /** * 设置名称 * @param name */ public void setName(String name) { this.name = name; } /** * 获取描述 * @return String */ public String getDescription() { return description; } /** * 设置描述 * @param description */ public void setDescription(String description) { this.description = description; } /** * 获取后台用户数量 * @return Integer */ public Integer getAdminCount() { return adminCount; } /** * 设置后台用户数量 * @param adminCount */ public void setAdminCount(Integer adminCount) { this.adminCount = adminCount; } /** * 获取创建时间 * @return Object */ public Object getCreateTime() { return createTime; } /** * 设置创建时间 * @param createTime */ public void setCreateTime(Object createTime) { this.createTime = createTime; } /** * 获取启用状态:0->禁用;1->启用 * @return Integer */ public Integer getStatus() { return status; } /** * 设置启用状态:0->禁用;1->启用 * @param status */ public void setStatus(Integer status) { this.status = status; } /** * 获取 * @return Integer */ public Integer getSort() { return sort; } /** * 设置 * @param sort */ public void setSort(Integer sort) { this.sort = sort; } /********************************************数据校验处理操作***********************************************/ /** * 数据校验,插入数据之前执行,需要手动调用 * @return */ @Override public ValidateData validate() { ValidateData valid = new ValidateData(); StringBuffer msg = new StringBuffer(); boolean status = true; valid.setStatus(status); valid.setMessage(msg.toString()); return valid; } /** * 插入数据之前执行方法,需要手动调用 */ @Override public void preInsert() { if (ValidateUtils.isEmpty(this.id)) { //this.id = CodeUtils.getUUID(); } } /** * 更新数据之前执行方法,需要手动调用 */ @Override public void preUpdate() { } /** * 逻辑删除数据之前执行方法,需要手动调用 * @param */ @Override public void preCancel() { } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.getClass().getName()); sb.append("; id=" + (id == null ? "null" : id.toString())); sb.append("; name=" + (name == null ? "null" : name.toString())); sb.append("; description=" + (description == null ? "null" : description.toString())); sb.append("; adminCount=" + (adminCount == null ? "null" : adminCount.toString())); sb.append("; createTime=" + (createTime == null ? "null" : createTime.toString())); sb.append("; status=" + (status == null ? "null" : status.toString())); sb.append("; sort=" + (sort == null ? "null" : sort.toString())); return sb.toString(); } }
Java
UTF-8
1,725
2.65625
3
[]
no_license
package pt.lsts; import io.vertx.core.net.SocketAddress; import pt.lsts.imc4j.def.SystemType; import pt.lsts.imc4j.msg.Message; import pt.lsts.imc4j.net.ImcNetwork; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class ImcBridgePublish { private DatagramSocket socket = new DatagramSocket(); int remotePort; String remoteHost; private void listenImc(int port) { ImcNetwork imc = new ImcNetwork("BridgePublisher", 8008, SystemType.CCU); imc.setConnectionPolicy(p -> p.getId() != 8008); try { imc.startListening(port); imc.subscribe(Message.class, msg -> { handle(msg); }); } catch (Exception e) { e.printStackTrace(); } } public ImcBridgePublish(int localPort, SocketAddress cloudServer) throws Exception { this.remoteHost = cloudServer.host(); this.remotePort = cloudServer.port(); listenImc(localPort); } void handle(Message localMessage) { try { byte[] data = localMessage.serialize(); DatagramPacket packet = new DatagramPacket(data, data.length, new InetSocketAddress(remoteHost, remotePort)); socket.send(packet); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { int localPort = Integer.valueOf(args[0]); String host = args[1]; int hostPort = Integer.valueOf(args[2]); SocketAddress addr = SocketAddress.inetSocketAddress(hostPort, host); new ImcBridgePublish(localPort, addr); } }
TypeScript
UTF-8
993
3.796875
4
[]
no_license
class Prime { private maxPrime: number = 104744 /* Implements the Sieve of Eratosthenes */ nth(n: number): number { if (n < 1) { throw Error('Prime is not possible') } const integers: boolean[] = [] const primes: number[] = [] integers.push(false) integers.push(false) for (let i = 2; i < this.maxPrime; i++) { integers.push(true) } for (let i = 2; i < Math.sqrt(this.maxPrime); i++) { if (integers[i] === true) { let count = 0 for (let j = i * i; j < integers.length; j = (count * i) + i * i) { integers[j] = false count++ } } } for (let i = 0; i < integers.length; i++) { if (integers[i] === true) { primes.push(i) } } console.dir(primes) return primes[n - 1] } } export default Prime
Java
UTF-8
227
1.710938
2
[]
no_license
package com.mevo.app.data.model.response; import com.google.gson.annotations.SerializedName; public class ResponseLatLon { @SerializedName("lat") public double lat; @SerializedName("lon") public double lon; }
C++
UTF-8
2,217
3.0625
3
[]
no_license
#ifndef PIECE_H #define PIECE_H #include "Piece_Type.h" #include "square.h" #include <QGraphicsScene> #include <QGraphicsView> #include <vector> using namespace std; //Class for Checkers Pieces class Piece : public QObject, public QGraphicsItem { Q_OBJECT public: Piece(QColor color, int team, bool alive, Piece_Type piece_type,int x, int y); //Constructor //GETTERS, INLINE int GetTeam() {return team_;} bool GetAlive() {return alive_;} Piece_Type GetPieceType() {return piece_type_;} int GetX(){return x_;} int GetY(){return y_;} int GetRow(){return vecPosRow_;} int GetCol(){return vecPosCol_;} QColor GetColor(){return color_;} vector<Square*> GetAvailableMoves() {return available_moves_;} //SETTERS, INLINE void setColor(QColor color) {color_ = color;} //Sets color of cell void SetPieceType(Piece_Type new_type) {piece_type_ = new_type;} // void SetX(int x){x_ = x;} // void SetY(int y){y_ = y;} void SetRow(int r){vecPosRow_ = r;} void SetCol(int c){vecPosCol_ = c;} void setX(int x){x_ = x;} void setY(int y){y_ = y;} void SetAlive(bool alive_status) {alive_ = alive_status;} void SetAvailableMoves(vector<Square*> current_moves) {available_moves_ = current_moves;} //Need these void mousePressEvent(QGraphicsSceneMouseEvent *event) override; QRectF boundingRect() const override; QPainterPath shape() const override; void paint(QPainter* painter, const QStyleOptionGraphicsItem* item, QWidget* widget) override; void prepareGeometryChange(); signals: void PRightClick(Piece* c); void PLeftClick(Piece* c); private: QColor color_; int team_; //Hold value of 1 for P1 and 2 for P2 Piece_Type piece_type_; //Normal, king, or Ace bool alive_; //True if alive, false if dead int x_; int y_; int vecPosRow_; int vecPosCol_; static const int size_ = 40; //Size of cell vector<Square*> available_moves_; //Vector that holds pointers to Sqaures of available moves }; #endif // PIECE_H
C++
UTF-8
5,313
2.921875
3
[]
no_license
/* * GLMouseTools.h * TrackViewer * * A MouseTool is a specialised kind of mouse tool that * connects to some kind of GLCanvas in order to influence the * display parameters. * I defines its own sub-class of MouseResponder to support the * tools and then defines a set of sub-classes to handle the various * display tasks. * * Created by Brian Collett on 1/8/09. * Expanded and revised BC 9/11/2010. * Copyright 2009 Brian Collett. All rights reserved. * */ #ifndef _GLMouseTools_H #define _GLMouseTools_H #include "MouseTool.h" // // First the MouseResponder that adds an interface that the user of a // GLMouseTool must implement. // Note that there is no expectation that one would ever create a simple // instance of a MouseResponder. It is intended to be mixed into a more // complex class, probably some kind of window class. // class GLMouseResponder : public MouseResponder { public: // // No instance variables. This makes multiple inheritance MUCH simpler // and makes for trivial ctors. // GLMouseResponder() {}; virtual ~GLMouseResponder() {}; // // Then the interface of things that the various tools want to be able // to ask the display class to do. // All have null bodies which can be overridden to provide additional // functionality in a real use of the class. // virtual void LeftClick(int x, int y) {}; virtual void LeftDClick(int x, int y) {}; virtual void GetSize(wxSize& theSize) {}; virtual void Spin(float quaternion[4]) {}; virtual void Pan(float dx, float dy) {}; virtual void Dolly(float inOut) {}; virtual void Zoom(float inOut) {}; virtual void StartRegion(float xs, float ys) {}; virtual void Region(float xe, float ye) {}; virtual void EndRegion(float xe, float ye) {}; }; // // The top-level class provides the instance var to hold a pointer to // the responder and ensures that it is a GLMouseResponder. // class CGLMouseTool : public CMouseTool { protected: // // We don't own this so we don't throw it away. // By owning it at this level we get to know that it is a GLMouseResponder // and not just any old responder. // GLMouseResponder* mResponder; // // All the tools like to track the initial click. // Although wxWidgets returns them as longs we keep them // as ints because they could never get too large. // int mStartX; int mStartY; public: // // Constructor/Destructor // Since we don't own the responder we cant dispose of it. // CGLMouseTool(GLMouseResponder* theResp) : mResponder(theResp), CMouseTool(theResp) {}; virtual ~CGLMouseTool() {}; // // The tools share quite a bit of code. The special actions are handled // in the LeftDrag method which is left to the sub-class. // virtual void DoLeftClick(wxMouseEvent& event); virtual void DoLeftDClick(wxMouseEvent& event); virtual void DoLeftRelease(wxMouseEvent& event); }; // // The the individual tools. // The mouse tool interacts with a GL canvas to rotate the view // using a trackball algorithm from SGI. // class CSpinTool : public CGLMouseTool { protected: // // Instance variables. // public: // // Constructor/Destructor // CSpinTool(GLMouseResponder* theResp) : CGLMouseTool(theResp) {}; virtual ~CSpinTool() {}; // // Drag handler does all the tool specific work. // virtual void DoLeftDrag(wxMouseEvent& event); }; // // This is a GL mouse tool that moves the GL viewpoint // to pan across the scene. // class CPanTool : public CGLMouseTool { protected: // // Instance variables. // public: // // Constructor/Destructor // CPanTool(GLMouseResponder* theResp) : CGLMouseTool(theResp) {}; virtual ~CPanTool() {}; // // Drag handler does all the tool specific work. // virtual void DoLeftDrag(wxMouseEvent& event); }; // // This is a GL mouse tool that changes the distance between // viewer and image. // class CDollyTool : public CGLMouseTool { protected: // // Instance variables. // public: // // Constructor/Destructor // CDollyTool(GLMouseResponder* theResp) : CGLMouseTool(theResp) {}; virtual ~CDollyTool() {}; // // Drag handler does all the tool specific work. // virtual void DoLeftDrag(wxMouseEvent& event); }; // // This is a GL mouse tool that changes the GL field of // view to zoom the image. // class CZoomTool : public CGLMouseTool { protected: // // Instance variables. // public: // // Constructor/Destructor // CZoomTool(GLMouseResponder* theResp) : CGLMouseTool(theResp) {}; virtual ~CZoomTool() {}; // // Drag handler does all the tool specific work. // virtual void DoLeftDrag(wxMouseEvent& event); }; // // This one drags a rubber band rectangle on the screen and // passes it to the responder. // class CRegionTool : public CGLMouseTool { protected: // // Instance variables. // public: // // Constructor/Destructor // CRegionTool(GLMouseResponder* theResp) : CGLMouseTool(theResp) {}; virtual ~CRegionTool() {}; // // Drag handler tells canvas where to draw box. // virtual void DoLeftDrag(wxMouseEvent& event); // // We need to override click and release so we can tell the canvas // where to start and stop. // virtual void DoLeftClick(wxMouseEvent& event); virtual void DoLeftRelease(wxMouseEvent& event); }; #endif
Java
UTF-8
4,739
2.203125
2
[]
no_license
package com.example.finalresdemo.ui.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.finalresdemo.R; import com.example.finalresdemo.UserHolder; import com.example.finalresdemo.bean.User; import com.example.finalresdemo.biz.UserBiz; import com.example.finalresdemo.net.CommonCallback; import com.example.finalresdemo.utils.Constant; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.cookie.CookieJarImpl; public class LoginActivity extends BaseActivity { private final String TAG = "LoginActivity"; private EditText mEtUsername; private EditText mEtPassword; private Button mbtLogin; private TextView mTvRegister; private UserBiz userBiz =new UserBiz(); private static final String USERNAME = "username"; private static final String PASSWORD = "password"; @Override protected void onResume() { super.onResume(); CookieJarImpl cookieJar = (CookieJarImpl)OkHttpUtils.getInstance().getOkHttpClient().cookieJar(); cookieJar.getCookieStore().removeAll(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); initEvent(); initIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); initIntent(intent); } private void initIntent(Intent intent) { if (intent == null) { return; } String username = intent.getStringExtra(USERNAME); String password = intent.getStringExtra(PASSWORD); mEtUsername.setText(username); mEtPassword.setText(password); } private void initView() { mEtUsername = findViewById(R.id.id_et_username); mEtPassword = findViewById(R.id.id_et_password); mbtLogin = findViewById(R.id.id_btn_login); mTvRegister = findViewById(R.id.id_tv_register); } private void initEvent() { mbtLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = mEtUsername.getText().toString(); String password = mEtPassword.getText().toString(); Log.d(TAG,"test username:" + username + "\t password:" + password); if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { displayToast(Constant.ACCOUNT_OR_PWD_EMPTY); //不能继续往下执行 return; } startLoadingProgress(); userBiz.login(username, password, new CommonCallback<User>() { @Override public void onError(Exception e) { stopLoadingProgress(); displayToast(e.getMessage()); } @Override public void onSuccess(User response) { stopLoadingProgress(); displayToast(Constant.LOGIN_SUCCESS); //保存用户信息 UserHolder.getInstance().setUser(response); toOrderActivity(); } }); } }); mTvRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toRegisterActivity(); } }); } private void toRegisterActivity() { Intent intent = new Intent(this,RegisterActivity.class); startActivity(intent); } private void toOrderActivity() { Intent intent = new Intent(this,OrderActivity.class); startActivity(intent); finish(); } public static void launch(Context context, String username, String password) { Intent intent = new Intent(context,LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(USERNAME,username); intent.putExtra(PASSWORD,password); context.startActivity(intent); } private void displayToast(String text) { Toast.makeText(this,text,Toast.LENGTH_SHORT).show(); } @Override protected void onDestroy() { super.onDestroy(); userBiz.onDestroy(); } }
Java
UTF-8
636
1.929688
2
[]
no_license
package com.duyi.onlinevideo.service.impl; import com.duyi.onlinevideo.dao.BannerDao; import com.duyi.onlinevideo.entity.Banner; import com.duyi.onlinevideo.service.BannerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BannerServiceImpl implements BannerService { private BannerDao bannerDao; @Autowired public BannerServiceImpl(BannerDao bannerDao) { this.bannerDao = bannerDao; } @Override public List<Banner> getIndexBanner() { return bannerDao.findBannerAll(); } }
C++
UTF-8
1,962
3.859375
4
[]
no_license
#include <iostream> #include <vector> // 2개의 배열 v[left...mid]와 v[mid+1...right] 합치기 void merge(std::vector<int>& v, int l, int mid, int r) { // 왼쪽 배열 길이(왼쪽 배열에 mid가 포함되어 있기에 1을 더해준다.) int left = mid - l + 1; // 오른쪽 배열 길이 int right = r - mid; // 배열 생성 // v[left...mid] std::vector<int> leftV(left); // v[mid+1...right] std::vector<int> rightV(right); // 기존 배열을 두 개의 배열로 나눠준다. for (int i = 0; i < left; i++) // v[left...mid] leftV[i] = v[l + i]; for (int i = 0; i < right; i++) // v[mid+1...right] rightV[i] = v[mid + 1 + i]; // 분할된 왼쪽 배열 포인터 int i = 0; // 분할된 오른쪽 배열 포인터 int j = 0; // 정렬된 배열에 대한 포인터 // 실제로 원래 배열 자체를 나누진 않았기 때문에 l부터 시작 int k = l; // 분할된 배열 정렬하며 합치기 // 이미 새로운 배열을 생성해 분할해줬기 때문에 temp등 임시 배열을 생성하지 않고 // 바로 기존 배열에 정렬된 값을 입력해도 된다. while (i < left && j < right) { if(leftV[i] < rightV[j]) { v[k] = leftV[i]; i++; } else { v[k] = rightV[j]; j++; } k++; } // 이미 정렬되어서 남아 있는 값 복사 while (i < left) { v[k] = leftV[i]; i++; k++; } while (j < right) { v[k] = rightV[j]; j++; k++; } } void mergeSort(std::vector<int>& v, int l, int r) { if (l < r) { // overflow 방지 int mid = l + (r - l) / 2; // 반으로 분할해준다. mergeSort(v, l, mid); mergeSort(v, mid + 1, r); // 분할한 배열을 합쳐준다. merge(v, l, mid, r); } } int main() { std::ios_base::sync_with_stdio(0); std::cin.tie(0); int N; std::cin >> N; std::vector<int> v(N); for (int i = 0; i < N; i++) std::cin >> v[i]; mergeSort(v, 0, N-1); for(int& i : v) std::cout << i << "\n"; return 0; }
Python
UTF-8
1,413
3.015625
3
[]
no_license
#!/usr/bin/env python3 from app import BacktrackingNQueensOptimizedSafetyCheck from app import connection def get_number_of_solutions(): nro_soluciones = [] print() for i in range(1,13): solver = BacktrackingNQueensOptimizedSafetyCheck(i) solver.run() nro = solver.get_number_of_solutions() nro_soluciones.append(nro) print(f' N : {i}, total soluciones : {nro}') connection.close() return nro_soluciones # N distintas todas las soluciones # 1 1 1 # 2 0 0 # 3 0 0 # 4 1 2  # 5 2 10 # 6 1 4  # 7 6 40 # 8 12 92 # 9 46 352 # 10 92 724 # 11 341 2680 # 12 1787 14200  # 13 9233 73712 # 14 45752 365596  # 15 285053 2279184  # 16 1846955 14772512 # 17 11977939 95815104 # 18 83263591 666090624 # 19 621012754 4968057848 # 20 4878666808 39029188884 # 21 39333324973 314666222712  # 22 336376244042 2691008701644  def test_8queen(): actual = get_number_of_solutions() soluciones = [1,0,0,2,10,4,40,92,352,724,2680,14200,73712,365596,2279184,2279184,14772512] assert all([a == b for a, b in zip(actual, soluciones)])
Java
UTF-8
342
3.46875
3
[]
no_license
package com.mainacad.modul2.Labs2; public class Employee { public void calcSalary(String name, double... salary) { double finSalary = 0; for (int i = 0; i < salary.length; i++) { finSalary += salary[i]; } System.out.println(String.format("Name is %s, salary is %f", name, finSalary)); } }
JavaScript
UTF-8
1,139
3.109375
3
[]
no_license
setInterval(()=>{ let secDoc= document.getElementById('sec'); let minDoc= document.getElementById('min'); let hourDoc= document.getElementById('hour'); let newSec=parseInt(secDoc.innerHTML)+1; newSec+=''; if(newSec.length==1){ newSec='0'+newSec; } if(newSec=='01'){ minDoc.classList.remove('animate'); hourDoc.classList.remove('animate'); } if(newSec=='60'){ newSec='00'; minDoc.classList.add('animate'); newMin=parseInt(minDoc.innerHTML)+1; newMin+=''; if(newMin.length==1){ newMin='0'+newMin; } if(newMin=='60'){ newMin='00'; hourDoc.classList.add('animate'); newHour=parseInt(hourDoc.innerHTML)+1; newHour+=''; if(newHour.length==1){ newHour='0'+newHour; } if(newHour=='24'){ newHour='00'; newMin='00'; newSec='00'; } hourDoc.innerHTML=newHour; } minDoc.innerHTML=newMin; } secDoc.innerHTML=newSec; }, 1000);
Python
UTF-8
323
3.359375
3
[]
no_license
import unittest class TestSum(unittest.TestCase): def test_sum(self): g = Game() g.word = "TREE" self.assertEqual(g.word, "TREE", "Should be TREE") """def test_sum_tuple(self): self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")""" if __name__ == '__main__': unittest.main()
Python
UTF-8
556
3.03125
3
[]
no_license
import json import os import pandas as pd from argparse import ArgumentParser import matplotlib.pyplot as plt if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('-f', '--file',required=True, help='Log file to read data from') args = parser.parse_args() if args.file: if os.path.exists(args.file): timingData = json.load(open(args.file, "r")) for key in timingData: df = pd.DataFrame(timingData[key]) df.plot(title=key,x="timeSent", y="pingTime") plt.show() else: print(f"\"{args.file}\" does not exist")
Java
UTF-8
756
2.84375
3
[]
no_license
package myproject.ui; /** * @see UIMenuBuilder */ public final class UIMenu { private final String heading; private final Pair[] menu; UIMenu(String heading, Pair[] menu) { this.heading = heading; this.menu = menu; } public int size() { return menu.length; } public String getHeading() { return heading; } public String getPrompt(int i) { return menu[i].prompt; } public void runAction(int i) { menu[i].action.run(); } static final class Pair { final String prompt; final UIMenuAction action; Pair(String prompt, UIMenuAction action) { this.prompt = prompt; this.action = action; } } }
C#
UTF-8
382
3.546875
4
[]
no_license
interface IFileGenerator { void GenerateFile(string userInput); } class FileGenerator : IFileGenerator { // inject both or your file services into the constructor public void GenerateFile(string userInput) { switch(userInput) { // call the correct service here } }
Shell
UTF-8
1,138
3.5625
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # # Copyright (c) 2018 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # This script is used to reset the kubernetes cluster SCRIPT_PATH=$(dirname "$(readlink -f "$0")") source "${SCRIPT_PATH}/../../lib/common.bash" cri_runtime="${CRI_RUNTIME:-crio}" case "${cri_runtime}" in containerd) cri_runtime_socket="/run/containerd/containerd.sock" ;; crio) cri_runtime_socket="/var/run/crio/crio.sock" ;; *) echo "Runtime ${cri_runtime} not supported" ;; esac export KUBECONFIG="$HOME/.kube/config" sudo -E kubeadm reset -f --cri-socket="${cri_runtime_socket}" sudo systemctl stop "${cri_runtime}" sudo ip link set dev cni0 down || true sudo ip link set dev flannel.1 down || true sudo ip link del cni0 || true sudo ip link del flannel.1 || true # if CI run in bare-metal, we need a set of extra clean BAREMETAL="${BAREMETAL:-false}" if [ "${BAREMETAL}" == true ] && [ -f "${SCRIPT_PATH}/cleanup_bare_metal_env.sh" ]; then bash -f "${SCRIPT_PATH}/cleanup_bare_metal_env.sh" fi # Check no kata processes are left behind after reseting kubernetes check_processes # Checks that pods were not left check_pods
Java
UTF-8
3,646
1.945313
2
[]
no_license
package com.visioglobe.libVisioMove; public class VgINavigationListenerRefPtr { protected boolean swigCMemOwn; private long swigCPtr; protected VgINavigationListenerRefPtr(long cPtr, boolean cMemoryOwn) { this.swigCMemOwn = cMemoryOwn; this.swigCPtr = cPtr; } protected static long getCPtr(VgINavigationListenerRefPtr obj) { if (obj == null) { return 0; } return obj.swigCPtr; } /* access modifiers changed from: protected */ public void finalize() { delete(); } /* access modifiers changed from: protected */ public synchronized void delete() { if (this.swigCPtr != 0) { if (this.swigCMemOwn) { this.swigCMemOwn = false; libVisioMoveJNI.delete_VgINavigationListenerRefPtr(this.swigCPtr); } this.swigCPtr = 0; } } public VgINavigationListenerRefPtr() { this(libVisioMoveJNI.new_VgINavigationListenerRefPtr__SWIG_0(), true); } public VgINavigationListenerRefPtr(VgINavigationListener pPointer) { this(libVisioMoveJNI.new_VgINavigationListenerRefPtr__SWIG_1(VgINavigationListener.getCPtr(pPointer), pPointer), true); } public VgINavigationListenerRefPtr(VgINavigationListenerRefPtr pRefPtr) { this(libVisioMoveJNI.new_VgINavigationListenerRefPtr__SWIG_2(getCPtr(pRefPtr), pRefPtr), true); } public static VgINavigationListenerRefPtr getNull() { return new VgINavigationListenerRefPtr(libVisioMoveJNI.VgINavigationListenerRefPtr_getNull(), true); } public VgINavigationListenerRefPtr set(VgINavigationListener pPointer) { return new VgINavigationListenerRefPtr(libVisioMoveJNI.VgINavigationListenerRefPtr_set(this.swigCPtr, this, VgINavigationListener.getCPtr(pPointer), pPointer), false); } public VgINavigationListener __ref__() { return new VgINavigationListener(libVisioMoveJNI.VgINavigationListenerRefPtr___ref__(this.swigCPtr, this), false); } public VgINavigationListener __deref__() { long cPtr = libVisioMoveJNI.VgINavigationListenerRefPtr___deref__(this.swigCPtr, this); if (cPtr == 0) { return null; } return new VgINavigationListener(cPtr, false); } public VgINavigationListener get() { long cPtr = libVisioMoveJNI.VgINavigationListenerRefPtr_get(this.swigCPtr, this); if (cPtr == 0) { return null; } return new VgINavigationListener(cPtr, false); } public boolean isValid() { return libVisioMoveJNI.VgINavigationListenerRefPtr_isValid(this.swigCPtr, this); } public void notifyPositionUpdated(VgINavigationConstRefPtr pNavigation, VgPosition pPosition, double pTime) { libVisioMoveJNI.VgINavigationListenerRefPtr_notifyPositionUpdated(this.swigCPtr, this, VgINavigationConstRefPtr.getCPtr(pNavigation), pNavigation, VgPosition.getCPtr(pPosition), pPosition, pTime); } public void notifyNewInstruction(VgINavigationConstRefPtr pNavigation, long pIndex) { libVisioMoveJNI.VgINavigationListenerRefPtr_notifyNewInstruction(this.swigCPtr, this, VgINavigationConstRefPtr.getCPtr(pNavigation), pNavigation, pIndex); } public void ref() { libVisioMoveJNI.VgINavigationListenerRefPtr_ref(this.swigCPtr, this); } public int unref() { return libVisioMoveJNI.VgINavigationListenerRefPtr_unref(this.swigCPtr, this); } public int getNbReferences() { return libVisioMoveJNI.VgINavigationListenerRefPtr_getNbReferences(this.swigCPtr, this); } }
Python
UTF-8
527
3.59375
4
[]
no_license
def equilibrium(a,n): i=0 j=n flag=False sm,ls=0,0 sm=sum(a) while i<j: sm-=a[i] if sm==ls: flag=True break # O(n) ls+=a[i] i+=1 if flag: return i return -1 if __name__ == "__main__": a=[1,7,3,6,5,6] # a=[1,2,3] # a=[-7, 1, 5, 2, -4, 3, 0] ans=equilibrium(a,len(a)) if ans>=0: print("Equilibrium exists at:",ans) else: print("-1")
SQL
UTF-8
860
3.84375
4
[]
no_license
-- -- OV-chipkaart stations -- CREATE TABLE stations_data ( company INT NOT NULL, -- transport company number ovcid INT NOT NULL, -- OV-chipkaart station number name VARCHAR(50), -- name as used by transport company city VARCHAR(50), -- city/municipality longname VARCHAR(120), -- long name, should be fully clear haltenr INT, -- dutch general halte nummer zone INT, -- dutch public transport zone lon FLOAT, -- longitude lat FLOAT, -- lattitude PRIMARY KEY (company, ovcid) ); -- stations view with title based on available fields in stations_data CREATE VIEW stations AS SELECT *, (CASE company WHEN 4 THEN name ELSE COALESCE(longname, city||', '||name, name) END) AS title FROM stations_data;
Python
UTF-8
151
2.9375
3
[]
no_license
t=int(input()) for test in range(t): n,m,k=map(int,input().split()) if abs(n-m)>k: print(abs(n-m)-k) else: print(0)
Shell
UTF-8
478
3.09375
3
[]
no_license
#!/bin/sh set -e if [ "$1" = "configure" ]; then if dpkg --compare-versions "$2" 'lt-nl' '2018.07.30~' && which gpg >/dev/null && which apt-key >/dev/null; then KEYRING="/etc/apt/trusted.gpg" eval $(apt-config shell KEYFILE Apt::GPGV::TrustedKeyring) eval $(apt-config shell KEYFILE Dir::Etc::Trusted/f) if [ -e "$KEYFILE" ]; then apt-key --keyring "$KEYFILE" del 4BE37A90 >/dev/null 2>&1 || : fi fi fi #DEBHELPER#
Python
UTF-8
1,195
4.25
4
[]
no_license
""" Define a function, munch_prefix(p, q), that takes as input two lists and returns a new list containing all the elements of q except of any elements at the beginning of q that match the corresponding elements at the beginning of p. For example, munch_prefix([1, 2, 3, 4], [5, 6]) => [5, 6] munch_prefix([1, 2, 3, 4], [3, 4, 5]) => [3, 4, 5] munch_prefix([1, 2, 3, 4], [1, 2, 4, 5, 6]) => [4, 5, 6] munch_prefix([1, 2, 3, 4], [1, 2, 3]) => [] """ """ Note that the returned list should not share any storage with either of the input lists, and the input lists must not be modified by your function: a = [1, 2, 3] b = [1, 2, 3, 4, 5] c = munch_prefix(a, b) b[4] = 6 assert c == [4, 5] """ def munch_prefix(p, q): index = 0 if p[0] == q[0]: for i in range(0, min(len(q), len(p))): if p[i] == q[i]: index = index + 1 else: break return q[index:] return q print munch_prefix([1, 2, 3, 4], [5, 6]) print munch_prefix([1, 2, 3, 4], [3, 4, 5]) print munch_prefix([1, 2, 3, 4], [1, 2, 4, 5, 6]) print munch_prefix([1, 2, 3, 4], [1, 2, 3])
C++
UTF-8
1,534
2.5625
3
[]
no_license
#include <vector> #include <algorithm> #include <utility> #include <cstdio> #include <queue> #define min(a,b) ((a<b)?a:b) const long long INF = 1e15; using namespace std; using ll = long long; using pll = pair<ll, ll>; vector <pll> G1[5001], G2[5001]; priority_queue <pll, vector<pll>, greater<pll> > Q; ll d1[5001], d2[5001]; ll DP[5001][5001] = {{0}}; ll cost[5001][5001]; int n, b, s, r; void dij(int s, ll d[], vector <pll> G[]){ for(int i=1; i<=n; ++i){ d[i] = INF; } Q.push({0, s}); while(!Q.empty()){ int v = Q.top().second; ll w = Q.top().first; Q.pop(); if (w > d[v]) continue; for(auto edge : G[v]){ ll chi = edge.first, len = edge.second; if (w+len < d[chi]) { d[chi] = w+len; Q.push({w+len, chi}); } } } } int main(){ scanf("%d%d%d%d", &n,&b,&s,&r); int a,d,c; for(int i=0; i<r; ++i){ scanf("%d%d%d",&a,&d,&c); G1[a].push_back({d,c}); G2[d].push_back({a,c}); } dij(b+1, d1, G1); dij(b+1, d2, G2); vector <ll> C(b); for(int i=0; i<b; ++i){ C[i] = d1[i+1] + d2[i+1]; } sort(C.begin(), C.end()); // Get costs ll sum = 0; for(int i=0; i<b; ++i){ sum = 0; for(int j=i; j<b; ++j){ sum += C[j]; cost[i+1][j+1] = sum * (j-i); } } // DP is min_cost[nums up to i][num of partitions] for(int i=1; i<=b; ++i){ DP[i][1] = cost[1][i]; for(int j=2; j<=i && j<=s; ++j){ DP[i][j] = DP[i-1][j-1]; for(int k=2; k <= i/j; ++k){ DP[i][j] = min(DP[i][j], DP[i-k][j-1]+cost[i-k+1][i]); } } } printf("%lli\n", DP[b][s]); }
C
UTF-8
455
3.671875
4
[]
no_license
#include <unistd.h> int is_lower(char c) { if ('a' <= c && c <= 'z') return (1); return (0); } int is_upper(char c) { if ('A' <= c && c <= 'Z') return (1); return (0); } int main(int argc, char** argv) { int i; char c; if (argc == 2) { i = 0; while (argv[1][i]) { c = argv[1][i]; if (is_lower(argv[1][i])) c -= 32; else if (is_upper(argv[1][i])) c += 32; write(1, &c, 1); i++; } } write(1, "\n", 1); }
Java
UTF-8
387
1.546875
2
[]
no_license
package com.orientdata.lookforcustomers.view.home.imple; import com.orientdata.lookforcustomers.base.BaseView; import com.orientdata.lookforcustomers.bean.MessageAndNoticeBean; import java.util.List; /** * Created by wy on 2017/12/10. */ public interface IMsgAndNoticeView extends BaseView { void selectMsgAndAnnouncement(List<MessageAndNoticeBean> messageAndNoticeBeanList); }
Java
UTF-8
1,070
2.921875
3
[]
no_license
package asteroids.components.Geometry3D; import asteroids.components.Component; import asteroids.math.Vector3f; public class PointLightComponent extends Component { public LightComponent lightComponent; public Vector3f attenuation; public float range; public PointLightComponent() { this.lightComponent = new LightComponent(); this.attenuation = new Vector3f(); setAttenuation(new Vector3f(0.0f, 0.0f, 1.0f)); } public void setup(Vector3f color, float intensity, Vector3f attenuation) { this.lightComponent.setup(color, intensity); this.setAttenuation(attenuation); } private void setAttenuation(Vector3f attenuation) { this.attenuation.set(attenuation); calculateRange(); } private void calculateRange() { float minLight = 256 / 5; float c = this.attenuation.x - minLight * this.lightComponent.getIntensity() * this.lightComponent.getColor().max(); float l = this.attenuation.y; float q = this.attenuation.z; this.range = (float)((-l + Math.sqrt(l * l - 4 * q * c))/(2 * q)); } }
Java
UTF-8
186
2.484375
2
[]
no_license
package kr.taeu.effectiveJava.item38; // 인터페이스를 이용해 확장 가능 열거 타입을 흉내 냈다. public interface Operation { double apply(double x, double y); }
Python
UTF-8
4,602
2.71875
3
[ "MIT" ]
permissive
#!/usr/bin/env python #-*- coding: utf-8 -*- from __future__ import print_function from bs4 import BeautifulSoup as bs from selenium import webdriver import multiprocessing import os import re import signal import sys import time import csv import urllib2 import constants def worker(lock, queue, monitor): signal.signal(signal.SIGINT, signal.SIG_IGN) pid = os.getpid() while True: waiting = True try: monitor[pid] = waiting query = queue.get() except (IOError, EOFError): return monitor[pid] = False search_url = 'http://www.bing.com/search?q=%2bsite%3alinkedin.com+' + query browser = webdriver.Firefox() browser.implicitly_wait(4) browser.get(search_url) if browser.find_elements_by_xpath("//li[@class='b_no']"): result = 'No results found for {}. He/She is probably not a CEO.'.format(query) else: links = browser.find_elements_by_xpath("//li[@class='b_algo']/h2/a[@href]") url = next((link.get_attribute('href') for link in links if 'linkedin.com/in/' in link.get_attribute('href')), None) if url: req = urllib2.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) page = urllib2.urlopen(req).read() soup = bs(page, 'lxml') try: name = soup.find('h1', attrs = {'id': 'name'}).text.encode('utf-8').strip() tag = soup.find('section', attrs = {'id': 'experience'}) roles = [t.text.encode('utf-8').strip() for t in tag.find_all('h4', attrs={'class':'item-title'})] companies = [t.text.encode('utf-8').strip() for t in tag.find_all('h5', attrs={'class':'item-subtitle'})] date_ranges = [t.text.encode('utf-8').strip() for t in tag.find_all('span', attrs={'class':'date-range'})] positions = [] for i in range(len(roles)): dates = date_ranges[i].split('(')[0].split('\xe2\x80\x93') # split date range by en dash start_date = dates[0].strip() end_date = dates[1].strip() if len(dates) == 2 else '' positions.append({'company': companies[i], 'role': roles[i], 'start_date': start_date, 'end_date': end_date}) with lock: with open('linkedin.csv', 'ab') as csvfile: # append writer = csv.writer(csvfile, dialect = 'excel') writer.writerow([name]) writer.writerow(['Company', 'Role', 'Start Date', 'End Date']) for p in positions: result = [p['company'], p['role'], p['start_date'], p['end_date']] # print(result) writer.writerow(result) except AttributeError: result = 'WARNING: Something went wrong. Check out ' + url else: with lock: writer.writerow(result) browser.quit() def main(): manager = multiprocessing.Manager() lock = manager.Lock() monitor = manager.dict() queue = manager.Queue() with open(constants.SEARCH_STRING_FILE) as f: lines = filter(None, [line.rstrip('\n') for line in f.readlines() if not line.startswith('#')]) # alist = [r',', r'\w\.', r'/\w+/?'] # # Join all the regexes # rx = re.compile('|'.join(alist), re.M|re.DOTALL) # queries = [re.sub(r'\s+', r'+', rx.sub(r'', line)) for line in lines] queries = [re.sub(r'\s+', r'+', line) for line in lines] for query in queries: queue.put(query) pool = multiprocessing.Pool(4, worker, (lock, queue, monitor)) while True: try: time.sleep(1) waits = [] pids = iter(monitor.keys()) for p in pids: waits.append(monitor[p]) if all(waits): pool.terminate() pool.join() return except KeyboardInterrupt: pool.terminate() pool.join() sys.exit() if __name__ == '__main__': start_time = time.time() main() print('Elapsed time:', time.time() - start_time, 'seconds.')
Python
UTF-8
2,589
3.140625
3
[]
no_license
import unittest from src.Display.TestOutput import TestOutput from src.Engine.Game import Game class GameTest(unittest.TestCase): user_output = TestOutput() game = Game({"Game Id": "1", "Game Name": "City Builder", "Price": 8.99, "Stock": 4}) game2 = Game({"Game Id": "2", "Game Name": "Survivalist", "Price": 9.99, "Stock": 5}) game3 = Game({"Game Id": "3", "Game Name": "Secret Treasure", "Price": 26.99, "Stock": 7}) def test_reduceStock(self): game = Game({"Game Id": "1", "Game Name": "City Builder", "Price": 8.99, "Stock": 4}) game.reduceStock() self.assertEqual(3, game.getStock()) def test_reduceStockFrom0(self): game = Game({"Game Id": "1", "Game Name": "City Builder", "Price": 8.99, "Stock": 0}) game.reduceStock() self.assertEqual(0, game.getStock()) def test_reduceMultipleStocks(self): game = Game({"Game Id": "1", "Game Name": "City Builder", "Price": 8.99, "Stock": 4}) game2 = Game({"Game Id": "2", "Game Name": "Survivalist", "Price": 9.99, "Stock": 5}) game3 = Game({"Game Id": "3", "Game Name": "Secret Treasure", "Price": 26.99, "Stock": 7}) game.reduceStock() game2.reduceStock() game3.reduceStock() self.assertEqual(6, game3.getStock()) def test_displayGameDetails(self): self.game.displayGameDetails(self.user_output) self.assertIn("Stock", self.user_output.getOutputList()[-1]) def test_displayGameDetailsWithStock0(self): game = Game({"Game Id": "1", "Game Name": "City Builder", "Price": 8.99, "Stock": 0}) output_list_size = len(self.user_output.getOutputList()) game.displayGameDetails(self.user_output) self.assertEqual(output_list_size, len(self.user_output.getOutputList())) def test_displayMultipleGameDetails(self): self.game.displayGameDetails(self.user_output) self.game2.displayGameDetails(self.user_output) self.game3.displayGameDetails(self.user_output) self.assertIn("7", self.user_output.getOutputList()[-1]) def test_displayGame(self): self.game.displayGame(self.user_output) self.assertIn("City Builder", self.user_output.getOutputList()[-1]) def test_displayMultipleGames(self): self.game.displayGame(self.user_output) self.game2.displayGame(self.user_output) self.game3.displayGame(self.user_output) game_name = "Secret Treasure" self.assertIn(game_name, self.user_output.getOutputList()[-1]) if __name__ == '__main__': unittest.main()
Java
UTF-8
3,325
2
2
[ "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.felix.ipojo.manipulator.metadata.annotation.visitor; import org.apache.felix.ipojo.manipulator.Reporter; import org.apache.felix.ipojo.manipulator.metadata.annotation.ComponentWorkbench; import org.apache.felix.ipojo.metadata.Attribute; import org.apache.felix.ipojo.metadata.Element; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Opcodes; /** * Parses the @Handler annotation. * * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a> * @see org.apache.felix.ipojo.annotations.Handler */ public class HandlerVisitor extends AnnotationVisitor { private Element handler = new Element("handler", ""); private ComponentWorkbench workbench; private Reporter reporter; public HandlerVisitor(ComponentWorkbench workbench, Reporter reporter) { super(Opcodes.ASM5); this.workbench = workbench; this.reporter = reporter; } /** * Visit @Handler annotation attributes. * * @param name : annotation attribute name * @param value : annotation attribute value * @see org.objectweb.asm.AnnotationVisitor#visit(java.lang.String, java.lang.Object) */ public void visit(String name, Object value) { if (name.equals("name")) { handler.addAttribute(new Attribute("name", value.toString())); return; } if (name.equals("namespace")) { handler.addAttribute(new Attribute("namespace", value.toString())); return; } if (name.equals("level")) { handler.addAttribute(new Attribute("level", value.toString())); return; } if (name.equals("architecture")) { handler.addAttribute(new Attribute("architecture", value.toString())); } } /** * End of the visit. * Append to the "component" element computed attribute. * * @see org.objectweb.asm.AnnotationVisitor#visitEnd() */ public void visitEnd() { String classname = workbench.getType().getClassName(); handler.addAttribute(new Attribute("classname", classname)); if (workbench.getRoot() == null) { workbench.setRoot(handler); } else { // Error case: 2 component type's annotations (@Component and @Handler for example) on the same class reporter.error("Multiple 'component type' annotations on the class '{%s}'.", classname); reporter.warn("@Handler will be ignored."); } } }
Markdown
UTF-8
9,479
3.421875
3
[]
no_license
+++ title = "第一百九十九章 车轮战" weight = 199 +++ 第8卷   第一百九十九章 车轮战   床上,五位赤裸的少女并排躺在一起,刚刚洗完澡,还经历了一轮性爱之后的她们都感觉到有点疲倦,处于五位少女的最中间的林萱则是完全一副人生赢家的模样。她一手揽着左边的林璇,一手在旁边诺霖的小肚子上来回抚摸着,身后的那条猫尾巴好像是放在了诺汐的小穴里,在那温暖的地方休息着。虽然这样子很奇怪,不过诺汐本人也并没有什么在意的,毕竟林萱学姐的那条猫尾巴挺舒服的。床上唯有月涟一人,就单纯地呆在最左侧,好像是被遗忘的样子。   “喵~月涟酱是不是寂寞了呢?”林璇看出了月涟的心情,将自己的尾巴缠到了月涟的脚踝上,自己也稍稍倾了过去,捏了一下月涟的乳首。   “呀!没,没有——”月涟嘟起嘴来,看着呆在自己身旁的两对双胞胎姐妹,唉,为什么自己就没有一个姐姐或妹妹呢?   “姐姐,不如我们再开始第二回合吧?这一次再多照顾一点月涟怎么样?”林璇一边用自己的猫尾抚过月涟的大腿内侧,一边向自己的姐姐提议道。   “哦?第二回合?”   “喵~很累了喵~”此时的诺霖则是伸了个懒腰,“呀!林萱学姐不要把手指伸进去!”   “嗯?诺霖酱不想要吗?”   “嘤嘤……姐姐,林萱学姐欺负我喵!”诺霖摇了摇脑袋,虽然她显得有点抗拒林萱学姐的抚摸,但是她也不得不承认,这位公主的技巧绝对是一流的水平。   “诺汐——”   “我,我不好说……”诺汐也不敢反抗林萱学姐,毕竟说不定那猫尾长驱直入,把她玩坏掉呢。   “好了,那么我们一起去照顾照顾月涟吧!”林萱将猫尾巴从诺汐的小穴里抽出,从林璇和诺霖的环抱之中起身,“嗯,不如直接来车轮战吧!”   “车轮战——”   听到这个词的时候,诺霖不由得一惊。   “哇哦,姐姐竟然要玩车轮战吗?”旁边的林璇掩着嘴,好像是在笑一样。   “嗯嗯,我觉得目前来看车轮战是一个不错的选择。”林萱点了点头,“这样才能更好的照顾月涟,对吧?”   “诶诶诶,你们还没有问过我的意见呢!”月涟的心中泛起了一丝不好的预感。她还记得在游戏里车轮战好像就是多对一轮番上阵……林萱学姐突然说出车轮战的话语,而自己还是被轮的对象吗!   “难道月涟要拒绝我吗?”林萱一下子捂住了自己的胸口,装出了一番十分痛心的表情,“没想到,本公主竟然也有遭到拒绝的那一天,啊——”   “正常女孩都会拒绝的吧!”   “不哦,想和姐姐做爱的女孩子可以绕整个风环王国一圈呢。”旁边的林璇说道。   “哈?是不是我下楼遇到的10个女孩里至少有9个都和她做过呀!”   “准确来说可能10个都做过……”   “所以,月涟同学——真的要拒绝本公主吗?”林萱将月涟逼到了床边的角落,对她眨了眨眼。无论怎么看,林萱都是一位无可挑剔的美少女,身为公主的她性爱技巧也是超一流的水准。在刚刚的那个“回合”之中,自己就已经败下阵来,而现在又要迎接车轮战……   “唔!要,要不随机决定!你,你看,诺霖、诺汐她们不也很期待车轮战吗!不能就只照顾我一个人,对吧!公主,公主是不能偏心的!”虽然月涟只是平民家庭出身,但是她想起了之前她们圣帕公主秦雅说过的话。   “诶诶?等,等等,月涟你不要胡说!”   “还有,还有,林萱学姐你难道不想被我们一起欺负吗!”   “唔……这个展开倒也的确不错。”林萱思考了一下,“行,那么,手心手背如何?和大家都不同的那一位,就要遭到最残酷的‘惩罚’哦!”   “我没意见。”林璇点了点头,反正无论是赢是输,对她来说都不会亏。赢了还可以欺负一下姐姐,嗯,相当不错。   “手心手背嘛,嗯,那么就这样吧!”   五位少女在床上围成了一个圈。   “那么——”林萱故意拉长了声音,看着床上的大家彼此对视的模样,“手心手背!”   下一秒,五位少女一同伸出手来,四个手心一个手背,看来结果已经是显然易见了。   “哦哦哦——竟然还是月涟呢。”林萱舔了舔舌头,露出了一丝不怀好意的笑容,“看来,是天意如此了呢。”   “是月涟呢。”诺霖的心中暗喜,还好是月涟,如果她成为了车轮战里当受的那一位,估计第二天她连床都下不来了吧!   “月涟,加油哦!我会好好照顾你的!”诺汐则是拍了拍月涟的肩膀,对她露出了一个祝福般的眼神。   “月涟酱,请多多指教。”而林璇则是礼貌地一笑,虽然同为风环王国的两位公主,不过姐妹俩的性格却完全不同呢。   “等,等等为什么你们都出手心呀!等等,林萱学姐不,不要——”月涟不由得吐槽道,当然,还不等她反应过来,她便是被林萱给按倒在了床头,林璇递来了新的绳子,捆住了她的手腕和双腿。最终,月涟被她们俩给好好捆绑了一番,像是一个艺术品一样展示在了床上。   “那么顺序该怎么决定呢?”林萱舔了舔自己的手指,一副跃跃欲试的表情。诺霖和诺汐也已经将道具全都准备好了,十根形状各异的情趣按摩棒,像是商店柜台一般摊开展示在床上,无论是哪一根都可以让可怜的小月涟达到人生的顶峰吧。   “猜拳?”   “石头剪刀布!”   “耶,由我先来!”唯一出布的诺霖露出了胜利的表情,她立即便是拿起了其中一根按摩棒,嗯,是姐姐比较喜欢的插入型。不知道月涟是不是也一样会喜欢呢?   她拿着按摩棒,来到了月涟的面前,“第一个是我哦,月涟酱。”   “请,请温柔一点……”月涟点了点头,看起来她估计心中在暗喜吧。还算好第一个是比较温柔的诺霖,如果第一个就让林萱来的话,估计怕不是自己就要高潮到昏迷。   “嗯嗯,我会让月涟酱很舒服的哦!那么首先就从这里开始吧。”诺霖拿起那根按摩棒,将其抵在了月涟挺立起来的乳首处,接着按下了按摩棒的开关。只见按摩棒的前端稍稍转动了一下,刺激了一下月涟的乳首,令她发出了一声可爱的呻吟。   “没想到月涟怎么敏感呢。”   “才,才没有呢……只,只是平日里,开发那边比较多而已。”月涟轻声地嘀咕了一句,而这个时候旁边的林萱好像是蓄势待发一样,立即拿起了两个乳夹,夹在了月涟的乳头上。   “呀!林萱学姐!”   “做爱的时候要叫我林萱公主,不然的话——”林萱凑到月涟的耳边,轻轻咬了一下她的耳垂。这一动作,令敏感的月涟更是饥渴难耐,整个人都在床上不断地挣扎着。   “我,我知道了,林萱……公,公主!”   “这才是乖孩子呢,诺霖,用棒棒奖励她吧。”林萱舔过她的耳垂。   “嗯嗯。月涟酱,放轻松哦~”诺霖轻轻用手分开了月涟的阴唇,将按摩棒在那入口处磨蹭了几下。听着月涟口中所发出的呻吟声,她缓缓地将其推入了进去。   “啊,啊啊啊——啊啊!”   诺霖按下按摩棒的开关,让插在其中的按摩棒开始搅动了起来。快感从下体之中传来,月涟刚想要发出呻吟就被林萱堵住了嘴唇。接着,大功告成的诺霖暂且退后,让自己的姐姐后继了上去。   “后面也要插哦~”诺汐笑了笑,既然前面小霖已经搞定了,那她就只能享用后方了,轻轻拍了一下月涟的小屁股,调整了一下她整个人的姿势之后,她拿起了一根更粗一点的按摩棒,将其插到了月涟的菊花口。   “呀!那,那里不,不行……我,我也没,开,开发过呀!”月涟表示除了日常的灌肠和一些课程的要求之外,她还真的没有用过后面。诺汐一下子选用这么粗的按摩棒,让她还感觉到有点疼呢。   “没事的,来,努力一下。”   “不,不要……那,那里不可以……”月涟挣扎着。   “放轻松哦,后面也挺舒服的。”林萱挠着她的腋窝,给月涟放松着身体,同时对诺汐点了点头,示意自己已经控制住了月涟。   “呀!”在诺汐的推动下,第二根按摩棒从她的菊穴处进入,给月涟带来了一番全新的快感。同时,后面的林璇还拿着第三根按摩棒在跃跃欲试呢。   “救……救命,唔……”月涟想要叫出声,不过嘴唇却又被林萱堵上了,发出的声音最后只剩下了呜咽。   真是一位可怜的少女呢~   真是一个美妙的夜晚呢~   
Java
UTF-8
366
1.617188
2
[]
no_license
package com.nklmish.springkafkaissue.kafkautilsexception; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KafkaUtilsExceptionApplication { public static void main(String[] args) { SpringApplication.run(KafkaUtilsExceptionApplication.class, args); } }
C#
UTF-8
1,637
3.421875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; using System.Net; using System.IO; using Newtonsoft.Json; namespace Pokedex { class Program { static void Main(string[] args) { Console.WriteLine("Digite o número do pokemon: "); var pokeNumber = Console.ReadLine(); // Create the web request HttpWebRequest request = WebRequest.Create("http://pokeapi.co/api/v2/pokemon/" + pokeNumber) as HttpWebRequest; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { // Get the response stream var json = DeserializeFromStream(response.GetResponseStream()); Pokemon deserializedJson = JsonConvert.DeserializeObject<Pokemon>(json.ToString()); // Console application output Console.WriteLine("Nome: " + deserializedJson.name.ToUpperInvariant()); Console.ReadKey(); } } } public static object DeserializeFromStream(Stream stream) { var serializer = new JsonSerializer(); using (var sr = new StreamReader(stream)) using (var jsonTextReader = new JsonTextReader(sr)) { return serializer.Deserialize(jsonTextReader); } } } }
Shell
UTF-8
188
2.90625
3
[]
no_license
#!/bin/sh echo Content-type: text/html echo "" WANIP=`busybox ip -4 -o addr show wan0 | busybox awk '{print $6}'` if [ -n "$WANIP" ]; then echo "$WANIP" else echo "127.0.0.1" fi
Python
UTF-8
174
3.703125
4
[ "MIT" ]
permissive
class Circle: def __init__(self, radius): self.radius = radius def area(self): return self.radius**2*3.14 aCircle = Circle(2) print(aCircle.area())
JavaScript
UTF-8
1,120
2.609375
3
[]
no_license
import React, { useState } from 'react'; // import logo from './logo.svg'; import './App.css'; function App() { let [count, updateCount] = useState(0); let [nightMode, updateMode] = useState(false); return ( <div className={`main_div ${nightMode ? 'main_div_night' : ''}`}> <div className='color_change'> <button className={`color_change_button ${nightMode ? 'color_change_button_night' : ''}`} onClick={()=>{updateMode(!nightMode)}}>{nightMode ? "Light Mode" : "Dark Mode"}</button> </div> <div className='counter_section'> <button className={`decrement_button ${nightMode ? 'decrement_button_night' : ''}`} onClick={()=>{ if(count > 0){ updateCount(count-1); } }}> - </button> <div className='counter'> <h1 className={`counter_text ${nightMode ? 'counter_text_night' : ''}`}>{count}</h1> </div> <button className={`increment_button ${nightMode ? 'increment_button_night' : ''}`} onClick={() =>{ updateCount(count+1); }}> + </button> </div> </div> ); } export default App;
Markdown
UTF-8
1,785
2.90625
3
[ "Unlicense" ]
permissive
--- layout: post title: Unusual Spending Kata categories: [Experienced, Mocks, TDD, Pair-Programming] image: default.jpg --- {% include credits.md name='Test Double Consulting Agency' url='https://github.com/testdouble/contributing-tests/wiki/Unusual-Spending-Kata' %} ## Description You work at a credit card company and as a value-add they want to start providing alerts to users when their spending in any particular category is higher than usual. * A `Payment` is a simple value object with a `price`, `description`, and `category` * A `Category` is an enumerable type of a collection of things like "entertainment", "restaurants", and "golf" * For a given `userId`, fetch the payments for the current month and the previous month * Compare the total amount paid for the each month, grouped by category; filter down to the categories for which the user spent at least 50% more this month than last month * Compose an e-mail message to the user that lists the categories for which spending was unusually high, with a subject like "Unusual spending of $1076 detected!" and this body: ``` Hello card user! We have detected unusually high spending on your card in these categories: * You spent $148 on groceries * You spent $928 on travel Love, The Credit Card Company ``` ## More details More details about the goal, caveats, extra credit or solutions: [Unusual Spending Kata by Test Double](https://github.com/testdouble/contributing-tests/wiki/Unusual-Spending-Kata). ## Get the code Starter projects: [JavaScript](https://github.com/testdouble/unusual-spending), [Java](https://github.com/testdouble/java-testing-example/tree/master/unusual-spending). If your favorite language is missing, feel free to create a pull request. Be sure the maintainer will be happy ;-)