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
|
---|---|---|---|---|---|---|---|
C
|
UTF-8
| 919 | 3.09375 | 3 |
[] |
no_license
|
/*
* TCP/IP
* => Socket Programming: Client
*
* Server
* 1. socket
* 2. connect
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
// Need for Internet Protocol
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
struct sockaddr_in saddr;
struct sockaddr_in caddr;
socklen_t caddrlen;
char buf[100];
int ret;
// 1. socket
int sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&saddr, 0, sizeof saddr);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(5000); // big endian of 5000;
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 2. connect
connect(sock, (struct sockaddr*)&saddr, sizeof(saddr));
// Echo Server
while ((ret = read(0, buf, sizeof buf)) > 0) {
write(sock, buf, ret);
ret = read(sock, buf, sizeof buf);
write(1, buf, ret);
}
close(sock);
// useage
// > $ telnet 127.0.0.1 5000
return 0;
}
|
PHP
|
UTF-8
| 309 | 3.203125 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html>
<head>
<title>My age</title>
</head>
<body>
<h1>This is a Heading</h1>
<?php
$birthyear = 1995;
$age = date("Y") - $birthyear;
echo "<p>Jeg er født i " . $birthyear . ", og er i år " . $age . "år gammel.</p>";
?>
<p>This is a paragraph.</p>
</body>
</html>
|
Java
|
UTF-8
| 1,347 | 2.125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.iskycode.jeewe.adm.service;
import org.apache.commons.collections.CollectionUtils;
import org.iskycode.jeewe.adm.dao.UserDao;
import org.iskycode.jeewe.adm.entity.AdmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author phoenix
* <p>
* 用户业务处理层
*/
@Service
public class UserService {
@Autowired
UserDao userDao;
public List<AdmUser> findAll() {
return userDao.findAll(new AdmUser());
}
@SuppressWarnings("rawtypes")
public List<Map> findRolesByUserName(String username) {
return userDao.findRolesByUserName(username);
}
@SuppressWarnings("rawtypes")
public List<Map> findPermissionsByUserName(String username) {
return userDao.findPermissionsByUserName(username);
}
public AdmUser findUserByName(String username) {
AdmUser user = new AdmUser();
user.setName(username);
List<AdmUser> users = userDao.findAndByExample(user);
if (CollectionUtils.isEmpty(users)) {
return null;
}
AdmUser result = users.get(0);
return result;
}
public void save(AdmUser user) {
userDao.save(user);
}
}
|
Python
|
UTF-8
| 1,698 | 2.8125 | 3 |
[
"MIT",
"ISC"
] |
permissive
|
#!/usr/bin/python
import optparse
import time
def get_args():
parser = optparse.OptionParser()
#parser.add_option("-x", "--x_bytes", dest ="xb", help = "Recieved bytes (rx) or Transmited bytes (tx)")
parser.add_option("-d", "--dev", dest ="dev", help = "Device used in transmission (wlan0, wl01, eth0)")
parser.add_option("-t", "--time", dest ="interval", help = "Time interval used for calulation in sec")
(options, arguments) = parser.parse_args()
#if not options.xb:
# print('[-] Please specify whether rx or tx . For more details do --help ')
# return 0
if not options.dev:
print('[-] Please specify the device . For more details do --help ')
return (0,0)
elif not options.interval:
print('[-] Please specify the time interval . For more details do --help ')
return (0,0)
else:
return (options.dev, options.interval)
dev, interval = get_args()
if dev != 0 and interval !=0:
path_rx = "/sys/class/net/{}/statistics/rx_bytes".format(dev)
path_tx = "/sys/class/net/{}/statistics/tx_bytes".format(dev)
f = open(path_rx, "r")
rx_bytes_before = int(f.read())
f.close()
f = open(path_tx, "r")
tx_bytes_before = int(f.read())
f.close()
time.sleep(float(interval))
f = open(path_rx, "r")
rx_bytes_after = int(f.read())
f.close()
f = open(path_tx, "r")
tx_bytes_after = int(f.read())
f.close()
speed_rx = (rx_bytes_after-rx_bytes_before)/1000*float(interval)
speed_tx = (tx_bytes_after-tx_bytes_before)/1000*float(interval)
#print("{:.1f} kb/s".format(speed))
print("{:.1f}kb/s {:.1f}kb/s".format(speed_rx, speed_tx))
|
JavaScript
|
UTF-8
| 3,560 | 2.96875 | 3 |
[] |
no_license
|
var mysql = require("mysql");
var inquirer = require("inquirer");
// ------------------------------- CONNNECTION
var connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
port: 3306,
user: "root",
password: "rootroot",
database: "bamazon"
});
connection.connect(function (err) {
if (err) throw err;
showProducts();
});
// ------------------------------- SHOW PRODUCTS
function showProducts() {
myQuery = "select * from products"
connection.query(myQuery, function (err, res) {
for (var i = 0; i < res.length; i++) {
console.log(
i + 1 + ".) " +
"Product ID: " + res[i].item_id +
" || Product name: " + res[i].product_name +
" || Product quantity: " + res[i].stock_quantity
)
}
})
setTimeout( function() {
requestProduct()
}, 1000)
}
// ------------------------------- PRODUCT AMOUNT
function requestProduct() {
inquirer.prompt([
{
name: "productID",
type: "input",
message: "What is the ID of the product that you would like to buy?",
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
},
{
name: "productAmount",
type: "input",
message: "How many products of that kind would you like to buy?",
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
},
])
.then(function(obj) {
console.log(obj)
/*
obj = {
productID: someValue,
productAmount: someValue
} */
productID = obj.productID
productAmount = obj.productAmount
// console.log(productID)
// console.log(productAmount)
var myQuery = "select stock_quantity from products where item_id = ";
myQuery += productID;
// -------------------- QUERY
connection.query(myQuery, function(err, res) {
console.log(res)
var productsAvailable = res[0].stock_quantity;
console.log("Products available: " + productsAvailable)
if (productAmount > productsAvailable) {
console.log("There isn’t enough of that product, pick a smaller size.")
}
else {
console.log("Congrats my brother, you have purchased " + productAmount + " of the item_id: " + productID)
var productRemaining = 0;
var productRemaining = productsAvailable - productAmount;
updateProductQuantity(productID, productRemaining)
}
})
})
}
function updateProductQuantity(productID, productRemaining) {
console.log("---inside---")
console.log("-->productRemaining: " + productRemaining)
console.log("-->productID: " + productID)
var aQuery = "update products ";
aQuery += "set stock_quantity = ";
aQuery += productRemaining;
aQuery += " where item_id = ";
aQuery += productID;
console.log(aQuery)
// var aa = "update products set stock_quantity = ";
// aa += "78 ";
// aa += " where item_id = 10";
// -------------------- QUERY
connection.query(aQuery, function(err, res) {
console.log(res)
// res[0].stock_quantity = 44;
})
setTimeout(function () {
showProducts()
}, 1000)
}
|
Java
|
UTF-8
| 935 | 2.90625 | 3 |
[] |
no_license
|
public class Solution {
public boolean isValidSerialization(String preorder) {
String[] strs=preorder.split(",");
List<String> list=new ArrayList<String>();
for (int i = 0; i < strs.length; i++) {
list.add(strs[i]);
}
return isValid(list);
}
public boolean isValid(List<String> list) {
int len=list.size();
if (len==1) {
return "#".equals(list.get(0));
}
for (int i = 0; i < len-2; i++) {
if ("#".equals(list.get(i+1))&&"#".equals(list.get(i+2))) {
if ("#".equals(list.get(i))) {
return false;
}else{
list.remove(i+2);
list.remove(i+1);
list.remove(i);
list.add(i,"#");
return isValid(list);
}
}
}
return false;
}
}
|
C#
|
UTF-8
| 2,378 | 2.78125 | 3 |
[] |
no_license
|
using HotelFinder.Entities;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace HotelFinder.API.JWT
{
public class TokenHandler
{
public IConfiguration Configuration { set; get; }
public TokenHandler(IConfiguration configuration)
{
Configuration = configuration;
}
public Token CreateAccessToken(User user)
{
Token token = new Token();
var parameters = new Claim[]
{
new Claim(JwtRegisteredClaimNames.UniqueName,user.Name)
};
//Security Key'in simetriğini alıyoruz.
SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Hey. I am a secret Key. Sooo Who are you....."));
//Şifrelenmiş kimliği oluşturuyoruz.
SigningCredentials signingCredentials = new SigningCredentials(securityKey,SecurityAlgorithms.HmacSha256);
//Oluşturulacak token ayarlarını veriyoruz.
token.Expiration = DateTime.Now.AddMinutes(5);
JwtSecurityToken securityToken = new JwtSecurityToken(
issuer: "www.abc.com",
audience: "www.cba.com",
claims:parameters,//Tokenımızın içine gömdüğümüz ekstra bilgidir. Bu örnekte kullanıcı adı bilgisini tokenımıza verdik. İstersek bu bilgiyi daha sonra kullanabiliriz.
expires:token.Expiration,//Token süresi beş dakika belirlendi
notBefore:DateTime.Now,//Token üretildikten ne kadar sora devreye girsin?
signingCredentials: signingCredentials
);
//Token oluşturucu sınıfından bir örnek oluşturuyoruz.
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
//Token üretiyoruz.
token.AccessToken = tokenHandler.WriteToken(securityToken);
token.RefreshToken = CreateRefreshToken(); ;
return token;
}
public Guid CreateRefreshToken()
{
return Guid.NewGuid();
}
}
}
|
Java
|
UTF-8
| 1,691 | 2.703125 | 3 |
[] |
no_license
|
package xogame.is_complete.any_diagonal;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import xogame.is_complete.GameOver;
import xogame.models.Board;
public class IsAnyDiagonalCompleteTest {
@Test
public void the_primary_diagonal_is_complete_if_it_contains_all_ones() {
Board board = new Board(new int[] { 1, 2, 0, 2, 1, 2, 0, 0, 1 });
assertTrue(GameOver.isAnyDiagonalComplete(board));
}
@Test
public void the_primary_diagonal_is_complete_if_it_contains_all_twos() {
Board board = new Board(new int[] { 2, 1, 0, 1, 2, 0, 2, 0, 2 });
assertTrue(GameOver.isAnyDiagonalComplete(board));
}
@Test
public void the_primary_diagonal_is_not_complete_if_it_contains_all_zeros() {
Board board = new Board(new int[] { 0, 0, 0, 0, 0, 2, 0, 1, 0 });
assertFalse(GameOver.isAnyDiagonalComplete(board));
}
@Test
public void the_secondary_diagonal_is_complete_if_it_contains_all_ones() {
Board board = new Board(new int[] { 2, 1, 1, 2, 1, 0, 1, 1, 0 });
assertTrue(GameOver.isAnyDiagonalComplete(board));
}
@Test
public void the_secondary_diagonal_is_complete_if_it_contains_all_twos() {
Board board = new Board(new int[] { 1, 2, 2, 1, 2, 1, 2, 2, 0 });
assertTrue(GameOver.isAnyDiagonalComplete(board));
}
@Test
public void the_secondary_diagonal_is_not_complete_if_it_contains_all_zeros() {
Board board = new Board(new int[] { 0, 0, 0, 0, 0, 2, 0, 0, 1 });
assertFalse(GameOver.isAnyDiagonalComplete(board));
}
}
|
C++
|
UTF-8
| 3,494 | 2.875 | 3 |
[] |
no_license
|
#include "ScrambleFind.h"
#include "..\ApplicationManager.h"
#include "..\GUI\Output.h"
ScrambleFind::ScrambleFind(ApplicationManager * pApp) :Action(pApp)
{
validCount = 0;
inValidCount = 0;
}
ScrambleFind::~ScrambleFind()
{
}
//The game logic happens here
void ScrambleFind::Execute()
{
pManager->DeSelectAllFigures(); //precatious act not needed except an error from other class occured
Output* pOut = pManager->GetOutput();
FiguresMaxID = CFigure::getCount(); //save it to restore after finish
pManager->ToLeftHalf(); //shrinks figures to left half of screen
gameFigures = pManager->createCopyOfFigures(); //create copy of images
pManager->RandomizePositionsRight(gameFigures); //randomize their positions in the right of screen
pManager->UpdateInterface(gameFigures); //over loaded function to draw original and copied images
figuresCount = pManager->GetFigureCount();
pOut->PrintMessage("Choose fugure like selected, Valide answers " + to_string(validCount) + ", InValide answers " + to_string(inValidCount));
//Main game loop
while (validCount < figuresCount) {
CFigure* Choice1;
CFigure* Choice2;
Choice1 = pManager->getRandomFigure();
pManager->UpdateInterface(gameFigures);
//getting the user chosen shape and if he chooses another action
do {
ReadActionParameters();
Choice2 = selectedFigure;
} while (Choice2 == NULL);
//responsible of reinitializing process and start the loop from beginning
if (restartGame)
{
RestartGame();
pOut->PrintMessage("Game Restarted");
continue;
}
//responsible for the breaking the loop only
if (endGame)
{
break;
}
if (Choice2->getID() == Choice1->getID()) {
Choice1->setVisible(false);
Choice2->setVisible(false);
validCount++;
}
else {
Choice1->SetSelected(false);
inValidCount++;
}
pOut->PrintMessage("Choose fugure like selected, Valide answers " + to_string(validCount) + ", InValide answers " + to_string(inValidCount));
pManager->UpdateInterface(gameFigures);
}
pOut->PrintMessage("Total grade = " + to_string(((float)validCount / (validCount + inValidCount)) * 100) + '%');
//block of code responsible of getting the shapes as the game started
pManager->ShowAllFigures();
pManager->RestoreFromHalf();
CFigure::setCount(FiguresMaxID); //restore everything
pManager->deleteFigureArray(gameFigures);
pManager->DeSelectAllFigures();
}
//the read action parameters are resbonsible for knowing the
//selected figure from copied figures
//also determine if the user want to (End / Restart) game
void ScrambleFind::ReadActionParameters()
{
int x, y;
Input* pIn = pManager->GetInput();
Output* pOut = pManager->GetOutput();
restartGame = endGame = false;
pIn->GetPointClicked(x, y);
if (y < UI.ToolBarHeight) {
if (x / UI.MenuItemWidth == ITM_Find) {
restartGame = true;
return;
}
else if (x / UI.MenuItemWidth <= ITM_EXIT2) {
endGame = true;
return;
}
}
selectedFigure = pManager->GetFigure(x, y, gameFigures);
}
//procedures of restarting the game is
//to get scores to zero
//show copied figures then randomize their place again
//delete the array of copied figures
void ScrambleFind::RestartGame()
{
validCount = 0;
inValidCount = 0;
pManager->ShowAllFigures();
pManager->deleteFigureArray(gameFigures);
pManager->DeSelectAllFigures();
gameFigures = pManager->createCopyOfFigures();
pManager->RandomizePositionsRight(gameFigures);
pManager->UpdateInterface(gameFigures);
}
|
JavaScript
|
UTF-8
| 2,231 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Require the contact model
User = require('../models/user');
Contact = require('../models/contact');
// Use body-parser middleware
router.use(bodyParser.json());
// API router to GET all users
router.get('/', function(req, res) {
User.getUsers(function(err, users) {
if (err) {
throw err;
}
res.json(users)
});
});
// API router to GET one user by id
router.get('/:_id', function(req, res) {
User.getUserById(req.params._id, function(err, user) {
if (err) {
throw err;
}
res.status(200).json(user);
});
});
// API router to POST a user
router.post('/', function(req, res) {
var newUser = req.body;
if (!newUser.name || !newUser.email || !newUser.password) {
res.status(400).json({
"error": "Missing required paramaters"
});
} else {
User.addUser(newUser, function(err, newUser) {
if (err) {
throw err;
}
res.status(200).json(newUser);
});
}
});
// API router to PUT a user
router.put('/:_id', function(req, res) {
var id = req.params._id;
var updateUser = req.body;
if (!updateUser.name || !updateUser.email || !updateUser.password) {
res.status(400).json({
"error": "Missing required paramaters"
});
} else {
User.updateUserById(id, updateUser, {}, function(err, updateUser) {
if (err) {
throw err;
}
res.status(200).json(updateUser);
});
}
});
// API router to DELETE a user
router.delete('/:_id', function(req, res) {
var id = req.params._id;
User.deleteUsertById(id, function(err, updateUser) {
if (err) {
throw err;
}
res.status(200).json(req.params._id);
});
});
// GET User Contact List
router.get('/:_id/contacts', function(req, res) {
var id = req.params._id;
User.getUserById(id, function(err, user) {
if (err) {
throw err;
}
res.status(200).send(user.contactList);
});
});
// GET a User Contact
router.get('/:_userId/contacts/:_contactId', function(req, res) {
var userId = req.params._userId;
var contactId = req.params._contactId;
Contact.getContactById(contactId, function(err, contact) {
if (err) {
throw err;
}
res.status(200).json(contact);
});
});
module.exports = router;
|
C++
|
UTF-8
| 4,981 | 2.828125 | 3 |
[] |
no_license
|
#include <exception>
#include <algorithm>
#include <bitset>
#include "include/parser.h"
namespace nand2tetris{
Parser::Parser(std::string input_file){
if(input_file.substr(input_file.find_last_of('.')+1)!="asm"){
std::cout << "Wrong file type" << std::endl;
exit(0);
}
this->file_name = input_file;
// this->in_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try{
this->in_file.open(this->file_name);
}
catch(const std::system_error& e){
std::cerr << e.code().message() << std::endl;
}
std::string output_file_name = input_file.substr(0, input_file.find_last_of('.')) + std::string(".hack");
this->out_file.open(output_file_name);
if(!this->out_file.is_open()){
std::cout << "Output file open fails" << std::endl;
exit(1);
}
this->code_dict = Code();
this->symbol_table = SymbolTable();
}
Parser::~Parser(){
this->in_file.close();
this->out_file.close();
}
bool Parser::HasMoreCommand(){
int len = this->in_file.tellg();
std::string dummy;
std::getline(this->in_file, dummy);
bool result = !this->in_file.eof();
this->in_file.seekg(len, std::ios_base::beg);
return result;
}
void Parser::Advance(){
std::string command;
std::getline(this->in_file, command);
command = this->Preprocess(command);
if(command.empty()){
return;
}
if(command[0] == '@'){
// A command
std::string address_str = command.substr(1);
int address_dec;
if(this->ContainSymbol(address_str)){
if(this->symbol_table.Contains(address_str)){
address_dec = this->symbol_table.GetAddress(address_str);
}else{
address_dec = this->symbol_table.GetDataAddress();
this->symbol_table.AddDataAddress();
this->symbol_table.AddEntry(address_str, address_dec);
}
}else{
address_dec = std::stoi(address_str);
}
std::string machine_code = std::bitset<16>(address_dec).to_string();
this->out_file << machine_code << std::endl;
}else if(command[0] == '('){
// L command
// std::string symbol = this->Symbol(command);
// int address_dec = this->symbol_table.GetInstructionAddress();
// this->symbol_table.AddEntry(symbol, address_dec);
return;
}else{
// C command
std::string machine_code = "111";
std::string dest_code = this->code_dict.DestinationCode(this->Destination(command));
std::string comp_code = this->code_dict.ComputationCode(this->Computation(command));
std::string jump_code = this->code_dict.JumpCode(this->Jump(command));
machine_code = machine_code + comp_code + dest_code + jump_code;
this->out_file << machine_code << std::endl;
}
}
void Parser::BuildInstructionTable(){
std::ifstream temp_steam(this->file_name);
std::string command;
while(std::getline(temp_steam, command)){
command = this->Preprocess(command);
if(command.empty()){
continue;
}
if(command[0] == '('){
std::string symbol = this->Symbol(command);
this->symbol_table.AddEntry(symbol, this->symbol_table.GetInstructionAddress());
}else{
this->symbol_table.AddInstructionAddress();
}
}
temp_steam.close();
}
std::string Parser::Preprocess(std::string command){
// Remove all space
command.erase(std::remove(command.begin(), command.end(), '\n'), command.end());
command.erase(std::remove(command.begin(), command.end(), '\r'), command.end());
command.erase(std::remove(command.begin(), command.end(), ' '), command.end());
// Remove comment
auto position = command.find("//");
if(position != std::string::npos){
return command.substr(0, position);
}
return command;
}
std::string Parser::Destination(std::string command) {
if(command.find('=')!=std::string::npos){
std::string dest_str = command.substr(0, command.find_first_of('='));
return dest_str;
}else{
return std::string("null");
}
}
std::string Parser::Computation(std::string command){
if(command.find('=')!=std::string::npos){
return command.substr(command.find_first_of('=')+1);
}else{
return command.substr(0, command.find_first_of(';'));
}
}
std::string Parser::Jump(std::string command){
if(command.find(';')!=std::string::npos){
std::string jump_str = command.substr(command.find_first_of(';')+1);
return jump_str;
}else{
return std::string("null");
}
}
bool Parser::ContainSymbol(std::string command){
return !std::all_of(command.begin(), command.end(), ::isdigit);
}
std::string Parser::Symbol(std::string command){
// return symbol only for L-command
return command.substr(1, command.length()-2);
}
}// namespace name
|
Python
|
UTF-8
| 2,603 | 2.515625 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
##########################################################
# testStreamline.py
# Author: Akito D. Kawamura
# This program tests my streamline.py for 3D.
#
# This program is published under BSD 3-Clause License.
# This program is a beta version.
# Please use this program under your responsibility.
##########################################################
import streamline as strl
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
v0 = 1.0
B0 = 1.0
sx = 10
sy = 10
sz = 10
dx = 1.0
dy = 1.0
dz = 1.0
xx = np.arange(sx) * dx - sx * dx * 0.5
yy = np.arange(sy) * dy - sy * dy * 0.5
zz = np.arange(sz) * dz - sz * dz * 0.5
mesh_yy, mesh_zz, mesh_xx = np.meshgrid(zz,yy,xx)
Bx = np.zeros((sz,sy,sx))
By = B0*np.sin(np.pi*mesh_xx*0.5)
Bz = B0*np.cos(np.pi*mesh_xx*0.5)
vx = v0 * 0.5 * np.ones((sz,sy,sx))
vy = v0 * 0.5 * np.sin(np.pi*mesh_xx*0.5)
vz = v0 * 0.5 * np.cos(np.pi*mesh_xx*0.5)
mySeed = np.array([-4.0, 0.0, 0.0])
fig = plt.figure(figsize=(8,8))
ax = fig.gca(projection='3d')
qvr = ax.quiver(mesh_xx,mesh_yy,mesh_zz,vx,vy,vz)
tt = 0.2
new_pos = mySeed
strl_x, strl_y, strl_z = strl.getStreamline(xx,yy,zz,Bx,By,Bz, seed=new_pos)
#print("strl = {0}, {1}".format(strl_x,strl_y))
ax.plot(strl_x,strl_y,strl_z, "r--")
for ii in range(50):
old_pos = new_pos
# Linear Interpolation
id_x_l = np.where((old_pos[0]>=xx))[0][-1]
id_y_l = np.where((old_pos[1]>=yy))[0][-1]
id_z_l = np.where((old_pos[2]>=zz))[0][-1]
id_x_h = np.where((old_pos[0]<xx))[0][0]
id_y_h = np.where((old_pos[1]<yy))[0][0]
id_z_h = np.where((old_pos[2]<zz))[0][0]
dx = xx[id_x_h]-xx[id_x_l]
dy = yy[id_y_h]-yy[id_y_l]
dz = zz[id_z_h]-zz[id_z_l]
wg_x_l = (xx[id_x_h]-old_pos[0])/dx
wg_y_l = (yy[id_y_h]-old_pos[1])/dy
wg_z_l = (zz[id_z_h]-old_pos[2])/dy
weight = np.array([wg_x_l,1.-wg_x_l])
weight = np.array([wg_y_l*weight,(1.-wg_y_l)*weight])
weight = np.array([wg_z_l*weight,(1.-wg_z_l)*weight])
curr_vx = np.sum(vx[id_z_l:id_z_h+1,id_y_l:id_y_h+1,id_x_l:id_x_h+1]*weight)
curr_vy = np.sum(vy[id_z_l:id_z_h+1,id_y_l:id_y_h+1,id_x_l:id_x_h+1]*weight)
curr_vz = np.sum(vz[id_z_l:id_z_h+1,id_y_l:id_y_h+1,id_x_l:id_x_h+1]*weight)
# update position and plot
new_pos = old_pos + tt * np.array([curr_vx,curr_vy,curr_vz])
strl_x, strl_y, strl_z = strl.getStreamline(xx,yy,zz,Bx,By,Bz, seed=new_pos)
ax.plot(strl_x,strl_y,strl_z, "g--")
ax.plot([new_pos[0],old_pos[0]],[new_pos[1],old_pos[1]],[new_pos[2],old_pos[2]],"ro")
#ax.streamplot(xx,yy,vx,vy)
plt.pause(0.1)
plt.show()
|
Java
|
UTF-8
| 33,626 | 1.820313 | 2 |
[] |
no_license
|
package ch.ethz.globis.isk.Zoo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.util.Collection;
import java.util.Collections;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import ch.ethz.globis.isk.domain.ConferenceEdition;
import ch.ethz.globis.isk.domain.DomainObject;
import ch.ethz.globis.isk.domain.InProceedings;
import ch.ethz.globis.isk.domain.Person;
import ch.ethz.globis.isk.domain.Publication;
import ch.ethz.globis.isk.domain.zoodb.ZooConference;
import ch.ethz.globis.isk.domain.zoodb.ZooConferenceEdition;
import ch.ethz.globis.isk.domain.zoodb.ZooInProceedings;
import ch.ethz.globis.isk.domain.zoodb.ZooPerson;
import ch.ethz.globis.isk.domain.zoodb.ZooProceedings;
import ch.ethz.globis.isk.domain.zoodb.ZooPublication;
import ch.ethz.globis.isk.domain.zoodb.ZooPublisher;
import ch.ethz.globis.isk.domain.zoodb.ZooSeries;
import ch.ethz.globis.isk.util.Pair;
public class Panel extends javax.swing.JPanel {
String filter = "";
String field1 = "";
String field2 = "";
public Panel() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jPanel4 = new javax.swing.JPanel();
jSeparator8 = new javax.swing.JSeparator();
jTextField16 = new javax.swing.JTextField();
jTextField17 = new javax.swing.JTextField();
jPanel5 = new javax.swing.JPanel();
jButton9 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jTextField6 = new javax.swing.JTextField();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jSeparator7 = new javax.swing.JSeparator();
jButton16 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
setBackground(new java.awt.Color(97, 212, 195));
setForeground(new java.awt.Color(255, 255, 255));
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBackground(new java.awt.Color(36, 47, 65));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(379, 0, -1, 529));
jPanel2.setBackground(new java.awt.Color(36, 47, 65));
jLabel9.setFont(new java.awt.Font("Century Gothic", 0, 13)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setIcon(new javax.swing.ImageIcon("/Users/panuyabalasuntharam/Desktop/0001.png")); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel9)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel9)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 190, 550));
jLabel1.setFont(new java.awt.Font("Century Gothic", 1, 30)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Publication Search");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 20, 300, 47));
add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1057, 243, 300, 0));
jPanel4.setBackground(new java.awt.Color(36, 47, 65));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jSeparator8.setForeground(new java.awt.Color(255, 255, 255));
jPanel4.add(jSeparator8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 290, -1));
jTextField16.setBackground(new java.awt.Color(36, 47, 65));
jTextField16.setFont(new java.awt.Font("Century Gothic", 0, 10)); // NOI18N
jTextField16.setForeground(new java.awt.Color(255, 255, 255));
jTextField16.setText("Enter");
jTextField16.setBorder(null);
jTextField16.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextField16MouseClicked(evt);
}
});
jTextField16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField16ActionPerformed(evt);
}
});
jPanel4.add(jTextField16, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 70, 120, 20));
jTextField17.setBackground(new java.awt.Color(36, 47, 65));
jTextField17.setFont(new java.awt.Font("Century Gothic", 0, 10)); // NOI18N
jTextField17.setForeground(new java.awt.Color(255, 255, 255));
jTextField17.setText("Enter");
jTextField17.setBorder(null);
jTextField17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextField17MouseClicked(evt);
}
});
jTextField17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField17ActionPerformed(evt);
}
});
jPanel4.add(jTextField17, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, 140, 20));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel4.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 480, -1, 40));
jButton9.setText("No of Publications per year");
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jPanel4.add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 210, 230, -1));
jButton14.setText("Search Publisher");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
jPanel4.add(jButton14, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 300, 230, -1));
jButton15.setText("Shortest Path between 2 authors");
jButton15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton15ActionPerformed(evt);
}
});
jPanel4.add(jButton15, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 240, 230, -1));
jButton19.setText("Search Publication");
jButton19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton19ActionPerformed(evt);
}
});
jPanel4.add(jButton19, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 270, 230, -1));
add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 0, 340, 550));
jTextField6.setBackground(new java.awt.Color(97, 212, 195));
jTextField6.setFont(new java.awt.Font("Century Gothic", 0, 10)); // NOI18N
jTextField6.setForeground(new java.awt.Color(255, 255, 255));
jTextField6.setText("Enter filter ");
jTextField6.setBorder(null);
jTextField6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextField6MouseClicked(evt);
}
});
jTextField6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField6ActionPerformed(evt);
}
});
add(jTextField6, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 70, 210, 26));
jButton3.setText("No of authors of a conference");
add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 390, 230, -1));
jButton4.setText("Search author/ editors");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 480, 230, -1));
jButton5.setText("Search Edition");
add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 150, 230, -1));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("Search InProceeding");
add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 180, 230, -1));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton7.setText("Search Proceeding");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 210, 230, -1));
jButton8.setText("Search Author");
add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 240, 230, -1));
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton10.setText("Search Publisher");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
add(jButton10, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 300, 230, -1));
jButton11.setText("Search Series");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
add(jButton11, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 330, 230, -1));
jButton12.setText("Find average number of authors");
add(jButton12, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 360, 230, -1));
jButton13.setText("Search Publication");
jButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton13ActionPerformed(evt);
}
});
add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 270, 230, -1));
jSeparator7.setForeground(new java.awt.Color(255, 255, 255));
add(jSeparator7, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 100, 210, -1));
jButton16.setText("Search Conference");
jButton16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton16ActionPerformed(evt);
}
});
add(jButton16, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 120, 230, -1));
jButton17.setText("Search Co-Authors");
jButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton17ActionPerformed(evt);
}
});
add(jButton17, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 420, 230, -1));
jButton18.setText("No of publications in conference");
jButton18.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton18ActionPerformed(evt);
}
});
add(jButton18, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 450, 230, -1));
}// </editor-fold>
private void jTextField16MouseClicked(java.awt.event.MouseEvent evt) {
}
private void jTextField16ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField17MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jTextField17ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField6MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooPerson> collection = db.getWithFilter(ZooPerson.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooPublisher> collection = db.getWithFilter(ZooPublisher.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooConferenceEdition> collection = db.getWithFilter(ZooConferenceEdition.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooInProceedings> collection = db.getWithFilter(ZooInProceedings.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooSeries> collection = db.getWithFilter(ZooSeries.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooProceedings> collection = db.getWithFilter(ZooProceedings.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooPublication> collection = db.getWithFilter(ZooPublication.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooConference> collection = db.getWithFilter(ZooConference.class, "");
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {
Pair<Object[][], String[]> objectsAndTitle = null;
Database db = new Database("database", false);
try {
db.open();
Collection<ZooPerson> collection = db.getCoAuthors(jTextField6.getText());
objectsAndTitle = getObjectsAndTitle(collection, filter);
DefaultTableModel model = new DefaultTableModel(objectsAndTitle.a, objectsAndTitle.b);
openNewTable(model);
} catch (Exception e) {
System.out.println(e.getMessage());
final String error = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(error);
PanelErrorMessage panel = new PanelErrorMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
} finally {
db.close();
}
}
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JButton jButton20;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JSeparator jSeparator8;
private javax.swing.JTextField jTextField16;
private javax.swing.JTextField jTextField17;
private javax.swing.JTextField jTextField6;
// End of variables declaration
private Pair<Object[][], String[]> getObjectsAndTitle(Collection<?> collection, String filter) {
if (collection.isEmpty())
return null;
Object[][] objects = new Object[collection.size()][];
int i = 0;
for (Object object : collection) {
if (object instanceof ZooPublication) {
ZooPublication publication = (ZooPublication) object;
String authors = "";
for (Person author : publication.getAuthors()) {
authors += author.getName() + ", ";
}
if (authors.length() > 2)
authors = authors.substring(0, authors.length() - 2);
if ((publication.getTitle() != null && publication.getTitle().contains(filter))
|| (Integer.toString(publication.getYear()).contains(filter))
|| (authors.contains(filter)))
objects[i++] = new Object[]{ publication.getTitle(), publication.getYear(), authors };
} else if (object instanceof ZooConference) {
ZooConference conference = (ZooConference) object;
String editions = "";
for (ConferenceEdition edition : conference.getEditions()) {
editions += edition.getYear() + ", ";
}
if (editions.length() > 2)
editions = editions.substring(0, editions.length() - 2);
if ((conference.getName() != null && conference.getName().contains(filter))
|| (editions.contains(filter)))
objects[i++] = new Object[]{ conference.getName(), editions };
} else if (object instanceof ZooConferenceEdition) {
ZooConferenceEdition conferenceEdition = (ZooConferenceEdition) object;
if ((conferenceEdition.getConference() != null && conferenceEdition.getConference().getName() != null && conferenceEdition.getConference().getName().contains(filter))
|| (Integer.toString(conferenceEdition.getYear()).contains(filter)))
objects[i++] = new Object[]{ conferenceEdition.getConference().getName(), conferenceEdition.getYear() };
} else if (object instanceof ZooPerson) {
ZooPerson person = (ZooPerson) object;
String publications = "";
for (Publication publication : person.getAuthoredPublications()) {
publications += publication.getTitle() + ", ";
}
for (Publication publication : person.getEditedPublications()) {
publications += publication.getTitle() + ", ";
}
if (publications.length() > 2)
publications = publications.substring(0, publications.length() - 2);
if ((person.getName() != null && person.getName().contains(filter))
|| (publications.contains(filter)))
objects[i++] = new Object[]{ person.getName(), publications };
} else if (object instanceof ZooPublisher) {
ZooPublisher publisher = (ZooPublisher) object;
String publications = "";
for (Publication publication : publisher.getPublications()) {
publications += publication.getTitle() + ", ";
}
if (publications.length() > 2)
publications = publications.substring(0, publications.length() - 2);
if ((publisher.getName() != null && publisher.getName().contains(filter))
|| (publications.contains(filter)))
objects[i++] = new Object[]{ publisher.getName(), publications };
} else if (object instanceof ZooSeries) {
ZooSeries series = (ZooSeries) object;
String publications = "";
for (Publication publication : series.getPublications()) {
publications += publication.getTitle() + ", ";
}
if (publications.length() > 2)
publications = publications.substring(0, publications.length() - 2);
if ((series.getName() != null && series.getName().contains(filter))
|| (publications.contains(filter)))
objects[i++] = new Object[]{ series.getName(), publications };
}
}
String[] title = null;
if (collection.iterator().next() instanceof ZooPublication)
title = new String[] { "Title", "Year", "Authors" };
else if (collection.iterator().next() instanceof ZooConference)
title = new String[] { "Name", "Editions" };
else if (collection.iterator().next() instanceof ZooConferenceEdition)
title = new String[] { "Conference", "Edition" };
else if (collection.iterator().next() instanceof ZooPerson)
title = new String[] { "Name", "Publications" };
else if (collection.iterator().next() instanceof ZooPublisher)
title = new String[] { "Name", "Publications" };
else if (collection.iterator().next() instanceof ZooSeries)
title = new String[] { "Name", "Publications" };
return new Pair<Object[][], String[]> (objects, title);
}
private void openNewTable(DefaultTableModel model) {
//////////////Table/////////
JFrame frame = new JFrame("Result");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(new java.awt.Color(97, 212, 195));
panel.setForeground(new java.awt.Color(255, 255, 255));
panel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
JTable table = new JTable();
table.setModel(model);
table.setFont(new java.awt.Font("Century Gothic", 0, 12));
table.setGridColor(new java.awt.Color(97, 212, 195));
// table.setBackground(new java.awt.Color(97, 212, 195));
table.getTableHeader().setOpaque(false);
table.getTableHeader().setBackground(new java.awt.Color(97, 212, 195));
table.getTableHeader().setForeground(new java.awt.Color(255, 255, 255));
table.getTableHeader().setBorder(null);
table.getTableHeader().setFont(new java.awt.Font("Century Gothic", 0, 12));
Container container = getRootPane();
container.setLayout(new BorderLayout());
container.setBackground(new java.awt.Color(97, 212, 195));
container.add(table.getTableHeader(), BorderLayout.PAGE_START);
container.add(table, BorderLayout.CENTER);
frame.add(new JScrollPane(table));
frame.pack();
// frame.add(panel);
frame.setVisible(true);
}
}
|
Java
|
UTF-8
| 3,513 | 1.953125 | 2 |
[] |
no_license
|
package Hibernate.model;
// Generated 2015�~6��23�� �U��07:41:21 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
/**
* Shop generated by hbm2java
*/
public class Shop implements java.io.Serializable {
private int shopId;
private int shopName;
private String shopType;
private String shopRemark;
private String shopStatus;
private Set<Lost> losts = new HashSet<Lost>(0);
private Set<Supplierorder> supplierorders = new HashSet<Supplierorder>(0);
private Set<Supplierpreorder> supplierpreorders = new HashSet<Supplierpreorder>(
0);
private Set<Logisticsorder> logisticsorders = new HashSet<Logisticsorder>(0);
private Set<Sales> saleses = new HashSet<Sales>(0);
private Set<Inventory> inventories = new HashSet<Inventory>(0);
public Shop() {
}
public Shop(int shopId, int shopName, String shopType, String shopStatus) {
this.shopId = shopId;
this.shopName = shopName;
this.shopType = shopType;
this.shopStatus = shopStatus;
}
public Shop(int shopId, int shopName, String shopType, String shopRemark,
String shopStatus, Set<Lost> losts,
Set<Supplierorder> supplierorders,
Set<Supplierpreorder> supplierpreorders,
Set<Logisticsorder> logisticsorders, Set<Sales> saleses,
Set<Inventory> inventories) {
this.shopId = shopId;
this.shopName = shopName;
this.shopType = shopType;
this.shopRemark = shopRemark;
this.shopStatus = shopStatus;
this.losts = losts;
this.supplierorders = supplierorders;
this.supplierpreorders = supplierpreorders;
this.logisticsorders = logisticsorders;
this.saleses = saleses;
this.inventories = inventories;
}
public int getShopId() {
return this.shopId;
}
public void setShopId(int shopId) {
this.shopId = shopId;
}
public int getShopName() {
return this.shopName;
}
public void setShopName(int shopName) {
this.shopName = shopName;
}
public String getShopType() {
return this.shopType;
}
public void setShopType(String shopType) {
this.shopType = shopType;
}
public String getShopRemark() {
return this.shopRemark;
}
public void setShopRemark(String shopRemark) {
this.shopRemark = shopRemark;
}
public String getShopStatus() {
return this.shopStatus;
}
public void setShopStatus(String shopStatus) {
this.shopStatus = shopStatus;
}
public Set<Lost> getLosts() {
return this.losts;
}
public void setLosts(Set<Lost> losts) {
this.losts = losts;
}
public Set<Supplierorder> getSupplierorders() {
return this.supplierorders;
}
public void setSupplierorders(Set<Supplierorder> supplierorders) {
this.supplierorders = supplierorders;
}
public Set<Supplierpreorder> getSupplierpreorders() {
return this.supplierpreorders;
}
public void setSupplierpreorders(Set<Supplierpreorder> supplierpreorders) {
this.supplierpreorders = supplierpreorders;
}
public Set<Logisticsorder> getLogisticsorders() {
return this.logisticsorders;
}
public void setLogisticsorders(Set<Logisticsorder> logisticsorders) {
this.logisticsorders = logisticsorders;
}
public Set<Sales> getSaleses() {
return this.saleses;
}
public void setSaleses(Set<Sales> saleses) {
this.saleses = saleses;
}
public Set<Inventory> getInventories() {
return this.inventories;
}
public void setInventories(Set<Inventory> inventories) {
this.inventories = inventories;
}
}
|
Java
|
UTF-8
| 250 | 3.0625 | 3 |
[] |
no_license
|
package Week3;
public class ReverseBasics {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("ABC");
sb.reverse(); // execute reverse on sb
System.out.println(sb); // CBA
}
}
|
Python
|
UTF-8
| 2,252 | 2.90625 | 3 |
[] |
no_license
|
__author__ = 'apurvapawar'
from random import randint
from Models import Item
from Config import info
MAX_ITEMS=5
CARD_PROBABILITY=75
LEGAL_AGE=21
AGE_PROOF_PROBABILITY=80
MAX_CASH_IN_HAND=700
class Customer:
def __init__(self):
self.isAdult = False
self.hasAgeProof = False
self.hasDebitOrCreditCard = False
self.cashOnHand = 0
self.items = []
self.timestamp = None
self.generate_customer()
def generate_items(self):
total = randint(1, MAX_ITEMS)
for x in range(0, total):
item = Item.Item()
self.items.append(item)
def generate_customer(self):
if randint(0, 100) > CARD_PROBABILITY:
self.hasDebitOrCreditCard = True
if randint(0, 80) > LEGAL_AGE:
self.isAdult = True
if randint(0, 100) > 100 - AGE_PROOF_PROBABILITY:
self.hasAgeProof = True
self.cashOnHand = randint(0, MAX_CASH_IN_HAND)
self.generate_items()
def is_adult(self):
return self.isAdult
def has_age_proof(self):
return self.hasAgeProof
def has_debit_or_credit_card(self):
return self.hasDebitOrCreditCard
def get_cash_on_hand(self):
return self.cashOnHand
def get_items(self):
return self.items
def get_timestamp(self):
return self.timestamp
def set_adult(self, is_adult):
self.isAdult = is_adult
def set_has_age_proof(self, has_age_proof):
self.hasAgeProof = has_age_proof
def set_debit_or_credit(self, debit_or_credit_card):
self.hasDebitOrCreditCard = debit_or_credit_card
def set_cash_in_hand(self, cash_in_hand):
self.cashOnHand = cash_in_hand
def set_items(self, items):
self.items = items
def set_timestamp(self, t):
self.timestamp = t
def object_decoder(self, obj):
self.isAdult = obj['isAdult']
self.hasAgeProof = obj['hasAgeProof']
self.hasDebitOrCreditCard = obj['hasDebitOrCreditCard']
self.cashOnHand = obj['cashOnHand']
for item_json in obj['items']:
item = Item.Item()
item.decode_from_json(item_json)
self.items.append(item)
|
Markdown
|
UTF-8
| 27,541 | 2.578125 | 3 |
[] |
no_license
|
# Image Instance Segmentation with Mask R-CNN
---
# Abstract
Deep Learning 기술을 Computer Vision분야에 적용함으로써 많은 전문적인 분야들이 파생되었다. classification, segmentation, object detection, GAN 등이 이에 해당하는데, 특히 segmentation과 object detection을 접목해서 성능을 높인 ‘Mask R-CNN’ 모델을 깊이 연구하기로 한다. 구체적인 사항으로는 Mask R-CNN의 논문을 리뷰하고 토의하는 방식을 통해 모델을 이해한다. 그리고 Keras로 구현된 오픈소스를 활용하여 모델을 사용하고 성능을 평가한다.
# Object Detection
<img src="https://i.imgur.com/dXc6g6c.png" width="100%">
Mask R-CNN을 이해하기 위해서는 그 기저에 깔린 Object Detection과 Segmentation이 무엇인지 먼저 알 필요가 있다. 위 그림을 살펴보자.<br>
먼저 Semantic Segmentation의 경우, 각각의 픽셀에 대하여 해당 픽셀이 어떤 클래스에 속하는지를 분류한다. 위 그림의 경우 각 픽셀이 GRASS, CAT, TREE, SKY 중에 어떤 것에 해당하는지를 분류하고 값을 다르게 매긴 것을 확인할 수 있다.<br>
Classification 그리고 Localization의 경우, Classification은 단순히 사진 속의 객체가 어떤 클래스를 의미하는지를 분류하고, Localization은 그 객체의 Bounding Box를 추출해낸다. 이 때 Classification은 분류 문제에 해당하고, Localization은 회귀 문제에 해당한다. 단일 객체만을 분류 및 Bounding Box를 할 수 있다는 것이 특징이다.<br>
Object Detection의 경우, 여러 객체에 대하여 Classification과 Bounding Box를 추출해낸다. 특히 위의 그림처럼 같은 클래스(DOG)라도 각자 Classification 및 Bounding Box를 추출해낸다는 것이 특징이다. 따라서 앞의 문제에 비해 고난이도의 문제라고 할 수 있다.<br>
마지막으로 Instance Segmentation의 경우, 모든 객체(마찬가지로 같은 클래스라도 각자 수행)에 대하여 Classification 및 Bounding Box를 진행하고, 여기서 더 나아가 각 Bounding Box내에 Segmentation을 수행한다. 따라서 위의 그림처럼 클래스를 넘어서 모든 객체를 Classification하고 Segmentation한 결과를 확인할 수 있다. 우리가 살펴볼 Mask R-CNN은 이에 해당한다.
Mask R-CNN을 잘 이해하기 위해서는 결국 그 기저에 깔린 수많은 내용들을 이해해야 할 것이다. 이 모델은 갑자기 튀어나온 것이 아니라 사실 Object Detection을 위해 만들어진 모델에서 출발했다. 따라서 R-CNN 시리즈 모델이라고도 할 수 있는, R-CNN, Fast R-CNN, Faster R-CNN, Mask R-CNN의 주요 특징들과 변천과정을 이해한다면 Mask R-CNN을 더욱 잘 이해할 수 있을 것이다.
# R-CNN(2013)
### Model
<img src="https://i.imgur.com/HIpL2ks.png" width="100%">
<img src="https://i.imgur.com/jrU53ke.png" width="100%">
R-CNN의 작동원리와 구조는 위 두 그림과 같다.<br>
먼저 Input Image에서 약 2000여장의 이미지를 'Selective Search' 알고리즘을 통해 추출한다. 이 알고리즘에 대한 자세한 내용은 아래에서 설명한다. 이 이미지는 우리가 관심있어하는 정보이기에 'RoI(Region of Interest)'라고 부른다. 추출한 RoI를 CNN 모델에 입력하기 위해 Input Size를 동일하게 맞춰준다. 이 과정을 'Warp'이라고 한다. 그리고 CNN 모델은 2개의 연산으로 나뉘게 되는데, 하나는 분류를 위한 Classification이고, 나머지 하나는 Bounding Box를 정교하게 추출하기 위한 Regression이다. Bounding Box Regression은 Neural Network로 구성되어 있는 반면, Classification은 SVM이라는 다른 모델을 사용한다. 따라서 CNN 모델의 마지막 feature map을 SVM에 적용하여 Classification을 수행한다.
### Selective Search
<img src="https://i.imgur.com/V2dnlCS.png" width="100%">
Selective Search란 Object Detection에서 입력된 이미지의 후보 영역을 추천할 때 사용되었던 방법으로 R-CNN 등의 논문들이 탁월한 성능을 보여주면서 주목받게 되었다. 특히 이는 2가지 방법을 조합하여 수행하는데, Exhaustive Search와 Segmentation이 이에 해당한다. 전자의 경우 모든 가능한 객체의 위치를 찾아내는 것을 의미하고, 후자의 경우 이미지의 구조적 특징(색상, 무늬, 크기, 모양)을 사용하여 후보 영역을 추출하는 것을 의미한다.
<img src="https://i.imgur.com/71hypJX.png" width="100%">
알고리즘은 다음과 같은 방식으로 수행된다.<br><br>
1. Efficient Graph-Based Image Segmentation(Felzenszwalb)을 사용하여 초기 후보 영역을 다양한 크기와 비율로 생성한다.
2. 그리디 알고리즘을 통해 비슷한 영역을 반복적으로 통합한다.
* 처음에 모든 영역에 대해 유사도를 계산하여 similarity set S를 생성한다.
* S에서 가장 큰 유사도 값을 가진 r(i), r(j)에 대해 통합한다.
* r(i), r(j)의 유사도 값은 S로부터 제거한다.
* 통합된 새로운 영역(r(t))과 인접한 영역들에 대해 유사도(S(t))를 계산한다.
* S와 R에 유사도(S(t))와 통합된 새로운 영역(r(t))을 추가한다.
3. 최종적으로 하나의 영역이 만들어질 때까지 2번을 반복한다.
### R-CNN Training
<img src="https://i.imgur.com/6yOt47e.png" width="100%">
* Pre-train a ConvNet(AlexNet) for ImageNet classification dataset
* Fine-tune for object detection(softmax + log loss)
* Cache feature vectors to disk
* Train post hoc linear SVMs(hinge loss)
* Train post hoc linear bounding-box regressors(squared loss)
모델 구성을 조금 더 설명하자면 ImageNet classification dataset으로 Pre-train된 모델을(위의 그림에서는 AlexNet을 예로 들고 있다)을 ConvNet으로 활용한다. 이 때 AlexNet의 마지막 layer를 Obejct Detection을 위한 class의 수로 수정하여 fine tuning을 수행한다. 이후 마지막 layer의 이전 layer를 디스크에 따로 저장을 해놓는다. 그리고 그 저장된 데이터를 SVM에 학습시킨다.<br><br>
* fine tuning: 기존에 학습되어져있는 모델을 기반으로 아키텍처를 새로운 목적(나의 이미지 데이터에 맞게)에 맞게 변형하고 이미 학습된 모델 weights로부터 학습을 업데이트하는 방법을 말한다. 이는 모델의 파라미터를 미세하게 조정하는 행위로써 특히 딥러닝에서는 이미 존재하는 모델에 추가 데이터를 투입하여 파라미터를 업데이트하는 것을 말한다.
Question) Bounding-box regressor는 어떤 layer를 통해 학습하는가? 그리고 이 과정은 end-to-end인가?(PPT 12쪽에 따르면 update되지 않는다고 쓰여져 있음)<br><br>
Answer) BBox regression은 분리된 Neural Network로써 ConvNet과 함께 가중치들이 update되지 않는다. 따라서 end-to-end 학습이라고 할 수 없다. 즉, Selective Search, ConvNet, SVM, BBox Regerssion 모두가 각자의 모델로 존재한다.
### Bounding-Box Regression
<img src="https://i.imgur.com/5ikzHbY.png" width="100%">
<img src="https://i.imgur.com/dKxKXMX.png" width="100%">
<img src="https://i.imgur.com/zjXZJ8Q.png" width="100%">
Bounding-Box Regression의 작동원리는 Bounding Box의 중심 x좌표 x, y좌표 y, 높이 h, 너비 w를 예측한 P와 실제값 G를 줄이는 방식으로 진행된다. 특히 P와 G의 차이를 나타내는 t와 우리가 조절해야 할 대상인 d(P)의 간격을 최소화하는 방향으로 이루어진다.
Question) Bounding-Box Regression 위의 내용이 맞는지 여부?<br><br>
Answer) 추후 확인 필요
### Problems of R-CNN
R-CNN의 문제점은 다음과 같다.<br><br>
1. Slow at test-time<br>
R-CNN의 구조를 보면 처음 Selective Search를 통해 얻은 2000여장의 Region Proposal을 ConvNet에 모두 입력시켜야한다. 이는 test시에 굉장히 많은 시간을 필요로 하게 된다. 특히 논문에 게재된 내용에 따르면 test시 image 한 장당 GPU(K40)를 이용하여 13초의 시간을, CPU를 이용하여 53초의 시간을 필요로 했다.
2. SVM and regressors are post-hoc<br>
ConvNet과 SVM, Regressor는 별개의 모델로써 end-to-end 학습을 수행할 수 없다. 따라서 SVM과 Regressor에서 학습한 내용을 ConvNet에 전달할 수 없다.
3. Complex multistage training pipeline(84 hours using K40 GPU)<br>
R-CNN의 구조는 multistage training pipeline으로써 많은 모델을 한꺼번에 가지고 있다. ConvNet, SVMs, Bounding-Box Regressor가 이에 해당하는데, 이들을 모두 학습시켜야하기때문에 굉장히 복잡한 구조를 가지고 있다고 할 수 있다.
# Fast R-CNN(2015)
위의 R-CNN의 문제점들을 보완해서 나온 모델이 Fast R-CNN이다. 아래 그림을 통해 자세히 살펴보자.
### Model
<img src="https://i.imgur.com/gM5oGFt.png" width="100%">
<img src="https://i.imgur.com/m31U15k.png" width="100%">
Selective Search를 통해 RoI를 추출하는 것은 동일하다. 하지만 R-CNN과는 달리 이미지 전체를 ConvNet에 바로 입력시킨다. 이 때 Input Image가 ConvNet을 거치면서 사이즈가 pooling되는데 RoI 또한 같이 pooling된다고 볼 수 있다. 이를 RoI projection이라고 한다. 이후 각각의 Bounding Box를 pooling하여 같은 사이즈로 맞춰주는 RoI pooling을 수행한다. 이는 Fully Connected Layer에 동일한 사이즈로 입력시켜주기 위함이다. RoI pooling으로 인해 모두 동일한 사이즈를 갖게 된 데이터는 FC를 거쳐 RoI feature vector가 되고, 또 다시 병렬적인 FC를 거쳐 Softmax(classification)와 Bounding Box Regression을 수행하는 구조로 이루어져있다. 즉 Fast R-CNN의 핵심은 RoI pooling이라고 할 수 있겠다.
### RoI Pooling
<img src="https://i.imgur.com/BV8xO56.png" width="100%">
<img src="https://i.imgur.com/zQww6ym.png" width="100%">
ConvNet을 통과한 feature map에 존재하는 Bounding Box를 다음 FC에 입력하기 위해 모두 같은 사이즈로 만들어주는 것을 RoI Pooling이라고 했다. 구체적으로 어떻게 작동하는지 살펴보자.<br>
예를 들어 FC에 입력할 사이즈를 7x7로 정해놓았다고 가졍하자. 그럼 ConvNet을 통과한 feature map에 존재하는 모든 RoI의 사이즈를 7x7로 만들어주어야한다. 어떤 RoI의 사이즈가 21x14라고 하면, (3,2)의 stride를 가진 3x2 max pooling을 통해 7x7로 만들어줄 수 있다. 마찬가지로 또 다른 RoI의 사이즈가 35x42라고 하면, (5,6)의 stride를 가진 5x6 max pooling을 통해 7x7로 만들어줄 수 있다. 이처럼 모든 RoI에 각각에 맞는 stride를 적용하여 max pooling을 한다면 모두 같은 사이즈로 만들어 줄 수 있다. 이를 보기 편하게 설명하기 위해 아래와 같이 정리할 수 있다.<br><br>
RoI in Conv feature map : 21x14 -> 3x2 max pooling with stride(3, 2) -> output : 7x7<br>
RoI in Conv feature map : 35x42 -> 5x6 max pooling with stride(5, 6) -> output : 7x7
### Training & Testing
<img src="https://i.imgur.com/vNfzMVF.png" width="100%">
<img src="https://i.imgur.com/DatXybA.png" width="100%">
Fast R-CNN을 훈련시킴에 있어서 Loss Function을 눈여겨 볼 만하다. L(cls)는 우리가 흔히 알고 있는 Cross Entropy를 사용했고, L(loc)은 새롭게 함수를 정의해놓았다. 특히 u가 1 이상일 경우를 설정해놓았는데, 이는 u가 0인 경우, 즉 배경인 경우에는 L(loc)을 고려하지 않겠다는 것을 의미한다. 이는 엉뚱한 곳에 RoI를 잡은 경우 Bounding Box Regression에 대한 loss는 구하지 않도록 해준다. 특히 IoU에 대한 임계값을 설정하면 그 임계값 이상인 RoI에 대해서만 loss를 구하게 된다.
### R-CNN vs. SPP-net vs. Fast R-CNN
<img src="https://i.imgur.com/9KEPmyF.png" width="100%">
그렇다면 Fast R-CNN은 얼마나 성능이 향상되었을까? 위의 그래프를 통해 확인할 수 있다. 기존 R-CNN에 비해 Training time과 Test time을 굉장히 단축시킨 것을 확인할 수 있다. 특히 눈여겨 봐야 할 점은 오른쪽 그래프의 Fast R-CNN이다. 파란색 그래프는 Region Proposal를 포함시킨 시간이고, 빨간색 그래프는 포함시키지 않은 시간이다. 즉, 이 두 시간의 차이는 Region Proposal을 구하는 시간인 Selective Search를 의미한다. 이 시간이 전체 시간의 대부분을 차지하고 있음을 확인할 수 있다. 이는 앞에서도 언급했다시피 CPU상에서 작동하기 때문이다.
### Problems of Fast R-CNN
Fast R-CNN의 문제점은 다음과 같다.<br><br>
1. Out-of-network region proposals are the test-time computational bottleneck<br>
Region Proposal, 즉 Selective Search가 Network의 바깥에 존재하여 시간이 굉장히 오래 걸린다.
2. Is it fast enough?<br>
과연 Fast R-CNN의 성능을 빠르다고 할 수 있는가는 생각해봐야한다. Real-Time을 적용하기 위해서는 2.3초는 빠르다고 할 수는 없을것이다.
# Faster R-CNN(2015)
### Model
R-CNN, Fast R-CNN은 CPU에서 수행하는 Selective Search때문에 많은 시간을 필요로 했다. 이를 마지막 convolution layer 이후에 RPN(Region Proposal Network)을 사용하여 GPU를 사용해보자는 것이 Faster R-CNN의 아이디어이다. 따라서 RPN은 Region Proposal을 정확하게 잡아내도록 학습되고, RPN 이후 RoI Pooling을 하여 Classifier와 BBox regressor를 사용하는 것은 Fast R-CNN과 동일하다. 즉, Faster R-CNN을 한마디로 표현하면 RPN + Fast R-CNN이라고 할 수 있다.
<img src="https://i.imgur.com/d33QiVJ.png" width="100%">
Question) 기존 Fast R-CNN의 Selective Search가 느려서 RPN을 사용하여 Faster R-CNN이 나온 것으로 알고 있습니다. 이 때 RPN에 있는 reg가 BBox를 조정해주는 것으로 알고 있는데, 그럼 원래 Fast R-CNN의 reg는 없어져도 되지 않나요? reg가 2개가 있는 이유가 궁금합니다.<br><br>
Answer) ROI pooling 된 결과가 CNN에 입력으로 들어가야 하는데 CNN의 입력은 고정된 사이즈를 요구합니다. 따라서 정확한 ROI위치를 잡아서 CNN의 입력으로 넣어주기 위해서 첫번째 BB regression이 필요한것이구요. 두번째는 이제 object dection된 결과를 평가함에 있어 IOU와 같이 BB overlap이 얼마나 잘 됐는지를 평가하는 metirc이 있기 때문에 여기서 성능이 낮아지는걸 방지하기 위해 Refine BB 가 있는것입니다.
Question) 정확한 ROI 위치를 잡기 위해 BBox를 조정하는 것이 곧 BB overlap이 높다는 것을 의미하는 것 아닌가요?<br><br>
Answer) 그렇긴한데요. 결국 BB 오버랩은 맨 마지막에 측정하기 때문에 출력단에 refine BB가 있습니다.
Question) 그럼 마지막 reg는 BBox 미세조정도 하지만 측정을 위해서 존재의미가 더 큰건가요?<br><br>
Answer) 네네 BB 가 조금만 벗어나도 성능에 큰 영향을 미치기 때문에 사실 object를 detection하는데 있어서는 의미가 없지만 성능을 보여주기 위해서는 평가지표를 따라야 하기 때문에 평가지표상 성능을 높이기 위해서 존재한다고 보셔도 됩니다.
### RPN
<img src="https://i.imgur.com/AwZ6GyL.png" width="100%">
* 3x3 conv, 256 filters
* 1x1 conv, 18 filters
* 1x1 conv, 36 filters
그렇다면 RPN은 도대체 뭘까? 시작은 ConvNet을 통해 얻어진 feature map에서 시작한다. 여기서 동일한 크기의 sliding window를 이동시키며 window의 위치를 중심으로 사전에 정의된 다양한 비율/크기의 anchor box들을 적용하여 feature를 추출한다. 위의 그림에서는 ZF 기준으로 3x3 conv를 통해 256개의 feature를 추출하는 것을 확인할 수 있다. 이는 image 크기를 조정할 필요가 없으며, filter 크기를 변경할 필요도 없으므로 계산효율이 높은 방식이라 할 수 있다. 이후 추출된 feature를 1x1 conv를 수행하고 그 값을 바탕으로 병렬적으로 Classification과 BBox Regression을 수행하는 방식이라고 할 수 있겠다. 이 때 네트워크를 heavy하지 않고 slim하게 만들기 위해 물체가 존재하느냐 하지 않느냐에 따른 2개의 classification만을 수행한다.
<img src="https://i.imgur.com/UpSraSD.png" width="100%">
그렇다면 initial한 BBox가 필요할텐데, 그것을 'anchor'라고 한다. k개의 anchor box를 미리 정의해놓고 각 지역마다 사용하는 방식이다. 논문에서는 k개의 anchor box를 3가지 크기에 대한 3가지 비율을 경우의 수로 두고 9개의 anchor box로 정의했다. 이후 각각의 anchor box에 대해서 Classification과 BBox Regression을 수행하는 것이다. 위의 그림을 보면 Classification부분은 물체 존재여부에 따라 2개의 경우로 나뉘므로 총 2k개의 socres가 도출되고, BBox Regression부분은 x, y, h, w 4개의 값을 필요로 하므로 4k개의 coordinates가 도출된다.
* anchor: pre-defined reference boxes
* Multi-scale/size anchor: 3 scale(128x128, 256x256, 512x512) and 3 aspect rations(2:1, 1:1, 1:2) yield 9 anchors
### Positive/Negative Samples
* An anchor is labeled as positive if
* The anchor is the one with highest IoU overlap with a ground truth box
* The anchor has an IoU overlap with a ground truth box higher than 0.7
* Negative labels are assigned to anchors with IoU lower than 0.3 for all ground truth boxes
* 50%/50% ratio of positive/negative anchors in a minibatch
위의 설명과 같이 anchor box는 positive 또는 negative로 라벨링된다. ground-truth box와 가장 큰 IoU 값을 갖는 anchor와 0.7 이상의 값을 갖는 anchor는 positive로 라벨링된다. 반대로 IoU가 0.3 이하의 값을 갖는 anchor는 negative로 라벨링된다. 그 사이의 값들은 그냥 버리는 값이 된다. 특히 Random Sampling으로 학습을 하면 negative 레이블이 너무 많기 때문에 50대50 비율로 샘플링을 해준다.
### RPN Loss Function
<img src="https://i.imgur.com/7E1Yl8n.png" width="100%">
기존 Fast R-CNN의 Loss Function과 비슷한 Loss Function을 가진다. 특히 P_star는 물체가 있으면 1, 없으면 0의 값을 가지기 때문에 배경에 대해서는 Regression 계산을 하지 않는다. 추가적으로 논문에 따르면 N(cls)나 N(reg)처럼 Normalization하는 부분, 그리고 lambda는 크게 중요하지 않다고 말하고 있고 실험 결과를 통해 보여주고 있다.
Question) Loss Function 수식에 대한 이해?<br><br>
Answer) 수식에 대한 이해가 더욱 필요하다.
### 4-Step Alternating Training
<img src="https://i.imgur.com/cLc0heY.png" width="100%">
Question) 실제 Training에 대한 내용<br><br>
Answer) 이 부분은 실제 모델을 학습하고 Region Proposal을 출력하는 과정이다. 코드를 활용하기 위해 이해해야 할 부분인데 완벽히 이해하지를 못했다. 다른 자료들을 통해 이해해야 하는 과정이 필요하다.
### Results
<img src="https://i.imgur.com/In4IVHA.png" width="100%">
위의 표는 R-CNN, Fast R-CNN, Faster R-CNN의 정확도와 성능을 비교하고있다. 이미지 1장당 test time을 0.2초까지 줄였으며, 이는 R-CNN에 비해 250배 향상된 속도이다.
<img src="https://i.imgur.com/1Jmc0o3.png" width="100%">
또한 위의 표에서 VGG를 사용한 모델을 살펴보자. SS + Fast R-CNN은 Selective Search를 사용한 모델로써, 기존 Fast R-CNN을 의미한다. 그리고 그 아래 RPN + Fast R-CNN은 Faster R-CNN을 의미한다. 즉, CPU를 사용했던 Selective Search를 GPU를 사용하는 RPN으로 바꾸면 proposal부분에서 시간이 굉장히 단축됨을 확인할 수 있다.
### Problems of Faster R-CNN
Faster R-CNN의 문제점은 다음과 같다.
* RoI Pooling has some quantization operations
* These quantizations introduce misalignments between the RoI and the extracted features
* While this may not impact classification , it can make a negative effect on predicting bbox
Faster R-CNN 또한 마찬가지로 RPN에서 추출한 Region Proposal을 RoI Pooling을 통해 사이즈를 변환한다. 이 RoI Pooling 작동방식에서 위와 같은 문제가 발생한다. 이는 RoI Pooling을 사용하는 Fast R-CNN도 마찬가지이다. 위에서 RoI Pooling을 언급했던 예시를 다시 살펴보면 아래와 같다.<br><br>
RoI in Conv feature map : 21x14 -> 3x2 max pooling with stride(3, 2) -> output : 7x7<br>
RoI in Conv feature map : 35x42 -> 5x6 max pooling with stride(5, 6) -> output : 7x7<br><br>
이는 해당하는 두 개의 RoI가 7로 잘 나누어떨어지는 h와 w를 가지고 있는 경우인데, 예를 들어 세 번째 RoI가 21x15라면 어떤 방식으로 pooling을 해도 7x7의 출력을 할 수가 없다. 이는 Classification 부분에서는 큰 문제가 없을지 몰라도, BBox Regression에서 정보손실을 일으켜 부정적인 영향을 준다. 이해를 쉽게 하기 위해 아래 그림을 참조할 수 있겠다.
<img src="https://i.imgur.com/1KoOsmM.png" width="100%">
# Mask R-CNN
### Model
<img src="https://i.imgur.com/TDyfxMN.png" width="100%">
드디어 대망의 Mask R-CNN이다. 분위기상으로 보자면 이 모델은 이전 R-CNN 계열의 모든 문제점들을 해결한 것처럼 보이는데, 그게 맞다. 한 번 살펴보도록 하자.<br>
먼저 이 모델을 직관적으로 다음과 같이 이해할 수 있겠다. 우리가 해결하고자 하는 문제는 Instance Segmentation으로써, 모든 객체를 다르게 인식하고 segmentation 또한 할 수 있어야 한다. 어떻게 이 문제를 해결할 수 있을까? 단순하게 생각해보자면, 기존 Faster R-CNN은 BBox Classification을 아주 잘 해내는 모델이고 기존 FCN은 Segmentation을 아주 잘 해내는 모델이다. 그럼 이 두 모델의 장점만을 결합한다면? 이것이 바로 Mask R-CNN의 컨셉이다. 즉 Faster R-CNN이 검출해 준 BBox안에서 FCN을 통해 Segmentation을 하면 이 문제를 해결할 수 있다.
<img src="https://i.imgur.com/aZ1277L.png" width="100%">
### Mask Head
<img src="https://i.imgur.com/hMW3WMa.png" width="100%">
그럼 단순히 Faster R-CNN과 FCN을 붙여놓기만 하면 될까? 각각의 기능을 살펴보자.<br>
FCN의 첫 번째 특징은 'Pixel level Classification'이다. 이는 픽셀별로 어떤 클래스인지 구분을 하는 것을 의미하는데, 따라서 Activation Function 또한 'Per Pixel Softmax'이다. 그런데 Faster R-CNN의 모델은 이미 Classification을 통해 BBox 내부의 객체가 어떤 클래스에 해당하는지를 분류해주고 있다. 따라서 두 모델의 기능이 겹치므로 FCN은 Classification을 해 줄 필요가 없게 되고, 픽셀별로 객체가 존재하는지의 여부만 따져주면 된다. 즉 FCN의 기능은 'Per Pixel Sigmoid(Binary)'만 해주면 된다.<br>
FCN의 두 번째 특징은 'Multi Instance'이다. 마찬가지로 Faster R-CNN 모델은 이미 인스턴스 단위로 RoI를 잡아주기 때문에 이에 대해서도 걱정할 필요가 없다.<br>
즉 Mask R-CNN의 FCN 부분은 단순히 Sigmoid를 통해 픽셀별로 해당 BBox 내에서 객체가 존재하는지를 Binary로 출력해주기만 하면 되는 것이다.
### Loss Function
<img src="https://i.imgur.com/eYGZDPm.png" width="100%">
Mask R-CNN의 Loss Function은 위 그림과 같다. 기존 Faster R-CNN의 Loss Function에서 L(mask)가 추가된 형태로 이는 단순히 Binary Masking에 대한 loss값을 의미한다.
<img src="https://i.imgur.com/sGpowg6.png" width="100%">
조금 더 자세히 살펴보면 위의 슬라이드 그림을 통해 확인할 수 있다. L(mask)의 경우 모든 클래스에 대해서 loss값을 계산하지만, 결국 Classification에 의해 정해진 클래스 값의 loss값만 취하게 된다. 즉 Mask 브랜치는 클래스에 관계없이 오직 마스킹하는 법만 배운다고 말할 수 있다.
### RoI Align
Mask R-CNN의 주요 특징 중 하나는 'RoI Align'이라고 할 수 있겠다. 이전 Fast R-CNN, Faster R-CNN 모델에서 RoI Pooling의 단점을 언급했었는데, 이를 해결해주는 방법이 이것이다. 7x7 feature를 segmentation하기엔 너무 작은 사이즈이기에 feature를 pooling하는데 좀 더 정확한 방법이 필요했다.
<img src="https://i.imgur.com/aTWdcOq.png" width="100%">
위에 설명되어있는 RoI Pooling 그림과 비교해서 살펴보면 RoI Align의 장점을 더 잘 파악할 수 있다. RoI Pooling의 경우 실수 픽셀을 예측했을 때 반올림하여 Pooling을 하고, MaxPooling을 할 때에도 중앙을 정확히 자르지 못하는 경우 반올림하여 수행한다. 이런 식으로 수행하면 의도한 정보를 손실하게 되는 문제가 발생한다. 이에 대한 해결책으로 RoI Align은 실수값을 끝까지 끌어올리는 방법을 취하는데, MaxPooling을 위해 4등분을 하고, 더욱 정확하게 수행하기 위해 다시 한 번 4등분을 한다. 이 떄 이를 'Subcell'이라 부른다. 그리고 각 Subcell마다 binary interpolation을 수행하여 더욱 정확한 값을 도출해낸다. 이후 도출된 값들을 바탕으로 MaxPooling을 수행한다. 이러한 방법은 기존의 RoI Pooling 했을 떄의 정보손실을 줄여주는 역할을 함으로써 Binary Masking의 성능을 더욱 좋게 만들어주는 효과를 발휘한다.
<img src="https://i.imgur.com/dF84kK9.png" width="100%">
### RoI Issue: Zero Padding
<img src="https://i.imgur.com/kEKTAgL.png" width="100%">
추가적으로 Mask R-CNN은 RoI를 뽑을 때 Zero Padding을 해준다. 이를 통해 해당 인스턴스와 붙어있는 다른 인스턴스를 확실하게 구분시켜주어 인스턴스 예측이 용이하게 해준다.
### Network Architecture
<img src="https://i.imgur.com/BVr2bon.png" width="100%">
논문에서 제안한 Network Architecture는 위의 그림과 같이 2개의 종류로 나뉜다. 회색 음영처리부분이 각각 ResNet과 FPN을 의미하며 Mask Branch를 가지고 있다. 특이한 점은 Mask Branch로 뻗어나가는 부분의 shape이 (14, 14, 256)인 점이다.
* Faster R-CNN + ResNet
* Faster R-CNN + FPN
<img src="https://i.imgur.com/EXl2ivJ.png" width="100%">
요약하자면, Mask R-CNN은 Faster R-CNN + Binary Mask Prediction + FCN + RoIAlign이라고 할 수 있겠다. 추가적으로 Mask R-CNN의 단점은 BBox 안에서만 segmentation이 가능하기 때문에 BBox를 잘 잡아야만 성능이 좋게 나온다.
# Reference
[Deep Learning] pre-training 과 fine-tuning (파인튜닝)
* https://eehoeskrap.tistory.com/186
Object recognition을 위한 선택적 검색
* https://murra.tistory.com/25
[분석] Faster R-CNN
* https://curt-park.github.io/2017-03-17/faster-rcnn/
PR-012: Faster R-CNN : Towards Real-Time Object Detection with Region Proposal Networks
* https://www.youtube.com/watch?v=kcPAGIgBGRs&list=WL&index=8&t=0s
* https://www.slideshare.net/JinwonLee9/pr12-faster-rcnn170528
PR-057: Mask R-CNN
* https://www.youtube.com/watch?v=RtSZALC9DlU&list=WL&index=9&t=0s
* https://www.slideshare.net/TaeohKim4/pr057-mask-rcnn
|
Python
|
UTF-8
| 781 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
from nltk.probability import FreqDist
from os import path
from wordcloud import WordCloud
items = ["Computer Science", "foo", "bar"]
fd = FreqDist(items)
print(fd)
for i in fd.keys():
print(i, fd[i])
freq_dist = {}
for key in fd.keys():
freq_dist[key] = fd[i]
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'sentence1.txt')).read()
# Generate a word cloud image
wordcloud = WordCloud().generate_from_frequencies(freq_dist)
# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
# lower max_font_size
wordcloud = WordCloud(max_font_size=40).generate(text)
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
|
C#
|
UTF-8
| 467 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
using System.IO;
namespace ctorx.Core.SmtpMail
{
public class EmailAttachment
{
/// <summary>
/// Gets the attachment Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets the attachment content bytes
/// </summary>
public byte[] Content { get; set; }
/// <summary>
/// Gets a content stream for the attachment
/// </summary>
public Stream GetContentStream()
{
return new MemoryStream(this.Content);
}
}
}
|
Java
|
UTF-8
| 765 | 2.65625 | 3 |
[] |
no_license
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class heart here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class heart extends Actor
{
/**
* Act - do whatever the heart wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
if(isTouching(link.class)){
((Overworld)getWorld()).getHealth().decr();//adds a heart back to health
((Overworld)getWorld()).getLink().decrHealth();// removes a value from healthCounter so that you can fire your sword
getWorld().removeObject(this);
}
}
}
|
C++
|
UTF-8
| 6,283 | 2.546875 | 3 |
[
"MIT-Modern-Variant"
] |
permissive
|
// main.cc
// Bootstrap code to initialize the operating system kernel.
//
// Allows direct calls into internal operating system functions,
// to simplify debugging and testing. In practice, the
// bootstrap code would just initialize data structures,
// and start a user program to print the login prompt.
//
// Most of this file is not needed until later assignments.
//
// Usage: ManaOS -d <debugflags> -rs <random seed #>
// -s -x <ManaOS file> -c <consoleIn> <consoleOut>
// -f -cp <unix file> <ManaOS file>
// -p <ManaOS file> -r <ManaOS file> -l -D -t
// -n <network reliability> -m <machine id>
// -o <other machine id>
// -z
//
// -d causes certain debugging messages to be printed (cf. utility.h)
// -rs causes Yield to occur at random (but repeatable) spots
// -z prints the copyright message
//
// USER_PROGRAM
// -s causes user programs to be executed in single-step mode
// -x runs a user program
// -c tests the console
//
// FILESYS
// -f causes the physical disk to be formatted
// -cp copies a file from UNIX to ManaOS
// -p prints a ManaOS file to stdout
// -r removes a ManaOS file from the file system
// -l lists the contents of the ManaOS directory
// -D prints the contents of the entire file system
// -t tests the performance of the ManaOS file system
//
// NETWORK
// -n sets the network reliability
// -m sets this machine's host id (needed for the network)
// -o runs a simple test of the ManaOS network software
//
// NOTE -- flags are ignored until the relevant assignment.
// Some of the flags are interpreted here; some in system.cc.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#define MAIN
#include "copyright.h"
#undef MAIN
#include "utility.h"
#include "system.h"
// External functions used by this file
void ThreadTest();
void Copy(const char *unixFile, const char *ManaOSFile);
void Print(const char *file);
void PerformanceTest(void);
void StartProcess(char *file);
void ConsoleTest(const char *in, const char *out);
void MailTest(int networkID);
void sProc(void* n);
//----------------------------------------------------------------------
// main
// Bootstrap the operating system kernel.
//
// Check command line arguments
// Initialize data structures
// (optionally) Call test procedure
//
// "argc" is the number of command line arguments (including the name
// of the command) -- ex: "ManaOS -d +" -> argc = 3
// "argv" is an array of strings, one for each command line argument
// ex: "ManaOS -d +" -> argv = {"ManaOS", "-d", "+"}
//----------------------------------------------------------------------
int main(int argc, char **argv)
{
int argCount; // the number of arguments
// for a particular command
DEBUG('t', "Entering main");
(void) Initialize(argc, argv);
printf("__ __ __ __ ___ ____ _ \n");
printf("\\ \\ / /_ _ _ __ ___ ___ ___ | \\/ | __ _ _ __ __ _ / _ \\/ ___|| |\n");
printf(" \\ \\ / / _` | '_ ` _ \\ / _ \\/ __| | |\\/| |/ _` | '_ \\ / _` | | | \\___ \\| |\n");
printf(" \\ V / (_| | | | | | | (_) \\__ \\ | | | | (_| | | | | (_| | |_| |___) |_|\n");
printf(" \\_/ \\__,_|_| |_| |_|\\___/|___/ |_| |_|\\__,_|_| |_|\\__,_|\\___/|____/(_)\n");
printf("\nEs un Mana Operating System, es para compartir!\n\n\n");
#ifdef THREADS
// ThreadTest();
#endif
for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount)
{
argCount = 1;
if (!strcmp(*argv, "-z")) // print copyright
printf ("%s",copyright);
#ifdef USER_PROGRAM
if (!strcmp(*argv, "-x")) { // run a user program
ASSERT(argc > 1);
char *spArg = (char*) malloc(strlen(*(argv + 1)) + 1); //A esto no lo libera ni fidel castro
strcpy(spArg, *(argv + 1)) ;
StartProcess(spArg);
argCount = 2;
}
else if (!strcmp(*argv, "-c")) { // test the console
if (argc == 1)
ConsoleTest(NULL, NULL);
else {
ASSERT(argc > 2);
ConsoleTest(*(argv + 1), *(argv + 2));
argCount = 3;
}
interrupt->Halt(); // once we start the console, then
// ManaOS will loop forever waiting
// for console input
}
#endif // USER_PROGRAM
#ifdef FILESYS
if (!strcmp(*argv, "-cp")) { // copy from UNIX to ManaOS
ASSERT(argc > 2);
Copy(*(argv + 1), *(argv + 2));
argCount = 3;
} else if (!strcmp(*argv, "-p")) { // print a ManaOS file
ASSERT(argc > 1);
Print(*(argv + 1));
argCount = 2;
} else if (!strcmp(*argv, "-r")) { // remove ManaOS file
ASSERT(argc > 1);
fileSystem->Remove(*(argv + 1));
argCount = 2;
} else if (!strcmp(*argv, "-l")) { // list ManaOS directory
fileSystem->List();
} else if (!strcmp(*argv, "-D")) { // print entire filesystem
fileSystem->Print();
} else if (!strcmp(*argv, "-t")) { // performance test
PerformanceTest();
}
#endif // FILESYS
#ifdef NETWORK
if (!strcmp(*argv, "-o")) {
ASSERT(argc > 1);
Delay(2); // delay for 2 seconds
// to give the user time to
// start up another ManaOS
MailTest(atoi(*(argv + 1)));
argCount = 2;
}
#endif // NETWORK
}
#ifdef USER_PROGRAM
// Llamo a nuestro shell
printf("Vamos a entrar a la consola.\n");
char *s = (char *) malloc(14 * sizeof(char));
strcpy(s, "../test/bin/shell");
StartProcess(s);
#endif
currentThread->Finish(); // NOTE: if the procedure "main"
// returns, then the program "ManaOS"
// will exit (as any other normal program
// would). But there may be other
// threads on the ready list. We switch
// to those threads by saying that the
// "main" thread is finished, preventing
// it from returning.
return(0); // Not reached...
}
|
Python
|
UTF-8
| 1,358 | 2.5625 | 3 |
[] |
no_license
|
import tensorflow as tf
import numpy as np
from PIL import Image
from tensorflow.python.keras.preprocessing import image as kp_image
def gram_matrix(input_tensor):
channels = int(input_tensor.shape[-1])
a = tf.reshape(input_tensor, [-1, channels])
n = tf.shape(a)[0]
gram = tf.matmul(a, a, transpose_a=True)
return gram / tf.cast(n, tf.float32)
def load_img(path_to_img):
max_dim = 512
img = Image.open(path_to_img)
long = max(img.size)
scale = max_dim / long
img = img.resize((round(img.size[0] * scale), round(img.size[1] * scale)), Image.ANTIALIAS)
img = kp_image.img_to_array(img)
img = np.expand_dims(img, axis=0)
return img
def load_img_to_show(path_to_img):
max_dim = 512
img = Image.open(path_to_img)
long = max(img.size)
scale = max_dim / long
img = img.resize((round(img.size[0] * scale), round(img.size[1] * scale)), Image.ANTIALIAS)
return img
def load_and_process_img(path_to_img):
img = load_img(path_to_img)
img = tf.keras.applications.vgg19.preprocess_input(img)
return img
def in_img(processed_img):
x = processed_img.copy()
if len(x.shape) == 4:
x = np.squeeze(x, 0)
x[:, :, 0] += 103.939
x[:, :, 1] += 116.779
x[:, :, 2] += 123.68
x = x[:, :, ::-1]
x = np.clip(x, 0, 255).astype('uint8')
return x
|
Ruby
|
UTF-8
| 1,401 | 3.078125 | 3 |
[] |
no_license
|
require'rexml/document'
def cs(parent, x1, y1, x2, y2)
c = parent.add_element "line"
c.attributes["x1"] = x1
c.attributes["y1"] = y1
c.attributes["x2"] = x2
c.attributes["y2"] = y2
c.attributes["stroke"] = "black"
c.attributes["stroke-width"] = "1"
end
def line(parent, x1, y1, x2, y2)
c = parent.add_element "line"
c.attributes["x1"] = x1+600
c.attributes["y1"] = 350-y1.to_i
c.attributes["x2"] = x2+600
c.attributes["y2"] = 350-y2.to_i
c.attributes["stroke"] = "rgb(#{rand(255)},#{rand(255)},#{rand(255)})"
c.attributes["stroke-width"] = "2"
end
if ARGV.length.even? == false or ARGV.length == 0
puts "wrong arguments"
else
doc = REXML::Document.new
el_svg = doc.add_element "svg"
el_svg.attributes["version"] = "1.1"
el_svg.attributes["xmlns"] = "http://www.w3.org/2000/svg"
cs(el_svg, 600, 50, 600, 650)
cs(el_svg, 300, 350, 900, 350)
i=0
x1=0
x2=0
while ARGV[i] != nil
a = ARGV[i].to_i
b = ARGV[i+1].to_i
if a == 0
y1 = ARGV[count+1]
x1 = -300
y2 = ARGV[count+1]
x2 = 300
else
[300, -300].each do |y|
x = (y-b)/a
if x.between?(-300,300)
y1 = y
end
end
[-300, 300].each do |y|
x = (y-b)/a
if x.between?(-300,300)
y2 = y
end
end
x1= (y1.to_i-b)/a
x2= (y2.to_i-b)/a
end
line(el_svg,x1,y1,x2,y2)
i+=2
end
File.open("Milko_Filipov.svg", "w") do |f|
f.write(doc.to_s)
end
end
|
Java
|
UTF-8
| 1,160 | 2.28125 | 2 |
[] |
no_license
|
package com.mc.wechat.vo.menu;
import com.mc.EventType;
import lombok.Data;
import org.nutz.json.JsonField;
import java.util.List;
/**
* @ClassName Menu
* @Author ZhengRongZe
* @Date 2019/3/11 13:29
**/
@Data
public class Menu {
/**
* 菜单的响应动作类型,view表示网页类型,click表示点击类型,miniprogram表示小程序类型
*/
private String type;
/**
*菜单标题,不超过16个字节,子菜单不超过60个字节
*/
private String name;
/**
* 点击类型菜单KEY值,用于消息接口推送,不超过128字节
*/
private String key;
/**
* 网页链接,用户点击菜单可打开链接,不超过256字节
*/
private String url;
@JsonField(value = "sub_button")
private List<Menu> subButtons;
public Menu() {
}
public Menu(String name) {
this.name = name;
}
public Menu(String name, String type, String val) {
setName(name);
setType(type);
if(EventType.view.name().equals(type)){
setUrl(val);
}
else {
setKey(val);
}
}
}
|
SQL
|
UTF-8
| 203 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
SELECT
`salesmen`.`Scode`,
`salesmen`.`Sname`,
COUNT(`salesman`) AS family_members
FROM
`family`
INNER JOIN
`salesmen` ON family.salesman = salesmen.Scode
GROUP BY salesman;
|
Java
|
UTF-8
| 857 | 2.34375 | 2 |
[] |
no_license
|
/**
*
*/
package com.ncs.myblog.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.ncs.myblog.domain.User;
/**
* @author zhangyong
*
*/
public class UserMapperImpl implements UserMapper {
final String NAMESPACE = "com.ncs.myblog.dao.UserMapper";
private SqlSession session;
public UserMapperImpl(SqlSession session) {
this.session = session;
}
@Override
public void save(User user) {
session.insert(NAMESPACE + ".insert", user);
}
@Override
public User getById(Long id) {
return (User) session.selectOne(NAMESPACE + ".getById", id);
}
@SuppressWarnings("unchecked")
@Override
public List<User> getAll() {
return session.selectList(NAMESPACE + ".selectAll");
}
@Override
public User getByName(String name) {
return (User) session.selectOne(NAMESPACE + ".getByName", name);
}
}
|
C
|
UTF-8
| 7,304 | 3.203125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
/**
* Header file for functions related to the creation, deallocation,
* copying, and converting of color images. Other function headers cover
* the more complex operations. Implementation of these functions is in
* "image.c".
*/
#ifndef SIMPL_IMAGE_H_
#define SIMPL_IMAGE_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* Returns a SimplColorPixel struct built from red, green, blue components.
* Values outside 0 and 255 are pegged to 0 and 255.
*
* @param red A value from 0 to 255.
* @param greed A value from 0 to 255.
* @param blue A value from 0 to 255.
*
* @return A SimplColorPixel with RGB values assigned.
*/
SimplColorPixel simpl_color(const int red,
const int green,
const int blue);
/**
* Allocates or reallocates an image of a given width and height. If image
* points to an existing image, the pixel plane is reallocated to the
* desired size or no operation if the original image's size matches the
* desired size. If image points to NULL, a new image is allocated and
* returned.
*
* @param image A double pointer to an existing image or NULL.
* @param width The width of the image, cannot be 0.
* @param height The height of the image, cannot be 0.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image(SimplImage **image,
const size_t width,
const size_t height);
/**
* Deallocates an image and sets pointer to NULL.
*
* @param image A double pointer to an image or NULL.
*/
void simpl_image_free(SimplImage **image);
/**
* Clears an image by setting all the pixels to bk_color.
*
* @param image The image to be cleared. Value cannot be NULL.
* @param bk_color The color of the pixels to clear the image with.
*
* @return If successful, returns 0 (SIMPL_OK) or SIMPL_BAD_PARAMS if the
* image isn't valid.
*/
int simpl_image_clear(SimplImage *image,
const SimplColorPixel bk_color);
/**
* Copies the source image to a destination image. If dest_img points to
* NULL, the function allocates a new image and copies to that.
*
* @param dest_img A double pointer of image to copy to or NULL.
* @param src_img The image to be copied.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image_copy(SimplImage **dest_img,
const SimplImage *src_img);
/**
* Tests to see if the two images are the same.
*
* @param image1 An image to compare. Value cannot be NULL.
* @param image2 An image to compare. Value cannot be NULL.
*
* @return 1 if the dimensions and pixel content are the same, else 0.
*/
int simpl_image_compare(const SimplImage *image1,
const SimplImage *image2);
/**
* Crops a rectangular region from an image producing a new image. If
* dest_img points to NULL, the function allocates a new image. Both dest_img
* and src_img may point to the same image to destructively overwrite the
* original.
*
* @param dest_img A double pointer of the image to crop to or NULL.
* @param src_img The image to be cropped from and may be the dest_img.
* @param rect The rectangular region to crop from. It's borders will be
* bounded to src_img.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image_crop(SimplImage **dest_img,
const SimplImage *src_img,
const SimplRect *rect);
/**
* Similar to cropping, the function copies a patch defined by rect, but
* pixels sampled outside the image are defined by SimplBoundaryMethods
* and a background color and alpha.
*
* @param dest_img A double pointer of the image to copy to or NULL.
* @param src_img The image to be copied from and may be the dest_img.
* @param rect The rectangular region to copy from src_img.
* @param boundary How pixels outside the image are sampled.
* @param bk_color The background color if needed.
* @param bk_alpha The background alpha if needed.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image_patch(SimplImage **dest_img,
const SimplImage *src_img,
const SimplRect *rect,
const SimplBoundaryMethods boundary,
const SimplColorPixel bk_color,
const SimplPixel bk_alpha);
/**
* Flips an image horizontally and/or vertically. If dest_img points to NULL,
* the function allocates a new image. Both dest_img and src_img may point to
* the same image to overwrite the original.
*
* @param dest_img A double pointer of the image to flip or NULL.
* @param src_img The image to be flipped and may be the dest_img.
* @param flip_horizontal If not zero, flips horizontally.
* @param flip_vertical If not zero, flips vertically.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image_flip(SimplImage **dest_img,
const SimplImage *src_img,
const int flip_horizontal,
const int flip_vertical);
/**
* Rotates an image 90, 180, or 270 degrees. If dest_img points to NULL, the
* function allocates a new image. Both dest_img and src_img may point to the
* same image to overwrite the original.
*
* @param dest_img A double pointer of the image to rotate or NULL.
* @param src_img The image to be rotated and may be the dest_img.
* @param rotations The number of times to rotate by 90 (1, 2, or 3).
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image_rotate_ninety(SimplImage **dest_img,
const SimplImage *src_img,
const int rotations);
/**
* Converts an image to a gray image based on a specified method.
*
* @param gray_img A double pointer to the gray image or NULL.
* @param image The image to be converted, cannot be NULL.
* @param method The method used to convert color to gray.
* @param bk_value The background color in case of alpha.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_image_to_gray(SimplGrayImage **gray_img,
const SimplImage *image,
const SimplColorToGrayMethods method,
const SimplPixel bk_value);
/**
* Adds an alpha channel to an image if it doesn't already have one. If the
* function fails due to SIMPL_NOMEM, it doesn't destroy the original image
* data.
*
* @param image The image to have an alpha channel added, cannot be NULL.
*
* @return If successful, returns 0 (SIMPL_OK) else SIMPL_NOMEM or
* SIMPL_BAD_PARAMS.
*/
int simpl_alpha_create(SimplImage *image);
/**
* Removes the alpha channel from an image if it wasn't already removed.
*
* @param image The image to have the alpha channel removed, cannot be NULL.
*/
void simpl_alpha_remove(SimplImage *image);
/**
* Public function for unit testing.
*/
#ifndef NDEBUG
void test_image(void);
#endif
#ifdef __cplusplus
}
#endif
#endif
|
Python
|
UTF-8
| 2,406 | 2.609375 | 3 |
[] |
no_license
|
from Image import Image3D
from SaveImage import SaveImage
__author__ = 'Agnieszka'
from os import walk
from os.path import join
import dicom
import numpy as np
class ReadDirWithDicom(object):
def __init__(self, path):
my_path = path
files_in_dir = [join(my_path, fn) for fn in next(walk(my_path))[2]]
image3D = []
for f in files_in_dir:
if ".IMA" in f:
dicom_data_set = dicom.read_file(f)
image3D.append(dicom_data_set.pixel_array)
else:
raise IOError('wrong file- probably not DICOM')
self.Image3D = np.dstack(image3D)
print('Reading data done')
def get_all_slices_in_3D(self):
return self.Image3D
class ReadDirWithBinaryData(object):
def __init__(self, path):
"""
:param path: path to data containing data for one patient
:return:void
"""
self.my_path = path
#read sizing
meta_bin = open(self.my_path + 'hdr_CT.bin.txt')
self.width = int(meta_bin.readline().split(' = ')[1][:-2])
self.high = int(meta_bin.readline().split(' = ')[1][:-2])
self.depth = int(meta_bin.readline().split(' = ')[1][:-2])
self.data_type = meta_bin.readline().split(' = ')[1][:-2]
#read image
l = open(self.my_path + 'CT.bin', "r")
f = (np.array(np.fromfile(l, dtype="<f4")))
self.Image3D = np.reshape(f, (self.width, self.high, self.depth), order='F')
#hackig for weird binary values
if np.max(self.Image3D) < 0.1:
self.Image3D = self.Image3D.byteswap()
#read spacing
self.spacing = np.fromfile(self.my_path + 'spacing.txt', dtype=float, sep=" ")
self.im_agregation=Image3D(self.Image3D,self.spacing,self.width,self.high,self.depth,0)
SaveImage(path+'/CT_analysesClassification/1/').saveImage(self.im_agregation)
print('Reading data done')
def get_image3D(self):
"""
:return: Image from binary data as np.array with size self.width, self.high, self.depth
"""
return self.Image3D
def get_spacing(self):
"""
:return: return size of pixels in mm x|,y-,z /
"""
return self.spacing
def get_image_aggregation(self):
"""
:return:Image aggregation object
"""
return self.im_agregation
|
Java
|
UTF-8
| 3,054 | 2.1875 | 2 |
[] |
no_license
|
package com.example.AwesomeCompan.demo.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.models.auth.In;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "location")
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String url;
private String created;
private String type;
private String dimension;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "origin", fetch = FetchType.EAGER)
private Set<Character> origins = new HashSet<>();
@OneToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE }, mappedBy = "location",fetch = FetchType.EAGER)
private Set<Character> residents = new HashSet<>();
public Location() {
}
public Location(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDimension() {
return dimension;
}
public void setDimension(String dimension) {
this.dimension = dimension;
}
public Set<Character> getResidents() {
return residents;
}
public void setResidents(Set<Character> residents) {
this.residents = residents;
}
public Set<Character> getOrigins() {
return origins;
}
public void setOrigins(Set<Character> origins) {
this.origins = origins;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Location location = (Location) o;
return Objects.equals(name, location.name) &&
Objects.equals(url, location.url);
}
@Override
public int hashCode() {
return Objects.hash(id, name, url);
}
@Override
public String toString() {
return "Location{" +
"id=" + id +
", name='" + name + '\'' +
", url='" + url + '\'' +
", created='" + created + '\'' +
", type='" + type + '\'' +
", dimension='" + dimension + '\'' +
", origins=" + origins +
", residents=" + residents +
'}';
}
}
|
C++
|
UTF-8
| 638 | 2.625 | 3 |
[] |
no_license
|
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char str[200005],ptr[200005];
int NEXT[200005];
int main()
{
memset(str,0,sizeof(str));
memset(ptr,0,sizeof(ptr));
scanf("%s",str);
scanf("%s",ptr);
NEXT[0]=-1;
int k=-1;
int l=strlen(ptr);
int ans=0;
for(int i=1;i<l;i++)
{
while(k>-1&&ptr[k+1]!=ptr[i])
{
k=NEXT[k];
}
if(ptr[k+1]==ptr[i]) k++;
NEXT[i]=k; cout<<i<<' '<<NEXT[i]<<endl;
}
k=-1;
for(int i=0;i<strlen(str);i++)
{
while(k>-1&&ptr[k+1]!=str[i])
{
k=NEXT[k];
}
if(ptr[k+1]==str[i]) k++;
if(k==l-1)
{
k=-1;
ans++;
}
}
cout<<ans<<endl;
return 0;
}
|
JavaScript
|
UTF-8
| 3,390 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
/*
* akiha-circuit
*
* Copyright (c) 2019 Yuichiro MORIGUCHI
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
**/
var undef = void 0;
function isArray(anObject) {
return Object.prototype.toString.call(anObject) === '[object Array]';
}
function deepcopy(anObject) {
var result;
function copyAll() {
var i;
for(i in anObject) {
if(anObject.hasOwnProperty(i)) {
result[i] = deepcopy(anObject[i]);
}
}
}
if(isArray(anObject)) {
result = [];
copyAll();
return result;
} else if(typeof anObject === 'object' && anObject !== null) {
result = {};
copyAll();
return result;
} else {
return anObject;
}
}
var UNIT = {
"k": 1000,
"M": 1000000,
"G": 1000000000,
"T": 1000000000000,
"m": 0.001,
"u": 0.000001,
"µ": 0.000001,
"n": 0.000000001,
"p": 0.000000000001
};
function convertEngineerUnit(text) {
var unit = text.charAt(text.length - 1);
if(UNIT[unit]) {
return parseFloat(text.substring(0, text.length - 1)) * UNIT[unit];
} else {
return parseFloat(text);
}
}
function toStringEngineerUnit(val) {
function toStringVal(val, unit) {
return (val / UNIT["T"]).toString() + "T";
}
if(val > UNIT["T"]) {
return toStringVal(val, "T");
} else if(val > UNIT["G"]) {
return toStringVal(val, "G");
} else if(val > UNIT["M"]) {
return toStringVal(val, "M");
} else if(val > UNIT["k"]) {
return toStringVal(val, "k");
} else if(val > 1) {
return val.toString();
} else if(val > UNIT["m"]) {
return toStringVal(val, "m");
} else if(val > UNIT["u"]) {
return toStringVal(val, "u");
} else if(val > UNIT["n"]) {
return toStringVal(val, "n");
} else {
return toStringVal(val, "p");
}
}
function extend(base, child) {
var result = {},
i;
for(i in base) {
if(base.hasOwnProperty(i)) {
result[i] = base[i];
}
}
for(i in child) {
if(child.hasOwnProperty(i)) {
result[i] = child[i];
}
}
return result;
}
function I(x) {
return x;
}
function replaceTemplateFunction(template, setting, interprocess, postprocess) {
function replaceStr(str, prop) {
if(typeof setting[prop] === 'object') {
return JSON.stringify(setting[prop], null, 2);
} else {
return interprocess(setting[prop]);
}
}
return postprocess(template.replace(/@([^@\n]+)@/g, replaceStr));
}
function replaceTemplate(template, setting) {
return replaceTemplateFunction(template, setting, I, I);
}
function replaceTemplateRegExp(template, setting, opt) {
function escapeRE(x) {
var result = x;
result = result.replace(/\\/, "\\\\");
result = result.replace(/\//, "\\/");
return result;
}
function post(x) {
return new RegExp(x, opt);
}
return replaceTemplateFunction(template, setting, escapeRE, post);
}
module.exports = {
isArray: isArray,
deepcopy: deepcopy,
convertEngineerUnit: convertEngineerUnit,
extend: extend,
replaceTemplate: replaceTemplate,
replaceTemplateRegExp: replaceTemplateRegExp
};
|
Markdown
|
UTF-8
| 667 | 2.9375 | 3 |
[] |
no_license
|
# API
## Requests
### **POST** - /product/update/{sku}
## Update Product
Updates a product. It is just as particular as the create route, and is also identical. It requires all fields to be overwritten and does not load the old default values. You can do this however on the front end by doing a get route hit to populate the form fields if you want.
### Example Request
`POST /product/update/1`
`content-type: application/json`
```
{
"productname": "Swing",
"notificationquantity": 10,
"color": "test",
"trimcolor": "test",
"size": "test",
"price": 5.99,
"dimensions": "test",
"sku": 1
}
```
### Example Response
`202 Accepted`
|
Python
|
UTF-8
| 8,963 | 2.515625 | 3 |
[] |
no_license
|
from flask import render_template, url_for, flash, redirect, request, abort
from mainpackage import app, db, bcrypt, mail
from mainpackage.form import RegistrationForm, LoginForm, UpdateAccountForm, PostForm, RequestResetForm, ResetPasswordForm
from mainpackage.models import User, Post
from flask_login import login_user, current_user, logout_user, login_required
import secrets
import os
from PIL import Image
from flask_mail import Message
@app.route('/')
@app.route('/home')
@login_required
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
return render_template('home.html', posts=posts)
@app.route('/user/<string:username>')
def user_posts(username):
user = User.query.filter_by(username=username).first_or_404()
image_file = url_for('static', filename='profile_picture/' + user.image_file)
page = request.args.get('page', 1, type=int)
posts = Post.query.filter_by(author=user).order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
return render_template('user_posts.html', posts=posts, user=user, image_file=image_file)
'''
This code is for showing other users profile info if clicked on there name in (users Posts Page )
@app.route('/user_info/<string:username>')
def user_info(username):
user = User.query.filter_by(username=username).first_or_404()
image_file = url_for('static', filename='profile_picture/' + user.image_file)
return render_template('user_info.html', user=user, image_file=image_file)
'''
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = RegistrationForm()
if form.validate_on_submit(): # if the form validates (from front-end)
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') # hashing the password
user = User(first_name=form.first_name.data,
last_name=form.last_name.data,
username=form.username.data,
gender=form.gender.data,
email=form.email.data,
password=hashed_password) # passing all the info from form to the database userclass
db.session.add(user) # adding
db.session.commit() # commiting the changes
flash(f'Account created for {form.username.data}', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('home'))
else:
flash('Login Unsuccessful, Please check Email and Password again', 'danger')
return render_template('login.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('Logged Out Successfully', 'info')
return redirect(url_for('login'))
def save_picture(form_pic):
random_hex = secrets.token_hex(8)
f_name, f_ext = os.path.splitext(form_pic.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(app.root_path + '\\static\\profile_picture\\' + picture_fn)
output_size = (125, 125) # setting image pixel size
i = Image.open(form_pic)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn
@app.route('/account', methods=['GET', 'POST'])
@login_required
def account():
form = UpdateAccountForm()
if form.validate_on_submit():
if form.picture.data:
pic = save_picture(form.picture.data)
current_user.image_file = pic
current_user.first_name = form.first_name.data
current_user.last_name = form.last_name.data
current_user.username = form.username.data
current_user.email = form.email.data
db.session.commit()
flash('Your account has been updated', 'success')
return redirect(url_for('account'))
elif request.method == 'GET':
form.first_name.data = current_user.first_name
form.last_name.data = current_user.last_name
form.username.data = current_user.username
form.email.data = current_user.email
image_file = url_for('static', filename='profile_picture/' + current_user.image_file)
return render_template('account.html', current_user=current_user, image_file=image_file, form=form)
@app.route('/post/new', methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been created', 'success')
return redirect(url_for('home'))
return render_template('create_post.html', form=form, legend='Update Post')
@app.route('/post/<int:post_id>')
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', title=post.title, post=post)
@app.route('/post/<int:post_id>/update', methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm() # Re-using the Postform and getting the data populated as user clicks and Post that he wants to update
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash('Post updated successfully', 'success')
return redirect(url_for('post', post_id=post.id))
elif request.method == 'GET':
form.title.data = post.title
form.content.data = post.content
return render_template('create_post.html', form=form, legend='Update Post')
@app.route('/post/<int:post_id>/delete', methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user: # verify that the post selected belong to the current user or not
abort(403) # show abort error
db.session.delete(post) # else delete
db.session.commit()
flash('Post deleted successfully', 'success')
return redirect(url_for('home'))
def send_reset_email(user):
token = user.get_reset_token()
msg = Message('Message Reset Request', sender='noreply@facemash.com', recipients=[user.email])
msg.body = f'''To reset your password visit following link
{ url_for('reset_token', token=token, _external = True) }
If you did not request any reset then simply ignore and no changes will be made
Regards
Facemash.com
'''
mail.send(msg)
@app.route('/reset_password', methods=['GET', 'POST'])
def reset_request():
if current_user.is_authenticated:
return render_template('home')
form = RequestResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first() # getting the user for the submitted email
send_reset_email(user)
flash('An email has been sent with instructions to reset password !', 'info')
return render_template('reset_request.html', form=form)
@app.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_token(token):
if current_user.is_authenticated: # user needs to logout first and until they're not logged out they cannot apply for resetting password
return render_template('home')
user = User.verify_token(token) # function created in Models.py file for getting the user_id if token verifies
if user is None: # if no user is returned after verifying token
flash('This is an invalid or expired token', 'warning')
return redirect(url_for('reset_request'))
form = ResetPasswordForm()
if form.validate_on_submit(): # if the form validates (from front-end)
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') # hashing the password
user.password = hashed_password
db.session.commit() # commiting the changes
flash(f'Password has been updated, you can login now !', 'success')
return redirect(url_for('login'))
return render_template('reset_password.html', form=form)
|
Java
|
UTF-8
| 3,209 | 2.234375 | 2 |
[] |
no_license
|
package com.wgz.ant.antmove.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.wgz.ant.antmove.R;
import com.wgz.ant.antmove.adapter.RecycleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by qwerr on 2015/11/25.
*/
public class Fragment2 extends Fragment {
private TextView tuotou,untuotou;
private RecyclerView tuotoulv,untuotoulv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2,null);
intiview(view);
return view;
}
private void intiview(View view) {
tuotou = (TextView) view.findViewById(R.id.tuotou_tv);
untuotou = (TextView) view.findViewById(R.id.untuotou_tv);
tuotoulv = (RecyclerView) view.findViewById(R.id.tuotou_lv);
untuotoulv = (RecyclerView) view.findViewById(R.id.untuotou_lv);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
LinearLayoutManager layoutManager2 = new LinearLayoutManager(getActivity());
// 设置布局管理器
tuotoulv.setLayoutManager(layoutManager);
tuotoulv.setAdapter(new RecycleAdapter(data()));
untuotoulv.setLayoutManager(layoutManager2);
untuotoulv.setAdapter(new RecycleAdapter(data()));
tuotou.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tuotou.setBackgroundResource(R.drawable.bordergray_table_leftradius_ontrans_pressed);
untuotou.setBackgroundResource(R.drawable.bordergray_table_rightradius_ontrans);
tuotou.setTextColor(Color.WHITE);
untuotou.setTextColor(android.graphics.Color.parseColor("#ff0000"));
tuotoulv.setVisibility(View.VISIBLE);
untuotoulv.setVisibility(View.GONE);
}
});
untuotou.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
untuotou.setBackgroundResource(R.drawable.bordergray_table_rightradius_ontrans_pressed);
tuotou.setBackgroundResource(R.drawable.bordergray_table_leftradius_ontrans);
untuotou.setTextColor(Color.WHITE);
tuotou.setTextColor(android.graphics.Color.parseColor("#ff0000"));
tuotoulv.setVisibility(View.GONE);
untuotoulv.setVisibility(View.VISIBLE);
}
});
}
private List<Map<String, Object>> data(){
List<Map<String,Object>> da1 = new ArrayList<Map<String, Object>>();
for (int i = 0 ; i<20;i++){
Map<String,Object> map = new HashMap<>();
map.put("ceshi","测试数据"+i);
da1.add(map);
}
return da1;
}
}
|
Python
|
UTF-8
| 336 | 3.34375 | 3 |
[] |
no_license
|
def friend(n):
if(n <= 2):
return n
return friend(n-1) + (n-1)*friend(n-2)
def friendDp(n):
if(dp[n] != -1):
return dp[n]
if(n <= 2 ):
dp[n] = n
return dp[n]
dp[n] = friendDp(n-1)+(n-1)*friendDp(n-2)
return dp[n]
n = 4
dp = [-1] *(n+1)
print(friendDp(n))
print(dp)
|
C++
|
UTF-8
| 2,265 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include<SPI.h>
#include<RF24.h>
#include<nRF24L01.h>
#include "printf.h"
//receiver
//NRF ARDUINO
//1 GND GND
//2 VCC 3.3V
//3 CE 9 out
//4 CSN 10 out
//5 SCK 13 out
//6 MOSI 11 out
//7 MISO 12 in
//int radio_led = 13;
int CE_PIN = 7, CSN_PIN = 8;
RF24 Radio(CE_PIN, CSN_PIN);
const uint64_t pipeIn = 0xD4D4F0F0E1LL;
struct radio
{
int x1;
} data;
//const int xpin = A0; // x-axis of the accelerometer
//const int ypin = A1; // y-axis
//const int zpin = A2; // z-axis (only on 3-axis models)
void setup()
{
Serial.begin(9600);
//pinMode(radio_led, OUTPUT);
Radio.begin();
printf_begin();
Radio.setPALevel(RF24_PA_MIN);
Radio.setDataRate(RF24_250KBPS);
Radio.openReadingPipe(0, pipeIn);
Radio.startListening();
Radio.printDetails();
delay(2000);
data.x1 = 0;
pinMode(3,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(9,OUTPUT);
}
void loop()
{
// int x = analogRead(xpin); //read from xpin
//int y = analogRead(ypin); //read from ypin
// int z = analogRead(zpin); //read from zpin
//x=map(x,349,281,0,90);
// y=map(y,200,280,0,90);
// z=map(z,425,357,0,90);
//Serial.print(x);
//Serial.print("\t");
//Serial.print(y);
//Serial.print("\t");
//Serial.print(z);
//Serial.print("\n");
if (Radio.available())
{
Radio.read(&data, sizeof(data));
// digitalWrite(radio_led, HIGH);
}
else
{
// digitalWrite(radio_led, LOW);
}
Serial.print(data.x1);
Serial.print(" ");
int x1=data.x1;
/*int x2=0;
if((y>=40 && y<=55))
x2=2;
else if(y>=55)
x2=3;
else if(y<40)
x2=1;*/
if(x1==1)
{
forward(180);
}
else if(x1==2)
left(180);
else if(x1==3)
right(180);
else if(x1==4)
stop1();
}
void forward(int n)
{
Serial.println("FORWARD");
analogWrite(3,n);
analogWrite(5,0);
analogWrite(6,0);
analogWrite(9,n);
}
void left(int n)
{
Serial.println("LEFT");
analogWrite(3,n-80);
analogWrite(5,0);
analogWrite(9,0);
analogWrite(6,n);
}
void right(int n)
{
Serial.println("RIGHT");
analogWrite(3,n);
analogWrite(5,0);
analogWrite(6,(n-80));
analogWrite(9,0);
}
void stop1()
{
Serial.println("STOP");
analogWrite(3,0);
analogWrite(5,0);
analogWrite(6,0);
analogWrite(9,0);
}
|
PHP
|
UTF-8
| 2,185 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
// +----------------------------------------------------------------------
// | rootCMS 栏目权限与角色之间的授权
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rootcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author:
// +----------------------------------------------------------------------
namespace app\content\model;
use app\common\model\Model;
class CategoryPriv extends Model {
//自动验证
protected $_validate = array(
//array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
array('roleid', 'require', '角色ID不能为空!', 1, 'regex', 3),
array('catid', 'require', '栏目ID不能为空!', 1, 'regex', 3),
array('action', 'require', '权限动作不能为空!', 1, 'regex', 3),
);
/**
* 更新权限
* @param $catid 栏目ID
* @param $priv_datas
* @param $is_admin 1为管理员
*/
public function update_priv($catid, $priv_datas, $is_admin = 1) {
//删除旧的
$this->where(array('catid' => $catid, 'is_admin' => $is_admin))->delete();
if (is_array($priv_datas) && !empty($priv_datas)) {
foreach ($priv_datas as $r) {
$r = explode(',', $r);
//动作
$action = $r[0];
//角色或者会员用户组
$roleid = $r[1];
$this->add(array('catid' => $catid, 'roleid' => $roleid, 'is_admin' => $is_admin, 'action' => $action));
}
}
}
/**
* 检查栏目权限
* @param $privs 权限数据
* @param $action 动作
* @param $roleid 角色
* @param $is_admin 是否为管理组
*/
public function check_category_priv($privs, $action, $roleid, $is_admin = 1) {
$checked = '';
foreach ($privs as $priv) {
if ($priv['is_admin'] == $is_admin && $priv['roleid'] == $roleid && $priv['action'] == $action)
$checked = 'checked';
}
return $checked;
}
}
?>
|
Java
|
UTF-8
| 509 | 2.1875 | 2 |
[] |
no_license
|
package io.github.totom3.commons.binary;
import java.io.IOException;
/**
*
* @author Totom3
*/
public class DeserializingException extends IOException {
private static final long serialVersionUID = 1L;
public DeserializingException() {
}
public DeserializingException(String message) {
super(message);
}
public DeserializingException(String message, Throwable cause) {
super(message, cause);
}
public DeserializingException(Throwable cause) {
super(cause);
}
}
|
C++
|
UTF-8
| 6,722 | 3.546875 | 4 |
[] |
no_license
|
#include <vector>
#include <string>
#include <iostream>
#include <AutomatoFinito.hpp>
AutomatoFinito::AutomatoFinito(int n, std::string terminalSymbols, std::vector<int> initStates,
std::vector<int> acceptingStates, std::vector<Transition> transitions)
{
this->numStates = n;
this->terminalSymbols = terminalSymbols;
this->initStates = initStates;
this->bIsAFD = (int)initStates.size() == 1;
this->acceptingStates = acceptingStates;
this->states = std::vector<State>(n);
this->insertTransitions(transitions);
this->setAcceptingStates(acceptingStates);
}
/**
* bool AutomatoFinito::setAcceptingStates(std::vector<int> acceptingStates)
*
* Initially sets every state isFinal flag to false
* Then, loops through the acceptingStates vector, and given the state id,
* sets the correspondent state flag isFinal to true
*
* @param std::vector<int> acceptingStates vector containing all state ids
* @return void
*/
void AutomatoFinito::setAcceptingStates(std::vector<int> acceptingStates)
{
for (int i = 0; i < this->numStates; ++i) this->states[i].setFinal(false);
for (auto u : acceptingStates) this->states[u].setFinal(true);
}
/**
* bool AutomatoFinito::isValidSymbol(char ch)
*
* Check if a symbol is terminal by looping through the terminalSymbols vector
*
* @param char ch destination edge id
* @return bool valid or not
*/
bool AutomatoFinito::isValidSymbol(char ch)
{
if (ch == '-') return true;
for (auto u : this->terminalSymbols)
if (ch == u) return true;
std::cout << "ERRO: Caractér '" << ch << "' não é símbolo terminal." << '\n';
return false;
}
/**
* bool AutomatoFinito::indexOutOfRange(int src, int dest)
*
* Checks if the source and destination Ids of an edge are valid, that is,
* it respects the interval [0, numStates - 1]
*
* @param int src source edge id
* @param int dest destination edge id
* @return bool valid or not
*/
bool AutomatoFinito::indexOutOfRange(int src, int dst)
{
if (src < 0 || src >= this->numStates || dst < 0 || dst >= this->numStates)
{
std::cout << "ERRO: Índices não respeitam a numeração de estados." << '\n';
return true;
}
return false;
}
/**
* void AutomatoFinito::insertTransition(Transition transition)
*
* Insert a single transition in the automata, checking if the data
* is respects the automata constraints
*
* @param Transition transition Automata edge
* @return void
*/
void AutomatoFinito::insertTransition(int src, int dst, char ch)
{
if (!isValidSymbol(ch) || indexOutOfRange(src, dst)) return;
this->states[src].insertTransition(Transition(src, dst, ch));
}
/**
* void AutomatoFinito::insertTransitions(std::vector<Transition> transitions)
*
* For every Transition object containing the data of an edge, check if
* the data is valid (not out of bounds or is terminal character) and
* pushes it to the transition vector of the source state.
*
* @param std::vector<Transition> transitions Automata edges
* @return void
*/
void AutomatoFinito::insertTransitions(std::vector<Transition> transitions)
{
for (int i = 0; i < (int)transitions.size(); ++i)
{
Transition t = transitions[i];
if (!isValidSymbol(t.edge) || indexOutOfRange(t.source, t.dest)) continue;
this->states[t.source].insertTransition(t);
}
}
/**
* void AutomatoFinito::printTrasition()
*
* Print each transition of all the states in the automata
*/
void AutomatoFinito::printTransition()
{
for (auto u : this->states)
{
for (int i = 0; i < (int)u.transitions.size(); ++i)
{
Transition t = u.transitions[i];
std::cout << "(" << t.source << ", " << t.dest << ", " << t.edge << ")" << '\n';
}
}
}
/**
* void AutomatoFinito::isValidChain(std::string str, int stateId, int currIdx)
*
* Determines if a chain is valid by running a DFS on the automata.
* Given a state 's' and the current character 'ch' of the chain, check if there is a possible
* path that matches 'ch' and the transitions that start from 's'.
* If so, recursively call isValidChain(), incrementing the index and using one of the
* states that are adjacent to 's'.
*
* @param std::string str string representing the chain
* @param int stateId current state id
* @param int currIdx current index of chain
* @return bool isValid chain validation
*/
bool AutomatoFinito::isValidChain(std::string str, int stateId, int currIdx)
{
if (currIdx >= (int)str.size())
return this->states[stateId].getFinal();
State currState = this->states[stateId];
// Test all transitions of 'stateId'
for (int i = 0; i < (int)currState.transitions.size(); ++i)
{
Transition t = currState.transitions[i];
// Call next DFS phase
if (t.edge == str[currIdx] && isValidChain(str, t.dest, currIdx + 1))
{
return true;
}
// Lambda
else if (t.edge == '-' && isValidChain(str, t.dest, currIdx))
{
return true;
}
}
return false; // Didnt find transition that matched current chain symbol
}
/**
* void AutomatoFinito::runSimulation(std::vector<std::string> inputs)
*
* For each user input string, determines if the current chain is valid
* by calling the isValidChain() function.
* If the automata is non-deterministic, call the validation function
* for every initial state.
*
* @param std::vector<std::string> inputs chains to be determined
* @return none prints a message that indicates whether the chain is valid or not
*/
void AutomatoFinito::runSimulation(std::vector<std::string> inputs)
{
for (auto chain : inputs)
{
bool foundSolution = false;
for (auto stateId : this->initStates)
{
if (isValidChain(chain, stateId, 0))
{
foundSolution = true;
break;
}
}
std::cout << (foundSolution ? "aceita" : "rejeita") << '\n';
}
}
/**
* std::string AutomatoFinito::getAutomataType()
*
* Returns whether automata is deterministic or non-deterministic
*
* @return std::string automataType Deterministic or Non-Deterministic
*/
std::string AutomatoFinito::getAutomataType()
{
return this->bIsAFD ? "Determinístico": "Não Determinístico";
}
|
C++
|
UHC
| 1,290 | 3.71875 | 4 |
[] |
no_license
|
//ڷᱸ 9 ǽ 4 _correct
#include<iostream>
#include<vector>
using namespace std;
class isLess {
public:
bool operator()(const int a, const int b)const {
//int a,b Է¹Ƽ
if (a>b) {
return true;
}
else {
return false;
}
}
};
class PQ {
private:
vector<int>v;
public:
int size() {
return v.size();
}
bool empty() {
return v.size() == 0;
}
void insert(int e) {
vector<int>::iterator p = v.begin(); //ݺ
isLess C; //
if (v.empty()) { //켱 ť
v.insert(p, e); //beginտ e
}
else {
while (p != v.end() && C(e, *p)) { //ݺڰ Ű Һ e
++p; //ݺ ̵
}
v.insert(p, e); //pտ e
}
}
int min() { // Ҹ ȯ
return v.back(); //
}
void removeMin() {
v.pop_back();
}
void print() {
for (vector<int>::iterator iter = --v.end(); iter != v.begin(); --iter) {
cout << *iter << ' ';
}
cout << *v.begin() << endl;
}
};
int main() {
int t, n;
cin >> t; //Ʈ̽ Է
for (int i = 0; i < t; i++) {
cin >> n;
PQ pq;
int x = 0;
for (int j = 0; j < n; j++) {
cin >> x;
pq.insert(x);
}
pq.print();
}
}
|
Java
|
UTF-8
| 1,809 | 2.40625 | 2 |
[] |
no_license
|
import java.util.ArrayList;
public class AdminOperation {
public static void updateGames(String game_name, String console, int players, String genre, String year, String developer, String publisher, String price, String discount, int quantity, String description) throws ClassNotFoundException{
GameGateway game = new GameGateway();
game.setGame_name(game_name);
game.setConsole(console);
game.setPlayers(players);
game.setGenre(genre);
game.setRelease_date(year);
game.setDeveloper(developer);
game.setPublisher(publisher);
game.setPrice(price);
game.setDiscount(discount);
game.setQuantity(quantity);
game.setGame_description(description);
game.update();
}
public static void updateDiscount(String game_name, String discount) throws ClassNotFoundException{
GameGateway game = new GameGateway();
game.setGame_name(game_name);
game.setDiscount(discount);
game.updateDiscount();
}
public static void insertGames(String game_name, String console, int players, String genre, String year, String developer, String publisher, String price, String discount, int quantity, String description) throws ClassNotFoundException{
GameGateway game = new GameGateway();
game.setGame_name(game_name);
game.setConsole(console);
game.setPlayers(players);
game.setGenre(genre);
game.setRelease_date(year);
game.setDeveloper(developer);
game.setPublisher(publisher);
game.setPrice(price);
game.setDiscount(discount);
game.setQuantity(quantity);
game.setGame_description(description);
game.insert();
}
}
|
C++
|
UTF-8
| 3,291 | 2.953125 | 3 |
[] |
no_license
|
#include <iostream>
#include <regex>
#include <string>
#include <fstream>
#include <vector>
class Mange{
public:
std::fstream f;
std::string tmp = "" , res = "" , data = "";
public : std::string readFile(std::string path){
res = "";tmp = "";
f.open(path,std::ios::in);
while(getline(f,tmp)){
res.append(tmp);
res.append("\n");
}
f.close();
return res;
}
public : std::vector<std::string> getMatchData(std::string src , std::string reg , std::string removeString){
std::regex st_re(reg);
std::smatch m;
std::vector<std::string> v;
tmp = "";
while(std::regex_search(src,m,st_re)){
for(std::string d : m){
v.push_back(replaceAll(d,removeString,""));
}
src = m.suffix().str();
}
return v;
}
public : std::string replaceAll(std::string src , std::string oldString , std::string newString){
std::string::size_type pos(0);
while((pos = src.find(oldString)) != std::string::npos){
src.replace(pos,oldString.length(),newString);
}
return src;
}
public : void printHTML(std::string filePath){
data = readFile(filePath);
for(std::string d : getMatchData(data , "href=\"(.+?\\.(h|ht|htm|html|sht|shtm|shtml)\")", "href=\"")){
std::cout << d << std::endl;
}
}
public : void printImage(std::string filePath){
data = readFile(filePath);
for(std::string d : getMatchData(data , "src=\"(.+?\\.(jp|jpg|jpeg|png|gif)\")", "src=\"")){
std::cout << d << std::endl;
}
}
public : void printHELP(char *ar[]){
std::cout << "Usage: "<< ar[0] << " [OPTION]\n"<<std::endl;
std::cout <<"\t--printHTML|--HTML|HTML|--html|html : print all html url\n\t--printIMG|-IMG|IMG|--img|img : print all image url\n\t-f : select file path\n\t--help|-help|-h : print help\n\n" << std::endl;
std::cout <<"\t" << ar[0] << " -f file Patter removeString\n" <<std::endl;
std::cout <<"\t" << ar[0] << " -f file --printHTML\n" <<std::endl;
std::cout <<"\t" << ar[0] << " -f file --printIMG\n" <<std::endl;
}
};
void check(char *ar[]){
Mange m;
std::string opt = ar[1];
if("-f" == opt){
std::string fopt = ar[2];
if(fopt != ""){
std::string opt2 = ar[3];
if("--printHTML" == opt2 ||"html" == opt2||"--html" == opt2||"HTML" == opt2 || "--HTML" == opt2){
m.printHTML(fopt);
}else if("--printIMG" == opt2 ||"IMG" == opt2||"--IMG" == opt2||"--img" == opt2||"img" == opt2){
m.printImage(fopt);
}else{
if(opt2 != ""){
std::string opt3 = ar[4];
if(opt3 != ""){
std::string data = m.readFile(fopt);
for(std::string d : m.getMatchData(data , opt2, opt3)){
std::cout << d << std::endl;
}
}else{
m.printHELP(ar);
}
}else{
m.printHELP(ar);
}
}
}else{
m.printHELP(ar);
}
//ttt
}else if("--help" == opt || "-help" == opt || "-h" == opt){
//std::cout << "this help " <<std::endl;
m.printHELP(ar);
}
else{
std::cout << "invalid : " << ar[1]<<std::endl;
}
}
int main(int argc , char *argv[]){
if(argc < 2){
std::cout << "Usage: "<< argv[0] << " [OPTION]"<<std::endl;
std::cout << "Try '" << argv[0] << " --help' for more options."<<std::endl;
}else{
check(argv);
}
//std::cout << std::regex_match(res,m,st_re) << std::endl;
//std::cout << res << std::endl;
/*
while(std::regex_search(res,m,re)){
std::cout << "hello" << std::endl;
for(std::string s : m){
std::cout << s<<std::endl;
}
res = m.suffix().str();
}*/
return 0;
}
|
C++
|
UTF-8
| 1,346 | 3.28125 | 3 |
[] |
no_license
|
//
// maximize_distance_to_closest_person.cpp
//
// Created by omlenka on 21/04/20.
// Copyright © 2020 omkar lenka. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxDistToClosest(vector<int>& seats)
{
vector<int> dist(seats.size(), 0);
int left = -1;
//left to right
for(int i = 0;i<seats.size();i++)
{
if(seats[i] == 1)
{
left = i;
}
else
{
if(left != -1)
{
int d = i - left;
dist[i] = d;
}
}
}
//right to left
int right = -1;
int max_d = 0;
for(int i = seats.size()-1;i>=0;i--)
{
if(seats[i] == 1)
{
right = i;
}
else
{
if(right != -1)
{
int d = right-i;
if(dist[i])
dist[i] = min(dist[i], d);
else
dist[i] = d;
}
if(dist[i] > max_d)
max_d = dist[i];
}
}
return max_d;
}
};
|
JavaScript
|
UTF-8
| 324 | 4.15625 | 4 |
[] |
no_license
|
//Write a function that rearranges an integer into its largest possible value.
superSize(123456) //654321
superSize(105) // 510
superSize(12) // 21
function superSize(num){
if (num < 10) {
return num;
} else {
var r = String(num).split("").sort().reverse().join("");
return Number(r);
}
}
superSize(21)
|
Java
|
UTF-8
| 568 | 2.71875 | 3 |
[] |
no_license
|
package com.aos.dynatrace.lambda.monitor.exception;
/**
* @author Wagner Alves
*/
public class ExceptionUtils {
/**
* It returs stackTrace as a string
*
* @param e
* @return
*/
public static String getStackTrace(Exception e) {
StringBuilder str = new StringBuilder();
StackTraceElement[] stackTrace = e.getStackTrace();
for (int i = 0; i < stackTrace.length; i++) {
str.append(stackTrace[i]);
str.append(" ");
}
return str.toString();
}
}
|
C++
|
UTF-8
| 232 | 3.03125 | 3 |
[] |
no_license
|
#include <stdio.h>
int main()
{
long long n, i, sum=0;
scanf("%lld",&n);
/* if the number can be divide by 3, then add it to sum */
for(i=1;i<=n;i++){
if(i%3==0) sum+=i;
}
printf("%lld\n",sum);
return 0;
}
|
C++
|
UTF-8
| 2,801 | 3.3125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
#include <vector>
#include <queue>
#include <string>
#include <cstring>
/*
This is actually an extension of the 1-D rain trapping problem.
Reccll the 1-D situation, we can have a two-pointer solution.
We maintain two pointers pointed to current positions as well as the maximum height visited by these pointers.
Each time we pick up one of the two pointed position and compute water capacity of that bar directly.
Choices are made by comparing heights of the two pointed bar, as we will be safe to fill the shorter one because
water won't overflow to the other side (with a higher bar). Capacity is determined through the current maximum height,
which should always come from the same side of the current bar (otherwise we should fill bar from the other side).
Finally the two pointers will meet at one point, finishing the process.
The 2-D situation is basiclly the same, despite the 4-direction possibility. Instead of two boundary in a line,
we take the outmost rectangle as initial boundary. The simple comparision is replaced by picking up a boundary bar
with minimum height (using a heap). Also water filled is determined by the visited maximum height. Notice that once
the bar is filled, change its height and push it into the heap for further comparision. Higher nodes should be directly
pushed into the heap.
*/
class Solution {
public:
int gox[4]={-1,1,0,0}, goy[4]={0,0,1,-1};
struct node{
int y,x,h;
node(int _y, int _x, int _h) : y(_y), x(_x), h(_h) {}
bool operator < (const node &other) const {
return h > other.h;
}
};
int vis[115][115];
int trapRainWater(vector<vector<int>>& heightMap) {
priority_queue<node> que;
int m = heightMap.size(), n = heightMap[0].size();
for(int i = 0;i < m;i++)
que.push(node(i,0,heightMap[i][0])),
que.push(node(i,n-1,heightMap[i][n-1]));
for(int i = 1;i < n-1;i++)
que.push(node(0,i,heightMap[0][i])),
que.push(node(m-1,i,heightMap[m-1][i]));
int maxH = 0, ans = 0;
memset(vis,0,sizeof(vis));
while(!que.empty()){
node now = que.top(); que.pop();
maxH = max(maxH,now.h);
vis[now.y][now.x] = 1;
for(int i = 0;i < 4;i++){
int x = now.x + gox[i], y = now.y + goy[i];
if(x >= n || y >= m || x < 0 || y < 0 || vis[y][x]) continue;
if(heightMap[y][x] < maxH){
ans += maxH-heightMap[y][x];
heightMap[y][x] = maxH;
}
que.push(node(y,x,heightMap[y][x]));
}
}
return ans;
}
};
int main() {
}
|
JavaScript
|
UTF-8
| 3,730 | 2.625 | 3 |
[] |
no_license
|
define(function(require) {
var utils = require('utils');
var Cell = require('cell');
var DEFAULTWIDTH = 100;
function createStyleSheet(id, numCols, widths) {
var width = widths[0];
var left = width - 1;
var rules = '#sheet-' + id + ' .cell.label-col {' +
'left: 0; ' +
'width: ' + width + 'px;' +
'}\n';
for(var i = 1; i <= numCols; i++) {
width = widths[i] || DEFAULTWIDTH;
rules += '' +
'#sheet-' + id + ' .cell.col-' + utils.columnName(i) + ' {' +
'left: ' + left + 'px; ' +
'width: ' + width + 'px;' +
'}' +
'\n';
left += width - 1;
}
return utils.customStyleSheet(rules);
}
function createLabelRow(numCols) {
var labelRow = utils.createElement('div', { 'class': 'label-row' });
var emptyEl = createLabelCell('label-col label-empty');
labelRow.appendChild(emptyEl);
for(var i = 1; i <= numCols; i++) {
var name = utils.columnName(i);
var cell = createLabelCell('col-' + name, name);
var handle = utils.createElement('div', { 'class': 'handle' });
cell.appendChild(handle);
labelRow.appendChild(cell);
}
return labelRow;
}
function createLabelCell(className, text) {
return utils.createElement('div', {
'class': 'cell label ' + className
}, text);
}
var count = 0;
function SpreadSheet() {
// var stylesheet = css.sheet;
this.id = count++;
this.cells = [];
// this.selection = [1, 1];
this.el = utils.createElement('div', {
id: 'sheet-' + this.id,
'class': 'sheet'
});
this.el.addEventListener('dblclick', function(e) {
var target = e.target;
var cellEl = utils.findAncestor(e.target, 'cell-data');
if(cellEl) {
var row = +cellEl.dataset.row;
var col = +cellEl.dataset.column;
this.cells[row - 1][col - 1].editMode();
}
}.bind(this), false);
this.el.addEventListener('click', function(e) {
var target = e.target;
var cellEl = utils.findAncestor(e.target, 'cell-data');
if(cellEl) {
var row = +cellEl.dataset.row;
var col = +cellEl.dataset.column;
this.currentCell.unSelect();
this.currentCell = this.cells[row - 1][col - 1];
this.currentCell.select();
}
}.bind(this), false);
// TODO: compute rows cols that will fit in viewport
var numRows = 20, numCols = 15;
var labels = {
cols: {
width: [45]
},
rows: {
height: []
}
};
var styleEl = createStyleSheet(this.id, numCols, labels.cols.width);
styleEl.id = 'spreadsheet-rules-' + this.id;
var createRow = function createRow(num) {
var row = utils.createElement('div', {
'class': 'row'
});
var label = createLabelCell('label-col', num);
row.appendChild(label);
var cells = [];
for(var i = 1; i <= numCols; i++) {
var cell = new Cell(num, i);
row.appendChild(cell.el);
cells.push(cell);
}
this.cells.push(cells);
return row;
}.bind(this);
this.el.appendChild(createLabelRow(numCols));
for(var j = 1; j <= numRows; j++) {
this.el.appendChild(createRow(j));
}
this.currentCell = this.cells[0][0];
this.currentCell.select();
utils.$('#sheets').appendChild(this.el);
}
SpreadSheet.prototype.show = function spreadSheetLoad() {
this.el.classList.add('active');
};
SpreadSheet.prototype.show = function spreadSheetLoad() {
this.el.classList.remove('active');
};
SpreadSheet.prototype.load = function spreadSheetLoad(data) {
// TODO: load data
};
return SpreadSheet;
});
|
C++
|
UTF-8
| 1,802 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright @ 2014 - 2017 Personal
* All Rights Reserved.
*/
#ifndef ANT_ABSTRACTDATABLOCK_H
#define ANT_ABSTRACTDATABLOCK_H
#ifndef __cplusplus
# error ERROR: This file requires C++ compilation (use a .cpp suffix)
#endif
/*---------------------------------------------------------------------------*/
// Include files
#ifndef ANT_NEWTYPESDEFINE_H
# include "Ant_NewTypesDefine.h"
#endif
#ifndef ANT_OBJECT_H
# include "Ant_Object.h"
#endif
/*---------------------------------------------------------------------------*/
// Namespace
namespace antsupporter {
/*---------------------------------------------------------------------------*/
// Class declare
/**
* Definition of abstract interface for a data block.
*
* It only define interfaces, it does not provide implementation, you should
* sub-class it to implement the interface.
*/
class Ant_AbstractDataBlock : public virtual Ant_Object
{
public:
Ant_AbstractDataBlock();
virtual ~Ant_AbstractDataBlock();
/**
* Get size of the data block.
*
* @retval size of the data block in bytes.
*/
virtual size_t getLength() = 0;
/**
* Get pointer to raw data of the data block.
*
* @retval pointer to the data of the data block.
*/
virtual const void* getData() = 0;
private:
// Disable the copy constructor and operator =
Ant_AbstractDataBlock(const Ant_AbstractDataBlock&);
Ant_AbstractDataBlock& operator = (const Ant_AbstractDataBlock&);
};
/*---------------------------------------------------------------------------*/
// Namespace
}
/*---------------------------------------------------------------------------*/
#endif // ANT_ABSTRACTDATABLOCK_H
/*---------------------------------------------------------------------------*/
/* EOF */
|
Java
|
UTF-8
| 2,466 | 2.6875 | 3 |
[] |
no_license
|
package com.mivas.myharmonicasongs.util;
import android.util.Log;
import com.mivas.myharmonicasongs.database.handler.NoteDbHandler;
import com.mivas.myharmonicasongs.database.handler.SongDbHandler;
import com.mivas.myharmonicasongs.database.model.DbNote;
import com.mivas.myharmonicasongs.database.model.DbSong;
import java.util.ArrayList;
import java.util.List;
/**
* Util class for adding a song on the first run.
*/
public class FirstRunUtils {
public static void addSampleSong() {
DbSong dbSong = new DbSong();
dbSong.setTitle("Happy Birthday Sample Song");
dbSong.setAuthor("");
SongDbHandler.insertSong(dbSong);
long songId = dbSong.getId();
List<DbNote> dbNotes = new ArrayList<DbNote>();
dbNotes.add(new DbNote(6, true, "Ha", 0, 0, 0, songId));
dbNotes.add(new DbNote(6, true, "ppy", 0, 1, 0, songId));
dbNotes.add(new DbNote(6, false, "birth", 0, 2, 0, songId));
dbNotes.add(new DbNote(6, true, "day", 0, 3, 0, songId));
dbNotes.add(new DbNote(7, true, "to", 0, 4, 0, songId));
dbNotes.add(new DbNote(7, false, "you", 0, 5, 0, songId));
dbNotes.add(new DbNote(6, true, "Ha", 1, 0, 0, songId));
dbNotes.add(new DbNote(6, true, "ppy", 1, 1, 0, songId));
dbNotes.add(new DbNote(6, false, "birth", 1, 2, 0, songId));
dbNotes.add(new DbNote(6, true, "day", 1, 3, 0, songId));
dbNotes.add(new DbNote(8, false, "to", 1, 4, 0, songId));
dbNotes.add(new DbNote(7, true, "you", 1, 5, 0, songId));
dbNotes.add(new DbNote(6, true, "Ha", 2, 0, 0, songId));
dbNotes.add(new DbNote(6, true, "ppy", 2, 1, 0, songId));
dbNotes.add(new DbNote(9, true, "birth", 2, 2, 0, songId));
dbNotes.add(new DbNote(8, true, "day", 2, 3, 0, songId));
dbNotes.add(new DbNote(7, true, "dear", 2, 4, 0, songId));
dbNotes.add(new DbNote(7, false, "u", 2, 5, 0, songId));
dbNotes.add(new DbNote(6, false, "ser", 2, 6, 0, songId));
dbNotes.add(new DbNote(9, false, "Ha", 3, 0, 0, songId));
dbNotes.add(new DbNote(9, false, "ppy", 3, 1, 0, songId));
dbNotes.add(new DbNote(8, true, "birth", 3, 2, 0, songId));
dbNotes.add(new DbNote(7, true, "day", 3, 3, 0, songId));
dbNotes.add(new DbNote(8, false, "to", 3, 4, 0, songId));
dbNotes.add(new DbNote(7, true, "you", 3, 5, 0, songId));
NoteDbHandler.insertNotes(dbNotes);
}
}
|
Swift
|
UTF-8
| 1,202 | 2.96875 | 3 |
[] |
no_license
|
//
// SoundAsset.swift
// MyWayy
//
// Created by Robert Hartman on 12/2/17.
// Copyright © 2017 MyWayy. All rights reserved.
//
import Foundation
enum SoundAsset: String {
case activityComplete = "activity complete"
case addTime = "add time"
case pause = "pause"
case resume = "resume"
case done = "done"
case tone0 = "tone 0"
case tone1 = "tone 1"
case tone2 = "tone 2"
case tone3 = "tone 3"
case tone4 = "tone 4"
case tone5 = "tone 5"
case tone6 = "tone 6"
case tone7 = "tone 7"
case tone8 = "tone 8"
var assetName: String { return rawValue }
var fileTypeHint: String {
// All the above assets are of this type
return "com.microsoft.waveform-audio"
}
static let voiceAlertTone = SoundAsset.tone0
static func tone(at index: Int) -> SoundAsset? {
guard (index >= 0) && (index <= 8) else {
logError("No tone file exists with index \(index)")
return nil
}
guard let audioFile = SoundAsset(rawValue: "tone \(index)") else {
logError("Error looking up AudioFile with index \(index)")
return nil
}
return audioFile
}
}
|
Python
|
UTF-8
| 689 | 2.546875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# _*_ coding:utf-8 -*-
import pyautogui as pyag
import time
import cv2
print(pyag.position())
print(pyag.size())
while 1:
img = cv2.imread('/home/chen/datasets/5222.jpg')
cv2.imshow('1', img)
if cv2.waitKey(1) & 0xFF == ord('0'):
break
if cv2.waitKey(1) & 0xFF == ord('8'): #start
print('输入了8')
pyag.moveTo(1000, 500)
while 1:
pyag.scroll(-2)
time.sleep(0.5)
if cv2.waitKey(1) & 0xFF == ord('9'): #end
print('输入9成功')
break
cv2.destroyAllWindows()
# while True:
# num = input('退出')
# if num == str([0]):
# break
|
C++
|
UTF-8
| 2,683 | 2.546875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<long long> vll;
typedef pair<long long, long long> pll;
typedef vector<vector<long long>> mll;
typedef vector<pair<long long, long long>> vpl;
typedef long double ld;
typedef vector<long double> vld;
typedef vector<vector<long double>> mld;
typedef vector<bool> vbl;
typedef vector<vector<bool>> mbl;
#define minimize(a, b) (a = min(a, b))
#define maximize(a, b) (a = max(a, b))
const long long MOD = 1e9 + 7;
template <typename Type>
istream &operator>>(istream &in, vector<Type> &vec) {
ll n = vec.size();
for (int i = 0; i < n; i++)
in >> vec[i];
return in;
}
template <typename Type>
ostream &operator<<(ostream &out, vector<Type> &vec) {
for (auto val : vec)
out << val << " ";
out << endl;
return out;
}
vector<string> digits = {"1110111", "0010010", "1011101", "1011011", "0111010",
"1101011", "1101111", "1010010", "1111111", "1111011"};
int is_possible(const string &given, const string &target) {
int ans = 0;
for (int i = 0; i < 7; i++) {
if (given[i] == '0' && target[i] == '1')
ans++;
else if (given[i] == '1' && target[i] == '0')
return -1;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Input and Initialize
ll n, k;
cin >> n >> k;
mbl possible(n + 1, vbl(k + 1, false));
mll val(n, vll(10, -1));
// Store the input well
for (int i = 0; i < n; i++) {
string st;
cin >> st;
for (int d = 0; d < 10; d++) {
int on = is_possible(st, digits[d]);
val[i][d] = on;
}
}
// Make the possible matrix
possible[n][0] = true;
for (int i = n - 1; i >= 0; i--) {
set<int> shifts;
for (int d = 0; d < 10; d++) {
if (val[i][d] != -1)
shifts.insert(val[i][d]);
}
for (auto shift : shifts) {
for (int j = 0; j + shift <= k; j++) {
possible[i][j + shift] =
possible[i + 1][j] || possible[i][j + shift];
}
}
}
// Compute the answer
if (!possible[0][k]) {
cout << -1 << endl;
return 0;
}
string s = "";
for (int i = 0; i < n; i++) {
for (int d = 9; d >= 0; d--) {
if (val[i][d] == -1)
continue;
if (k >= val[i][d] && possible[i + 1][k - val[i][d]]) {
s.push_back('0' + d);
k -= val[i][d];
break;
}
}
}
cout << s << endl;
}
|
Java
|
UTF-8
| 377 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
package utilities;
import java.io.IOException;
public class Console {
public void clear() {
try {
if (System.getProperty("os.name").contains("Windows")) new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) { return;}
}
}
|
Markdown
|
UTF-8
| 2,100 | 2.671875 | 3 |
[] |
no_license
|
# Working with Mongo
Some notes on how to get the most out of Mongo.
## Text search
For text search, Mongo supports [these languages](https://docs.mongodb.com/manual/reference/text-search-languages/), at time of writing:
danish da
dutch nl
english en
finnish fi
french fr
german de
hungarian hu
italian it
norwegian nb
portuguese pt
romanian ro
russian ru
spanish es
swedish sv
turkish tr
Default is english. As a collection can only have one text index so at default, the whole collection can only have one language.
You can specify a field of the document that denotes the language of each document - in that case you can search different languages.
But it means you still can't mix languages in the same document, such as having a field of translations. Of course, you can still search, but word stemming won't work.
## Collation
Collation is the use of language-specific rules for sorting fields (both text and numeric). For example, should a and A be sorted as the same or differently, should "the" or other leading characters be ignored, etc. It has a lot of rules and wide support for languages: https://docs.mongodb.com/manual/reference/collation-locales-defaults/#collation-languages-locales
You can set a collation as default on a collection (but can't change it later). You can also set a collation on an index, and on just a specific operation. But the operations collation must match the collation on the index or the collection, if set. This means, if you want to set collation as default you can't practically change it so the whole collection will have to stick with one language.
You seem to be able to use a non-collated index with a temporarly collated operation, however.
## Query performance
https://docs.mongodb.com/manual/tutorial/analyze-query-plan/
https://studio3t.com/knowledge-base/articles/mongodb-query-performance/
https://medium.com/@zhaoyi0113/how-to-use-explain-to-improvement-mongodb-performance-3adadb1228f1
Simulate high latency to MongoDB:
https://medium.com/@kazushi/simulate-high-latency-network-using-docker-containerand-tc-commands-a3e503ea4307
|
Java
|
UTF-8
| 1,268 | 2.390625 | 2 |
[] |
no_license
|
package aljoschaRydzyk.viewportDrivenGraphStreaming.FlinkOperator.Batch;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.types.Row;
import aljoschaRydzyk.viewportDrivenGraphStreaming.FlinkOperator.GraphObject.EdgeGVD;
import aljoschaRydzyk.viewportDrivenGraphStreaming.FlinkOperator.GraphObject.VertexGVD;
import aljoschaRydzyk.viewportDrivenGraphStreaming.FlinkOperator.GraphObject.WrapperGVD;
public class WrapperRowMapWrapperGVD implements MapFunction<Row,WrapperGVD> {
@Override
public WrapperGVD map(Row row) throws Exception {
VertexGVD sourceVertex = new VertexGVD(
row.getField(1).toString(),
row.getField(3).toString(),
(long) row.getField(2),
(int) row.getField(4),
(int) row.getField(5),
(long) row.getField(6));
VertexGVD targetVertex = new VertexGVD(
row.getField(7).toString(),
row.getField(9).toString(),
(long) row.getField(8),
(int) row.getField(10),
(int) row.getField(11),
(long) row.getField(12));
EdgeGVD edge = new EdgeGVD(
row.getField(13).toString(),
row.getField(14).toString(),
row.getField(1).toString(),
row.getField(7).toString());
WrapperGVD wrapper = new WrapperGVD(sourceVertex, targetVertex, edge);
return wrapper;
}
}
|
JavaScript
|
UTF-8
| 631 | 2.859375 | 3 |
[] |
no_license
|
"use strict";
window.component_input = function() {
// Input type : File
let nodesArray = Array.prototype.slice.call(document.querySelectorAll('input[type=file]'));
nodesArray.forEach(function(element) {
element.addEventListener('change', function() {
let elementID = element.id;
let filepath = element.value;
let filename = filepath.substring(filepath.lastIndexOf('\\')+1);
let value = document.createTextNode(filename);
document.querySelectorAll('.custom-file-label[for='+elementID+']')[0].appendChild(value);
});
});
}
|
Go
|
UTF-8
| 523 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
package main
import (
uuid "github.com/satori/go.uuid"
"log"
"os"
)
func main() {
var (
bufferSize = 2000
bufferLimit = 1900
)
buf := make([]byte, 0, bufferSize)
file, err := os.Create("/tmp/uuid_single")
if err != nil {
panic(err)
}
defer func() {
_ = file.Close()
}()
for {
uid := uuid.NewV4()
buf = append(append(buf, uid.String()...), '\n')
if len(buf) > bufferLimit {
_, err := file.Write(buf)
if err != nil {
log.Fatal(err)
}
buf = make([]byte, 0, bufferSize)
}
}
}
|
C++
|
UTF-8
| 779 | 3.0625 | 3 |
[] |
no_license
|
#ifndef __ADJ_LIST_NETWORK_ARC_H__
#define __ADJ_LIST_NETWORK_ARC_H__
#include <bits/stdc++.h>
// 邻接表网边类
template <class WeightType>
struct ArcNode
{
int _adjVex; //弧头顶点的序号,指向目标节点
WeightType _weight; //边的权值
ArcNode<WeightType> *_nextArc; //下一条边结点的指针
ArcNode();
ArcNode(int adjVex, WeightType weight, ArcNode<WeightType> *nextArc = NULL);
};
template <class WeightType>
ArcNode<WeightType>::ArcNode()
//构造一个空的边
{
_nextArc = NULL;
_adjVex = -1;
}
template <class WeightType>
ArcNode<WeightType>::ArcNode(int adjVex, WeightType weight, ArcNode<WeightType> *nextArc)
{
_adjVex = adjVex;
_weight = weight;
_nextArc = nextArc;
}
#endif
|
Python
|
UTF-8
| 271 | 2.828125 | 3 |
[] |
no_license
|
"""Toplevel script for pymaze game - instanciate Game and then play it."""
import sys
from Game import Game
if len(sys.argv) != 2:
host, port = 'localhost', '8089'
else:
host, port = sys.argv[1].split(":")
game = Game("maze1.txt", host, int(port))
game.play()
|
Java
|
UTF-8
| 1,066 | 2.46875 | 2 |
[] |
no_license
|
package com.baidu.langshiquan.cache;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.baidu.langshiquan.base.FreeUnitTestBase;
import com.baidu.langshiquan.model.User;
/**
* Created by langshiquan on 17/9/30.
*/
public class SecondLevelUpdateCacheTest extends FreeUnitTestBase {
@Test
public void testCacheStrategy_READ_WRITE() {
Session session1 = sessionFactory.openSession();
Transaction transaction = session1.beginTransaction();
User user1 = (User) session1.get(User.class, 1);
System.out.println("user1:" + user1);
// 修改user
user1.setAddress("bj");
session1.update(user1);
transaction.commit();
// 同一session查询
User user2 = (User) session1.get(User.class, 1);
System.out.println("user2:" + user2);
// 其他session查询
Session session3 = sessionFactory.openSession();
User user3 = (User) session3.get(User.class, 1);
System.out.println("user3:" + user3);
}
}
|
SQL
|
ISO-8859-1
| 604 | 4.09375 | 4 |
[] |
no_license
|
-- sub-consultas: single-row - retornam apenas uma linha
-- realiza uma consulta a partir do resultado de outra consulta
-- sub-consulta executada antes da principal
-- fazem uso dos operadores de comparao de linhas simples: =, >, <, <>, !=
SELECT first_name, last_name, job_id, salary
FROM employees
WHERE salary > (SELECT AVG(NVL(salary,0))
FROM employees)
ORDER BY salary DESC;
-- utilizando o having
SELECT e.department_id, MAX(e.salary)
FROM employees e
GROUP BY e.department_id
HAVING MAX(e.salary) < (SELECT AVG(NVL(e2.salary,0))
FROM employees e2);
|
Java
|
UTF-8
| 408 | 2.28125 | 2 |
[] |
no_license
|
package ca.cours5b5.nicolasparr.donnees.partie;
import ca.cours5b5.nicolasparr.enumerations.ECouleur;
import ca.cours5b5.nicolasparr.global.GLog;
public class DCase {
private ECouleur couleur;
public ECouleur getCouleur() {
GLog.appel(this);
return couleur;
}
public void setCouleur(ECouleur couleur) {
GLog.appel(this);
this.couleur = couleur;
}
}
|
C++
|
UTF-8
| 8,260 | 3.75 | 4 |
[] |
no_license
|
#include <cstdlib>
#include <string>
#include <iostream>
#include <sstream>
#include "MyRational.h"
using namespace std;
/**
* Stores, displays, and manipulates rational numbers
*
* @author rwmeyer3
* @version 19.08.2020
*/
/**
* Default Constructor initializes 0/1.
* Rational number starts in simplified form.
*/
MyRational::MyRational() {
simplified = true;
numerator = 0;
denominator = 1;
}
/**
* Constructor that allows for choosing initial numerator and denominator upon creation.
* Rational Number is not assumed to be in simplified form.
*
* @param num Numerator choosen
* @param denom Denominator choosen
* @throws invalid_argument when denom is 0
*/
MyRational::MyRational(int num, int denom) {
simplified = false;
numerator = num;
if (denom == 0) {
throw invalid_argument("Rational number is undefined when denominator is 0.");
}
else {
denominator = denom;
}
}
/**
* Set new numerator value.
* @param num New numerator
*/
void MyRational::setNumerator(int num) {
numerator = num;
simplified = false;
}
/**
* Set new denominator value.
* @param denom New denominator
*/
void MyRational::setDenominator(int denom) {
if (denom == 0) {
throw invalid_argument("Rational number is undefined when denominator is 0.");
}
else {
denominator = denom;
}
simplified = false;
}
/**
* Returns numerator value.
* @return int numerator
*/
int MyRational::getNumerator() {
return numerator;
}
/**
* Returns denominator value.
* @return int denominator
*/
int MyRational::getDenominator() {
return denominator;
}
/**
* Returns a string with the fraction representation of the rational number.
* @return string fraction representation of rational number
*/
string MyRational::toString() {
stringstream buffer;
buffer << this->numerator << " / " << this->denominator << endl;
return buffer.str();
}
/**
* Returns a string with the fraction representation of the rational number and a statement of whether the fraction is confirmed to be in simplest form or not.
* @return string fraction representation of rational number and simplified state
*/
string MyRational::toStringVerbose() {
stringstream buffer;
buffer << this->numerator << " / " << this->denominator << "endl" << "This Rational number is" << ((simplified) ? "" : " possibly not") << " in simplest terms." << endl;
return buffer.str();
}
/**
* Modifies the existing object in order to simnplify the numerator and denominator into simplest terms.
* Nuemrator and Denominator are relatively prime and if the rational number is negative, then the numerator is negative.
* Also returns a copy of the object for external use.
*
* @return MyRational a copy of this rational number in simplest terms
*/
MyRational MyRational::simplify() {
int check = 2;
while (check < numerator && check < denominator) {
if (numerator % check == 0 && denominator % check == 0) {
numerator /= check;
denominator /= check;
}
++check;
}
if (denominator < 0) {
denominator *= -1;
numerator *= -1;
}
simplified = true;
return *this;
}
/**
* Calculates the sum of this rational number and another rational number to create a third, new rational number object.
* this + second = sum
* Values in the sum object are not simplified.
*
* @param second pointer to another rational number object
* @return MyRational sum of two rational numbers
*/
MyRational MyRational::addRaw(MyRational* second) {
int newDenom = this->getDenominator() * second->getDenominator();
int newNum = this->getNumerator() * second->getDenominator() + second->getNumerator() * this->getDenominator();
return MyRational(newNum, newDenom);
}
/**
* Calculates the difference of this rational number and another rational number to create a third, new rational number object.
* this - second = difference
* Values in the difference object are not simplified.
*
* @param second pointer to another rational number object
* @return MyRational difference of two rational numbers
*/
MyRational MyRational::subtractRaw(MyRational* second) {
MyRational* neg = &MyRational(-1, 1);
MyRational* negate = &(second->multiplyRaw(neg));
MyRational output = this->addRaw(negate);
delete(neg);
delete(negate);
return output;
}
/**
* Calculates the product of this rational number and another rational number to create a third, new rational number object.
* this * second = product
* Values in the product object are not simplified.
*
* @param second pointer to another rational number object
* @return MyRational product of two rational numbers
*/
MyRational MyRational::multiplyRaw(MyRational* second) {
int newDenom = this->getDenominator() * second->getDenominator();
int newNum = this->getNumerator() * second->getNumerator();
return MyRational(newNum, newDenom);
}
/**
* Calculates the quotient of this rational number and another rational number to create a third, new rational number object.
* this / second = quotient
* Values in the quotient object are not simplified.
*
* @param second pointer to another rational number object
* @return MyRational quotient of two rational numbers
*/
MyRational MyRational::divideRaw(MyRational* second) {
MyRational* invert = &(second->invert());
MyRational output = this->multiplyRaw(invert);
delete(invert);
return output;
}
/**
* Calculates the sum of this rational number and another rational number to create a third, new rational number object.
* this + second = sum
* Values in the sum object are simplified.
*
* @param second pointer to another rational number object
* @return MyRational sum of two rational numbers
*/
MyRational MyRational::add(MyRational* second) {
return this->addRaw(second).simplify();
}
/**
* Calculates the difference of this rational number and another rational number to create a third, new rational number object.
* this - second = difference
* Values in the difference object are simplified.
*
* @param second pointer to another rational number object
* @return MyRational difference of two rational numbers
*/
MyRational MyRational::subtract(MyRational* second) {
return this->subtractRaw(second).simplify();
}
/**
* Calculates the product of this rational number and another rational number to create a third, new rational number object.
* this * second = product
* Values in the product object are simplified.
*
* @param second pointer to another rational number object
* @return MyRational product of two rational numbers
*/
MyRational MyRational::multiply(MyRational* second) {
return this->multiplyRaw(second).simplify();
}
/**
* Calculates the quotient of this rational number and another rational number to create a third, new rational number object.
* this / second = quotient
* Values in the quotient object are simplified.
*
* @param second pointer to another rational number object
* @return MyRational quotient of two rational numbers
*/
MyRational MyRational::divide(MyRational* second) {
return this->divideRaw(second).simplify();
}
/**
* Swap numerator and denominator as if rased to the power of -1
* @return MyRational inverted rational number
*/
MyRational MyRational::invert() {
return MyRational(this->getDenominator(), this->getNumerator());
}
/**
* Calculates the product of this rational number raised to an integer power to create a third, new rational number object.
* this ^ pow = product
* Values in the product object are not simplified.
*
* @param pow integer power
* @return MyRational product a rational number raised to an integer power
*/
MyRational MyRational::powerRaw(int pow) {
if (!pow) {
return MyRational(1, 1);
}
int newNum = this->numerator;
int newDenom = this->denominator;
for (int i = 0; i < pow - 1; i++) {
newNum *= this->numerator;
newDenom *= this->denominator;
}
return MyRational(newNum, newDenom);
}
/**
* Calculates the product of this rational number raised to an integer power to create a third, new rational number object.
* this ^ pow = product
* Values in the product object are simplified.
*
* @param pow integer power
* @return MyRational product a rational number raised to an integer power
*/
MyRational MyRational::power(int pow) {
return this->powerRaw(pow).simplify();
}
//int main() {
// return 0;
//}
|
PHP
|
UTF-8
| 532 | 2.65625 | 3 |
[] |
no_license
|
<?php
//1、建立连接(连接数据库)(搭桥)
$conn = mysql_connect('localhost','root','root');
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}else{
//2、选择数据库(目的地)
mysql_select_db("mydb1902",$conn);
//3、执行数据库的SQL语句(增删改查)
$sqlstr = "insert into usertable(username,userpass,usersex) values('jiangzemin','123456','男')";
mysql_query($sqlstr,$conn);
//4、关闭数据库
mysql_close($conn);
}
?>
|
PHP
|
UTF-8
| 3,496 | 2.75 | 3 |
[] |
no_license
|
<?php
class Complaint{
private $conn;
private $table_name = "complaint";
//object properties
public $complaint_id;
public $customer_id;
public $amc_id;
public $date;
public $complaint_type_id;
public $status;
public function __construct($db){
$this->conn = $db;
}
function createComplaint(){
$this->customer_id=htmlspecialchars(strip_tags($this->customer_id));
$this->amc_id=htmlspecialchars(strip_tags($this->amc_id));
$this->date=htmlspecialchars(strip_tags($this->date));
$this->complaint_type_id=htmlspecialchars(strip_tags($this->complaint_type_id));
$this->status=htmlspecialchars(strip_tags($this->status));
$query = "INSERT INTO ". $this->table_name;
$query .= "(customerid, amcid, date, complainttypeid, status) VALUES";
$query .= "('". $this->customer_id ."','". $this->amc_id ."','".$this->date."','". $this->complaint_type_id ."',";
$query .= "'". $this->status ."')";
if ($this->conn->query($query) === TRUE) {
return true;
}
else {
return false;
}
}
public static function getAllComplaints($db){
$query = "SELECT complaint.complaintid, customer.customerid ,customer.billingname,complaint.amcid,complaint.date,complaint_type.complainttype,complaint.status
FROM complaint
INNER JOIN customer ON customer.customerid=complaint.customerid
INNER JOIN complaint_type ON complaint.complainttypeid=complaint_type.complainttypeid";
$result = $db->query($query);
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
return json_encode($output);
}
public static function getComplaintById($complaint_id,$db){
$query = "SELECT * FROM complaint WHERE complaintid='".$complaint_id."'";
$result = $db->query($query);
$output = array();
while($row = $result->fetch_assoc()) {
$output = $row;
}
return $output;
}
public static function getComplaintid($customer_id,$amc_id,$date,$complaint_type_id,$db){
$customer_id=htmlspecialchars(strip_tags($customer_id));
$amc_id=htmlspecialchars(strip_tags($amc_id));
$date=htmlspecialchars(strip_tags($date));
$complaint_type_id=htmlspecialchars(strip_tags($complaint_type_id));
$query = "SELECT complaintid FROM complaint WHERE customerid='".$customer_id."'";
$query .= "AND amcid='".$amc_id."' AND date='".$date."' AND complainttypeid='".$complaint_type_id."'";
$result = $db->query($query);
if($result->num_rows>0) {
$row = $result->fetch_assoc();
$output = $row['complaintid'];
return $output;
}else{
echo json_encode(array("message" => "Complaint not found."));
return false;
}
}
function updateComplaintById(){
$this->customer_id=htmlspecialchars(strip_tags($this->customer_id));
$this->amc_id=htmlspecialchars(strip_tags($this->amc_id));
$this->date=htmlspecialchars(strip_tags($this->date));
$this->complaint_type_id=htmlspecialchars(strip_tags($this->complaint_type_id));
$query = "UPDATE complaint SET customerid='".$this->customer_id."',amcid='".$this->amc_id."',";
$query .= " date='".$this->date."',complainttypeid='".$this->complaint_type_id."',";
$query .= "status='".$this->status."' WHERE complaintid='".$this->complaint_id."'";
if ($this->conn->query($query) === TRUE) {
return true;
} else {
return false;
}
}
function deleteComplaintById(){
$query = "DELETE FROM complaint WHERE complaintid='".$this->complaint_id."'";
if ($this->conn->query($query) === TRUE) {
return true;
} else {
return false;
}
}
}
?>
|
C++
|
UTF-8
| 2,645 | 2.875 | 3 |
[] |
no_license
|
#pragma once
#include <bits/stdc++.h>
namespace NodeFlow
{
double uniform_random()
{
return rand()*1.0/INT_MAX;
}
double guass_random(double m=0,double delta=1.0)
{
double u1 = NodeFlow::uniform_random();
double u2 = NodeFlow::uniform_random();
double z = sqrt(-2*log(u1))*sin(2*M_PI*u2);
return z*delta+m;
}
double glorot_uniform(double fan_in,double fan_out)
{
double limit = sqrt(6.0/(fan_in+fan_out));
double v = -limit+NodeFlow::uniform_random()*2*limit;
return v;
}
double constant(double m=0,double delta=1.0)
{
return m;
}
std::vector<int> create_random_int(int number,int range)
{
std::vector<int> n_list;
for (int i=0;i<range;i++)
{
n_list.push_back(i);
}
std::vector<int> ans;
int l = range;
for (int i=0;i<number;++i)
{
int index = rand() % l;
ans.push_back(n_list[index]);
n_list[index] = n_list[l-1];
l--;
}
return ans;
}
std::vector<double> onehot(unsigned int n,int range)
{
std::vector<double> ans(range,0);
ans[n] = 1.0;
return ans;
}
int argmax(std::vector<double> n)
{
int ans;
double max_=DBL_MIN;
for (int i=0;i<n.size();i++)
{
if (max_<n[i])
{
ans=i;
max_=n[i];
}
}
return ans;
}
class initializer
{
public:
double a_;
double b_;
initializer(double a=0,double b=1.0):a_(a),b_(b){}
virtual double init(){}
virtual std::shared_ptr<initializer> make_ptr(){return nullptr;}
};
class Constant:public initializer
{
public:
Constant(double a=0,double b=1.0):initializer(a,b){}
double init(){
return a_;
}
std::shared_ptr<initializer> make_ptr()
{
return std::shared_ptr<initializer>((initializer* )new Constant(a_,b_));
}
};
class Guass:public initializer
{
public:
Guass(double a=0,double b=1.0):initializer(a,b){}
double init(){
return NodeFlow::guass_random(a_,b_);}
std::shared_ptr<initializer> make_ptr()
{
return std::shared_ptr<initializer>((initializer* )new Guass(a_,b_));
}
};
class Glorot:public initializer
{
public:
Glorot(double a=0,double b=1.0):initializer(a,b){}
double init(){
return NodeFlow::glorot_uniform(a_,b_);}
std::shared_ptr<initializer> make_ptr()
{
return std::shared_ptr<initializer>((initializer* )new Glorot(a_,b_));
}
};
}
|
Python
|
UTF-8
| 1,424 | 3.9375 | 4 |
[] |
no_license
|
# Lazy buttons 2
# demonstrate using class in program which is using tkinter
from tkinter import *
# creating new class application on class frame
# it works because class object application is specialise type of object frame
class Application(Frame):
"""Application based on GUI with three buttons."""
def __init__(self, master):
"""Initialize frame."""
# passing master object to class application
super(Application, self).__init__(master)
# creating methods
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create three buttons which do nothing."""
# all buttons are attributes object class Application
# passing self to pass master object (Application)
# first button
self.bttn1 = Button(self, text="I do nothing!")
self.bttn1.grid()
# second button
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.configure(text="Me too!")
# third button
self.bttn3 = Button(self)
self.bttn3.grid()
self.bttn3["text"] = "The same thing works with me!"
root = Tk()
root.title("Lazy buttons 2")
root.geometry("400x500")
# creating app object and passing into master window
# app object call creating widgets method and make 3 buttons
# when I use app.creating_widgets() is makes buttons double
app = Application(root)
root.mainloop()
|
Java
|
UTF-8
| 9,107 | 2.765625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
/**
* Copyright (c) 2017 Ariel Favio Carrizo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'esferixis' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.esferixis.geometry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.esferixis.math.ExtraMath;
import com.esferixis.math.intervalarithmetic.FloatClosedInterval;
/**
* @author ariel
*
*/
public class Geometry {
private Geometry() {}
private static final float doublePI = ExtraMath.doublePI;
/**
* @post Halla la base del ángulo especificado
*/
public static float angleBase(float angle) {
return (float) Math.floor(angle / doublePI) * doublePI;
}
/**
* @pre El intervalo no puede ser nulo
* @post Halla la base del intervalo angular especificado
*/
public static float angleBase(FloatClosedInterval angleInterval) {
if ( angleInterval != null ) {
return angleBase(angleInterval.getMin());
}
else {
throw new NullPointerException();
}
}
/**
* @post Normaliza el ángulo especificado en el intervalo de 0 a 2 * pi
*/
public static float normalise(float angle) {
return angle - angleBase(angle);
}
/**
* @post Devuelve el ángulo mínimo tomando como referencia el ángulo mínimo
* especificado.
* Si sólo uno de ellos, devuelve ese ángulo.
* Si ambos son nulos devuelve null
*/
public static Float minAngle(float min, Float angle1, Float angle2) {
if ( ( angle1 != null ) && ( angle2 != null ) ) {
min = normalise(min);
angle1 = normalise(angle1);
angle2 = normalise(angle2);
if ( angle1 < min ) {
angle1 += doublePI;
}
if ( angle2 < min ) {
angle2 += doublePI;
}
return Math.min(angle1, angle2);
}
else if ( angle1 != null ) {
return angle1;
}
else if ( angle2 != null ) {
return angle2;
}
else {
return null;
}
}
/**
* @pre El iterable no puede ser nulo
* @post Devuelve el ángulo mínimo con la base especificada del iterable especificado
*/
public Float minAngle(float minBase, Iterable<Float> angles) {
if ( angles != null ) {
Float minAngle = null;
for ( Float eachAngle : angles ) {
minAngle = minAngle(minBase, minAngle, eachAngle);
}
return minAngle;
}
else {
throw new NullPointerException();
}
}
/**
* @pre El arrays de ángulos no puede ser nulo
* @post Devuelve el ángulo mínimo con la base especificada del iterable especificado
*/
public Float minAngle(float minBase, Float... angles) {
if ( angles != null ) {
return minAngle(minBase, Arrays.asList(angles));
}
else {
throw new NullPointerException();
}
}
/**
* @post Devuelve el ángulo máximo tomando como referencia el ángulo mínimo
* especificado.
* Si sólo uno de ellos, devuelve ese ángulo.
* Si ambos son nulos devuelve null
*/
public static Float maxAngle(float min, Float angle1, Float angle2) {
if ( ( angle1 != null ) && ( angle2 != null ) ) {
min = normalise(min);
angle1 = normalise(angle1);
angle2 = normalise(angle2);
if ( angle1 < min ) {
angle1 += doublePI;
}
if ( angle2 < min ) {
angle2 += doublePI;
}
return Math.max(angle1, angle2);
}
else if ( angle1 != null ) {
return angle1;
}
else if ( angle2 != null ) {
return angle2;
}
else {
return null;
}
}
/**
* @pre El iterable no puede ser nulo
* @post Devuelve el ángulo máximo con la base especificada del iterable especificado
*/
public Float maxAngle(float minBase, Iterable<Float> angles) {
if ( angles != null ) {
Float minAngle = null;
for ( Float eachAngle : angles ) {
minAngle = maxAngle(minBase, minAngle, eachAngle);
}
return minAngle;
}
else {
throw new NullPointerException();
}
}
/**
* @pre El arrays de ángulos no puede ser nulo
* @post Devuelve el ángulo máximo con la base especificada del iterable especificado
*/
public Float maxAngle(float minBase, Float... angles) {
if ( angles != null ) {
return maxAngle(minBase, Arrays.asList(angles));
}
else {
throw new NullPointerException();
}
}
/**
* @pre La diferencia entre los dos ángulos tiene que ser menor a 2*pi
* @post Crea un intervalo de ángulos con los ángulos especificados
*/
public static FloatClosedInterval makeAngleInterval(float startAngle, float endAngle) {
startAngle = startAngle - angleBase(startAngle);
endAngle = endAngle - angleBase(endAngle);
if ( endAngle < startAngle ) {
endAngle += doublePI;
}
return new FloatClosedInterval(startAngle, endAngle);
}
/**
* @post Calcula la intersección entre los dos intervalos de ángulos
* especificados
*
* <ARREGLAR IMPLEMENTACIÓN>
*/
public static List<FloatClosedInterval> angleIntervalIntersection(FloatClosedInterval angleInterval1, FloatClosedInterval angleInterval2) {
final List<FloatClosedInterval> result = new ArrayList<FloatClosedInterval>(2);
if ( containsAngle(angleInterval1, angleInterval2.getMin()) ) {
final float minBase = angleInterval2.getMin();
final float maxMin = Geometry.minAngle(minBase, angleInterval1.getMin(), minBase);
final float minMax = Geometry.minAngle(minBase, angleInterval1.getMax(), angleInterval2.getMax());
if ( minMax >= maxMin ) {
result.add(new FloatClosedInterval(maxMin, minMax));
}
}
if ( containsAngle(angleInterval2, angleInterval1.getMin()) ) {
final float minBase = angleInterval1.getMin();
final float maxMin = Geometry.minAngle(minBase, angleInterval2.getMin(), minBase);
final float minMax = Geometry.minAngle(minBase, angleInterval1.getMax(), angleInterval2.getMax());
if ( minMax >= maxMin ) {
result.add(new FloatClosedInterval(maxMin, minMax));
}
}
return Collections.unmodifiableList(result);
}
/**
* @pre El intervalo de ángulos no puede ser nulo
* @post Devuelve si el ángulo está contenido en el intervalo de ángulos
* especificado
*/
public static boolean containsAngle(FloatClosedInterval angleInterval, float angle) {
if ( angleInterval != null ) {
angle = angle - angleBase(angle);
angleInterval = angleInterval.sub( angleBase(angleInterval) );
if ( angle < angleInterval.getMin() ) {
angle += doublePI;
}
return angleInterval.contains(angle);
}
else {
throw new NullPointerException();
}
}
/**
* @pre El intervalo de ángulos no puede ser nulo
* @post Devuelve si el ángulo está contenido en el intervalo de ángulos
* especificado, excluyendo los extremos
*/
public static boolean containsAngleExcludingExtremes(FloatClosedInterval angleInterval, float angle) {
if ( angleInterval != null ) {
angle = angle - angleBase(angle);
angleInterval = angleInterval.sub( angleBase(angleInterval) );
if ( angle < angleInterval.getMin() ) {
angle += doublePI;
}
return angleInterval.containsExcludingExtremes(angle);
}
else {
throw new NullPointerException();
}
}
/**
* @post Devuelve ángulos repartidos, conteniendo los límites, con una distancia entre ellos
* no superior a 90°
* @param angleInterval
* @return
*/
public static float[] partialAngleIntervalSampling(FloatClosedInterval angleInterval) {
final int tangentVertices;
float[] angleSamples;
tangentVertices = (int) Math.ceil( angleInterval.length() / (Math.PI / 2.0f) ) + 1;
angleSamples = new float[tangentVertices];
for ( int i = 0 ; i<tangentVertices; i++ ) {
angleSamples[i] = angleInterval.linearInterpolation(i / (float) (tangentVertices-1));
}
return angleSamples;
}
}
|
Swift
|
UTF-8
| 4,311 | 2.609375 | 3 |
[] |
no_license
|
//
// speciesVC.swift
// CofeeGo
//
// Created by NI Vol on 10/15/18.
// Copyright © 2018 Ni VoL. All rights reserved.
//
import UIKit
import XLPagerTabStrip
class speciesVC: UIViewController, UITableViewDelegate,UITableViewDataSource,IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return IndicatorInfo(title : "Специи")
}
@IBOutlet weak var emptyAdditionalsView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
var species : [[String: Any]] = [[String: Any]]()
var selects : [Bool] = [Bool]()
override func viewDidLoad() {
super.viewDidLoad()
self.loadingIndicator.startAnimating()
self.loadingIndicator.isHidden = false
OrderData.tempSpecies = OrderData.currSpecies
OrderData.countSpecies = OrderData.tempSpecies.count
// tableView.isHidden = true
getSpeciesForSpot(spotId: "\(current_coffee_spot.id!)").responseJSON { (response) in
switch response.result {
case .success(let value):
self.species = value as! [[String : Any]]
if self.species.count > 0{
self.selects = [Bool](repeating: false, count: self.species.count)
self.emptyAdditionalsView.isHidden = true
self.tableView.isHidden = false
self.tableView.delegate = self
self.tableView.dataSource = self
self.loadingIndicator.stopAnimating()
self.loadingIndicator.isHidden = true
self.tableView.reloadData()
}
else{
self.emptyAdditionalsView.isHidden = false
print("nema")
}
break
case .failure(let error):
self.view.makeToast("Произошла ошибка загрузки, попробуйте еще раз")
self.loadingIndicator.isHidden = true
self.loadingIndicator.stopAnimating()
print(error)
break
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return species.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let addElem = species[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "speciesCell" , for : indexPath) as! speciesCell
cell.speciesNameLbl.text = addElem["name"] as? String
var isSelected = false
for i in 0..<OrderData.tempSpecies.count{
let value = OrderData.tempSpecies[i]
if "\(value["name"]!)" == "\(addElem["name"]!)"{
cell.checkMark.isHidden = false
selects[indexPath.row] = false
isSelected = true
break
}
}
if !isSelected{
cell.checkMark.isHidden = true
selects[indexPath.row] = true
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let addElem = species[indexPath.row]
if selects[indexPath.row]{
// selects[indexPath.row] = false
if OrderData.countSpecies < 5{
OrderData.tempSpecies.append(addElem)
OrderData.countSpecies += 1
} else{
// MAKE TOAST
}
} else {
// selects[indexPath.row] = true
var pos = 0
for i in 0..<OrderData.tempSpecies.count{
let value = OrderData.tempSpecies[i]
if "\(value["name"]!)" == "\(addElem["name"]!)"{
pos = i
break
}
}
OrderData.countSpecies -= 1
OrderData.tempSpecies.remove(at: pos)
}
tableView.reloadRows(at: [indexPath], with: .none)
}
}
|
Shell
|
UTF-8
| 507 | 3.3125 | 3 |
[
"ISC"
] |
permissive
|
#!/bin/bash
set -e
if [ ! -f "scripts/gcc.sh" ]
then
echo "Error: does not look like a root of Dancy source tree" 1>&2
exit 1
fi
if [ -f "./external/bin/x86_64-w64-mingw32-gcc" ]
then
echo "./external/bin/x86_64-w64-mingw32-gcc"
exit 0
fi
if [ -f "/usr/bin/x86_64-pc-msys-gcc.exe" ]
then
echo "x86_64-pc-msys-gcc"
exit 0
fi
if [ -f "/usr/bin/x86_64-w64-mingw32-gcc" ]
then
echo "/usr/bin/x86_64-w64-mingw32-gcc"
exit 0
fi
echo "Error: compiler is not found" 1>&2
exit 1
|
C#
|
UTF-8
| 2,541 | 2.890625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Autofac.Features.Indexed;
public class Program
{
private static IContainer _Container;
public static void Main()
{
InitDependencyInjection();
var rd1 = _Container.Resolve<RequiresDependency>(new NamedParameter("letterId", 1));
rd1.PrintType();
var rd2 = _Container.Resolve<RequiresDependency>(new NamedParameter("letterId", 2));
rd2.PrintType();
}
private static void InitDependencyInjection()
{
var builder = new ContainerBuilder();
var letterTypes = typeof(LetterBase).Assembly.GetTypes()
// Find all types that derice from LetterBase
.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(LetterBase)))
// Make sure they are decorated by attribute
.Where(t => t.GetCustomAttributes(typeof(LetterTypeAttribute), false).Length == 1)
.ToList();
//Register with Autofac, Keyed by LetterId
//This should throw an exception if any are duplicated
//You may want to consider using an enum instead
//It's not hard to convert an Int to Enum
foreach(Type letterType in letterTypes)
{
// we already tested the type has the attribute above
var attribute = letterType.GetCustomAttributes(typeof(LetterTypeAttribute), false)[0] as LetterTypeAttribute;
builder.RegisterType(letterType)
.Keyed<LetterBase>(attribute.LetterId);
}
builder.RegisterType<RequiresDependency>();
_Container = builder.Build();
}
}
public class RequiresDependency
{
private readonly LetterBase _letter;
//Autofac automagically provides a factory that returns type
//type you need via indexer
public RequiresDependency(int letterId, IIndex<int, LetterBase> letterFactory)
{
//resolve the needed type based on the index value passed in
_letter = letterFactory[letterId];
}
public void PrintType()
{
Console.WriteLine(_letter.GetType().Name);
}
}
public abstract class LetterBase
{
}
[LetterType(1)]
public class LetterA : LetterBase
{}
[LetterType(2)]
public class LetterB : LetterBase
{}
// make sure the classes using this attribute has only a single attribute
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class LetterTypeAttribute : Attribute
{
public LetterTypeAttribute(int letterId)
{
LetterId = letterId;
}
public int LetterId { get; private set; }
}
|
JavaScript
|
UTF-8
| 1,818 | 4.28125 | 4 |
[] |
no_license
|
/* 字符串 */
/* 普通字符串 */
// 1. 换行
const str_normal = '32131\n123123'
console.log(str_normal);
// 2. 数字运算(括号提高优先级)
const a = 20, b = 30, c = 'str'
console.log('我的年龄是:' + (a + b) + c);
/* 模板字符窜 */
// 可嵌套
// 带标签的模板字符串(函数式的高级用法)
// 第一个参数是没有变量的字符串组成的数组,其余为变量;若以变量结尾,则a中会多包含一个空字符串
const foo = (a, b, c, d) => { console.log(a); console.log(b); console.log(c); console.log(d); }
const foo_name = 'name', foo_age = 11, foo_state = '老了';
foo`这是${foo_name},经过了${foo_age}年光景,他${foo_state}`;
foo`这是${foo_name},经过了${foo_age}年光景,他${foo_state}很多`;
/* 新添加的方法 */
String.fromCharCode(0x20BB7) // es5由编码转换成字符串就,仅支持0000~ffff
String.fromCodePoint(0x20BB7) // 返回'𠮷',es6新添加由编码转换成字符串就
// includes, startsWith, endsWith
// repeat(重复拼接)
console.log('12'.repeat(2)); // 1212
// padStart(填充后的字符串长度,要填充的字符), padEnd() 填充
// * 若指定长度小于或等于原字符长度,则返回原字符串
// 应用:日期填充0
const now = new Date(),
year = now.getFullYear(),
month = (now.getMonth() + 1).toString().padStart(2, 0),
day = (now.getDate()).toString().padStart(2, 0),
str = `${year}-${month}-${day}`
console.log(str);
// 应用:手机号/银行卡星号
const tel = '17717421070'
const formattedTel = tel.slice(-4).padStart(tel.length, '*')
console.log(formattedTel);
// trimStart()、 trimEnd()、trimRight()、trimLeft()
const str_for_trim = ' kkk '
console.log(str_for_trim.trimStart());
console.log(str_for_trim.trimLeft());
// ES11 引入的matchAll
|
Java
|
UTF-8
| 888 | 1.53125 | 2 |
[] |
no_license
|
/*
* IBungeniForm.java
*
* Created on December 20, 2007, 3:55 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.bungeni.editor.selectors;
import java.util.HashMap;
import org.bungeni.editor.fragments.FragmentsFactory;
/**
*
* @author Administrator
*/
public interface IBungeniForm {
public String getClassName();
public boolean preFullEdit();
public boolean postFullEdit();
public boolean processFullEdit();
public boolean preFullInsert();
public boolean postFullInsert();
public boolean processFullInsert();
public boolean preSelectInsert();
public boolean postSelectInsert();
public boolean processSelectInsert();
/*
public HashMap<String,String> getPreInsertMap();
public HashMap<String,Object> getControlDataMap();
*/
}
|
Java
|
UTF-8
| 907 | 3.640625 | 4 |
[] |
no_license
|
import java.util.Scanner;
public class DaysInAMonth {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a month to get the number of days: ");
String month = sc.nextLine();
if(month.equals("January") || month.equals("March") || month.equals("May") || month.equals("July") || month.equals("August") || month.equals("October") || month.equals("December")){
System.out.println(month + " has 31 days");
}
else if(month.equals("April") || month.equals("June") || month.equals("September") || month.equals("November")) {
System.out.println(month + " has 30 days");
}
else if (month.equals("February")) {
System.out.println("This month has 28 days");
}
else {
System.out.println("Invalid value for month");
}
}
}
|
Python
|
UTF-8
| 3,227 | 2.96875 | 3 |
[] |
no_license
|
from http import cookiejar
from urllib import request,error
from urllib.parse import urlparse
'''
如下是使用 Python3 内置模块实现的一个比上一篇稍微健壮一点点的下载器。
通过内置 urllib 进行 header 设置或者代理设置或者启用会话,支持简单的 HTTP CODE 5XX 重试机制,支持 GET\POST。
(实际项目考虑和封装的要比这更加健壮)
'''
class HtmlDownloader(object):
def download(self,url,retry_count=3,headers=None,proxy=None,data=None):
'''
:param url: 准备下载的 URL 链接
:param retry_count: 如果 url 下载失败重试次数
:param headers: http header={'X':'x', 'X':'x'}
:param proxies: 代理设置 proxies={"https": "http://12.112.122.12:3212"}
:param data: 需要 urlencode(post_data) 的 POST 数据
:return: 网页内容或者 None
'''
if url is None:
return None
try:
req=request.Request(url,headers=headers,data=data)
# 初始化一个CookieJar来处理Cookie
#Cookie 的操蛋之处,分析时建议开启隐身模式等,不然就面对清空 Cookie 大法了,清空 Cookie 对于爬虫网站分析至关重要,一定要 get 到。
cookie=cookiejar.CookieJar()
#创建HTTP处理器
cookie_process=request.HTTPCookieProcessor(cookie)
opener=request.build_opener()
if proxy:
'''使用urlparse()后被分成6个部分:scheme = 'http', netloc = 'www.baidu.com', path = 'index.html'
paramters = 'user'.query = 'id=5', fragment = 'comment'
urlparse还有带参数的是使用方法
res=urlparse(urlstring,scheme=' ',allow_fragment=True)
scheme是默认的协议,如果urlstring没有带协议,则使用scheme中的协议,若是有,则仍然使用urlstring中协议
allow_fragment即是否忽略fragment,如果是False,fragment就被解析为path、paramenters或者query中的一部分
'''
proxies={urlparse(url).scheme:proxy}
#设置全局代理服务器
'''一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果
访问频率太快以至于看起来不像正常访客,它可能就会会禁止这个IP的访问。所以我们需要设置
一些代理服务器,每隔一段时间换一个代理,就算IP被禁止,依然可以换个IP继续爬取。'''
opener.add_handler(request.ProxyHandler(proxies))
content=opener.open(req).read()
except error.URLError as e:
print("HtmlDownLoader download error:",e.reason)
content=None
if retry_count>0:
if hasattr(e,'code') and 500<=e.code<600:
# 说明是 HTTPError 错误且 HTTP CODE 为 5XX 范围说明是服务器错误,可以尝试再次下载
return self.download(url,retry_count-1,headers,proxy,data)
return content
|
C++
|
UTF-8
| 6,433 | 2.53125 | 3 |
[] |
no_license
|
/******************************************************************************
* Copyright (C) 2011 by Jerome Maye *
* jerome.maye@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the Lesser GNU General Public License as published by*
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program 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 *
* Lesser GNU General Public License for more details. *
* *
* You should have received a copy of the Lesser GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
/** \file VdynePointCloud.h
\brief This file defines the VdynePointCloud class, which represents a
Velodyne point cloud
*/
#ifndef VDYNEPOINTCLOUD_H
#define VDYNEPOINTCLOUD_H
#include <stdint.h>
#include <vector>
#include "Library/Base/Serializable.h"
#include "Library/Base/BinaryStreamReader.h"
#include "Library/Base/BinaryStreamWriter.h"
/** The class VdynePointCloud represents a Velodyne point cloud.
\brief Velodyne point cloud
*/
class VdynePointCloud :
public Serializable {
public:
/** \name Types definitions
@{
*/
/// The struct Point3D represents a 3D point.
struct Point3D :
public Serializable {
/// X coordinate
double mX;
/// Y coordinate
double mY;
/// Z coordinate
double mZ;
/// Intensity
uint8_t mIntensity;
/// label
size_t mLaserID;
/// distance
double mDist;
/// rotation
double mRotation;
/// Default constructor
Point3D() :
mX(0),
mY(0),
mZ(0),
mIntensity(0),
mLaserID(0),
mDist(0),
mRotation(0)
{
}
/// Copy constructor
Point3D(const Point3D& other) :
mX(other.mX),
mY(other.mY),
mZ(other.mZ),
mIntensity(other.mIntensity),
mLaserID(other.mLaserID),
mDist(other.mDist),
mRotation(other.mRotation)
{
}
/// Assignment operator
Point3D& operator = (const Point3D& other) {
if (this != &other) {
mX = other.mX;
mY = other.mY;
mZ = other.mZ;
mIntensity = other.mIntensity;
mLaserID = other.mLaserID;
mDist = other.mDist;
mRotation = other.mRotation;
}
return *this;
}
/// Reads from standard input
virtual void read(std::istream& stream) {
}
/// Writes to standard output
virtual void write(std::ostream& stream) const {
stream << mX << " " << mY<< " " << mZ << " " << mIntensity;
}
/// Reads from a file
virtual void read(std::ifstream& stream) {
}
/// Writes to a file
virtual void write(std::ofstream& stream) const {
}
/// Writes binary into a output stream
void writeBinary(std::ostream& stream) const {
BinaryStreamWriter<std::ostream> binaryStream(stream);
binaryStream << mX << mY << mZ << mIntensity;
}
/// Reads binary from an input stream
void readBinary(std::istream& stream) {
BinaryStreamReader<std::istream> binaryStream(stream);
binaryStream >> mX >> mY >> mZ >> mIntensity;
}
};
/// Container type
typedef std::vector<Point3D> Container;
/// Constant iterator type
typedef Container::const_iterator ConstPointIterator;
/// Iterator type
typedef Container::iterator PointIterator;
/** @}
*/
/** \name Constructors/Destructor
@{
*/
/// Default constructor
VdynePointCloud();
/// Copy constructor
VdynePointCloud(const VdynePointCloud& other);
/// Assignment operator
VdynePointCloud& operator = (const VdynePointCloud& other);
// Destructor
~VdynePointCloud();
/** @}
*/
/** \name Accessors
@{
*/
/// Returns the timestamp
double getTimestamp() const;
/// Sets the timestamp
void setTimestamp(double timestamp);
/// Returns the starting rotational angle
double getStartRotationAngle() const;
/// Sets the starting rotational angle
void setStartRotationAngle(double angle);
/// Returns the ending rotational angle
double getEndRotationAngle() const;
/// Sets the ending rotational angle
void setEndRotationAngle(double angle);
/// Returns the container
const Container& getPoints() const;
/// Returns iterator at start of the container
ConstPointIterator getPointBegin() const;
/// Returns iterator at start of the container
PointIterator getPointBegin();
/// Returns iterator at end of the container
ConstPointIterator getPointEnd() const;
/// Returns iterator at end of the container
PointIterator getPointEnd();
/// Returns the size of the cloud
size_t getSize() const;
/// Inserts a point into the point cloud
void insertPoint(const Point3D& point);
/// Clear the point cloud
void clear();
/** @}
*/
/** \name Methods
@{
*/
/// Writes into a output stream
void writeBinary(std::ostream& stream) const;
/// Reads from an input stream
void readBinary(std::istream& stream);
/** @}
*/
protected:
/** \name Stream methods
@{
*/
/// Reads from standard input
virtual void read(std::istream& stream);
/// Writes to standard output
virtual void write(std::ostream& stream) const;
/// Reads from a file
virtual void read(std::ifstream& stream);
/// Writes to a file
virtual void write(std::ofstream& stream) const;
/** @}
*/
/** \name Protected members
@{
*/
/// Timestamp of the cloud
double mTimestamp;
/// Points in the cloud
Container mPoints;
/// Start angle of the cloud
double mStartRotationAngle;
/// End angle of the cloud
double mEndRotationAngle;
/** @}
*/
};
#endif // VDYNEPOINTCLOUD_H
|
C#
|
UTF-8
| 1,699 | 2.640625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using UNACH.CALCULADORA.WS.Clases;
namespace UNACH.CALCULADORA.WS
{
/// <summary>
/// Descripción breve de CalcularService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente.
// [System.Web.Script.Services.ScriptService]
public class CalcularService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hola a todos";
}
[WebMethod(Description = "Este metodo calcula el area de un cuadrado")]
public decimal cuadrado(decimal valor1, decimal valor2)
{
Calcular calcula = new Calcular();
calcula.lado1 = valor1;
calcula.lado2 = valor2;
return calcula.AreaCuadrado();
}
[WebMethod(Description = "Este metodo calcula el area de un triangulo")]
public decimal trianguloo(decimal baseee, decimal alturaa)
{
Calcular calcula = new Calcular();
return calcula.triangulo(baseee, alturaa);
}
[WebMethod(Description = "Este metodo calcula el area de un circulo")]
public double AreaCirculo(double radioo)
{
Calcular calcula = new Calcular();
return calcula.circulo(radioo);
}
}
}
|
Go
|
UTF-8
| 658 | 4.40625 | 4 |
[] |
no_license
|
package main
import "fmt"
func main() {
// In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default, a channel is bidirectional which means the go routines can send or receive data through the same channel
var ch chan int
fmt.Println(ch)
ch = make(chan int)
fmt.Println(ch)
// shorthand initialization
c := make(chan int)
fmt.Println(c)
// <- channel operator
// SEND
c <- 10
// RECEIVE
num := <-c
fmt.Println(num)
close(c)
}
|
Markdown
|
UTF-8
| 7,068 | 2.546875 | 3 |
[] |
no_license
|
---
title: Get started with Campaign Standard
description: Discover key capabilities, user interface and global guidelines.
audience: start
content-type: reference
topic-tags: about-adobe-campaign
feature: Overview
role: User
level: Beginner
exl-id: b62c70fe-c838-4a0e-9b0a-2e916a06ff39
---
# Get Started with Campaign Standard {#about-campaign-standard}
Adobe Campaign Standard is a powerful cross-channel campaign management tool that can help you align your online and offline strategies to create personalized customer experiences.
Control the entire process of creating, executing, and tracking cross-channel campaigns, as well as send messages that are personalized according to the profile, behavior, preferences, and needs of the clients. You can easily orchestrate, modelize and automate the entire marketing process, and integrate with other Adobe solutions.
## Grow your marketing database {#grow-database}
<img width="60px" alt="conditions" src="assets/icon_segment.svg"/>
**Campaign integrated customer profiles** allows you to track every interaction with customers across all channels within one single view, allowing you to deliver relevant and personalized messages to your customers.
**Segment your database into audiences** to optimize the target of your marketing campaigns.
**Manage customers permission and consent** using services and landing pages to set up easy opt-in and opt-out mechanisms.
**Enrich your database** using multiple functionalities: workflows, landing pages, or APIs, or Microsoft Dynamics 365.
[Get started with profiles and audiences](../../audiences/using/get-started-profiles-and-audiences.md)
## Orchestrate cross-channel marketing campaigns {#orchestrate-campaigns}
<img width="60px" alt="conditions" src="assets/icon_workflows.svg"/>
Plan, coordinate and orchestrate cross-channel campaigns.
**Optimize your marketing plans organization** by creating programs and campaigns. Analyze the impact of your marketing campaigns through reports. Orchestrate your campaigns using multiple marketing activities accessible from one single interface and set up marketing activities templates to save time. [Get started with Marketing plans and activities](../../start/using/programs-and-campaigns.md)
**Leverage workflows** to orchestrate and automate your campaigns. [Get started with processes and data management](../../automating/using/get-started-workflows.md)
## Design & send messages {#design-send}
<img width="60px" alt="conditions" src="assets/icon_send.svg"/>
Design and send messages on online and offline communication channels, including email delivery optimization for multiple devices through testing and responsive design strategies.
**Leverage Campaign communication channels** to deliver your marketing campaigns at the right place: email, SMS, push notification, In-App message, direct mail, landing pages. Gain time and consistency across your messaging strategy by creating templates for all types of messages (transactional, recurring, multilingual messages). Perform A/B testing, and capture your audience's interest using personalization and dynamic content functionalities. [Get started with communication channels](../../channels/using/get-started-communication-channels.md)
**Use Campaign Email Designer** to create captivating, individually tailored email messages. Start from scratch or leverage built-in content fragments or templates to design your emails using HTML format optimized for responsive design. [Get started with email content designing](../../designing/using/designing-content-in-adobe-campaign.md)
**Analyze and check the content of your messages** before sending, using multiple testing functionalities like preview, proofs, email subject line testing, email rendering etc. Make sure your messages are delivered at the right time by optimizing their sending time (scheduling, time zone management). [Get started with message testing and sending](../../sending/using/get-started-sending-messages.md)
## Track the impact of your campaigns {#track-impact-campaigns}
<img width="60px" alt="conditions" src="assets/icon_report.svg"/>
Once marketing campaigns have been executed and the different messages have been sent, Campaign Standard allows you monitor them to track their impact as well as their recipients' behavior.
**Monitor your deliveries** once they are sent. Consult and export detailed logs about your deliveries. Retrieve information on their status for each recipient, the messages excluded from the target and many more metrics.
Leverage the delivery alerting feature to keep track of the delivery successes or failures through email notifications. Want to learn more? [Get started with messages monitoring](../../sending/using/monitoring-a-delivery.md)
**Track the behavior of your delivery recipients**. Leverage session and permanent cookies to retrieve tracking information for each of your contact of your database. Monitor tracking information on deliveries (clicked URLs, mirror pages, opened messages...) through dedicated logs and reports. [Get started with messages tracking](../../sending/using/tracking-messages.md)
**Leverage dynamic reports** to outline specific metrics related to your message or campaign. Dynamic reporting provides fully customizable and real-time reports that add access to profile data, enabling demographic analysis by profile dimensions such as gender, city and age in addition to functional email campaign data like opens and clicks. With the drag-and-drop interface, you can explore data, determine how your email campaigns performed against your most important customer segments and measure their impact on recipients. [Get started with dynamic reporting](../../reporting/using/about-dynamic-reports.md)
## Administrate your platform and extend the data model {#datamodel-apis}
<img width="60px" alt="conditions" src="assets/icon_admin.svg"/>
**Extend Campaign Standard data model** with your own fields and resources, and monitor all data model changes into one single view. [Get started with Campaign Standard data model](../../developing/using/get-started-data-model.md)
**Leverage REST APIs** to perform various operations and integrate Campaign Standard with your own ecosystem. [Get started with Campaign Standard REST APIs](../../api/using/get-started-apis.md)
**Administrate Campaign** from one single view: monitor your instance, manage users' permissions. Setup external servers to connect to your instance, and configure parameters for your communication channels. [Get started with Campaign Standard administration](../../administration/using/get-started-campaign-administration.md)
**Import and export data** easily using Campaign Standard data management capabilities. [Get started with processes and data management](../../automating/using/get-started-workflows.md)
**Combine Campaign capabilities with other solutions** to help you build optimal marketing campaigns. [Get started with Campaign Standard integrations](../../integrating/using/get-started-campaign-integrations.md)
|
Java
|
UTF-8
| 3,421 | 2.046875 | 2 |
[] |
no_license
|
package com.nxt.ott.activity.account;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.nxt.ott.MyApplication;
import com.nxt.ott.R;
import com.nxt.ott.base.BaseTitleActivity;
import com.nxt.ott.Constant;
import com.nxt.ott.util.ToastUtils;
/**
* Created by Administrator on 2016/4/1. 16:28
*/
public class FeedBackActivity extends BaseTitleActivity {
private EditText et_note;
private EditText et_constact;
private EditText et_theme;
private Button btn_submit;
private String theme,note,contact;
@Override
protected int getLayout() {
return R.layout.activity_feed_back;
}
@Override
protected void initView() {
initTopbar(this,"意见反馈");
et_note=(EditText)findViewById(R.id.et_note);
et_constact=(EditText)findViewById(R.id.et_contact);
et_theme=(EditText)findViewById(R.id.et_theme);
btn_submit=(Button)findViewById(R.id.btn_submit);
et_theme.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//
theme=et_theme.getText().toString().trim();
}
@Override
public void afterTextChanged(Editable s) {
}
});
et_note.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//
note=et_note.getText().toString().trim();
}
@Override
public void afterTextChanged(Editable s) {
}
});
et_constact.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//
contact=et_constact.getText().toString().trim();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public void submit(View view){
if(TextUtils.isEmpty(theme)){
ToastUtils.showShort(this,"请输入您的反馈主题");
}else if(TextUtils.isEmpty(note)){
ToastUtils.showShort(this,"请输入您的意见或建议");
}else if(TextUtils.isEmpty(contact)){
ToastUtils.showShort(this,"请输入您的联系方式");
}else {
MyApplication.getInstance().getZDataTask().get(String.format(Constant.FEED_BACK_URL,
theme, note, contact),
null, null, this);
}
}
@Override
public void onRequestResult(String string) {
if(string.contains("true")){
ToastUtils.showShort(this, "您的意见已提交,谢谢您的反馈");
finish();
}
}
}
|
C++
|
UHC
| 2,170 | 2.609375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <memory.h>
#define MAX_N 651
using namespace std;
int n, m;
int aMatch[MAX_N];
int bMatch[MAX_N];
vector<int> adj[MAX_N];
int visit[MAX_N];
int visitCnt;
char map[51][51];
int cArr[51][51];
int rArr[51][51];
bool chkNum[MAX_N];
int num = 1;
bool dfs(int a)
{
if (visit[a] == visitCnt)
return false;
visit[a] = visitCnt;
for (int i = 0; i < adj[a].size(); i++)
{
int b = adj[a][i];
if (bMatch[b] == -1 || dfs(bMatch[b]))
{
bMatch[b] = a;
aMatch[a] = b;
return true;
}
}
return false;
}
int bipartiteMatch()
{
memset(aMatch, -1, sizeof(aMatch));
memset(bMatch, -1, sizeof(bMatch));
int ans = 0;
for (int start = 1; start <= num; start++)
{
visitCnt++;
ans += dfs(start);
}
return ans;
}
int main()
{
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i ++)
scanf("%s", map[i]);
// ѹ
for (int i = 0; i < n; i++)
{
if(chkNum[num])
num++;
for (int j = 0; j < m; j++)
{
if (map[i][j] == '*')
{
cArr[i][j] = num;
chkNum[num] = true;
}
else if(map[i][j] == '.')
if (chkNum[num])
num++;
}
}
int tmp = num;
num = 1;
memset(chkNum, false, sizeof(chkNum));
// ѹ
for (int i = 0; i < m; i++)
{
if (chkNum[num])
num++;
for (int j = 0; j < n; j++)
{
if (map[j][i] == '*')
{
rArr[j][i] = num;
chkNum[num] = true;
}
else if (map[j][i] == '.')
if (chkNum[num])
num++;
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (cArr[i][j] != 0)
adj[cArr[i][j]].push_back(rArr[i][j]);
if (tmp > num)
num = tmp;
printf("%d", bipartiteMatch());
return 0;
}
|
C++
|
UTF-8
| 1,365 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
/*
*
* DirectInteract this is a helper class to direct interaction with a set of Arduino pins.
*
* @author Valeriy V Dmitriev aka valmat <ufabiz@gmail.com>
* @coauthor Nikolai Tikhonov aka Dragon_Knight <dubki4132@mail.ru>, https://vk.com/globalzone_edev
* @licenses MIT https://opensource.org/licenses/MIT
* @repo https://github.com/valmat/LedMatrix
*
*/
#pragma once
#include "DirectPin.h"
class DirectInteract
{
public:
DirectInteract(uint8_t dataPin, uint8_t clockPin, uint8_t csPin) :
_data(dataPin, OUTPUT),
_clock(clockPin, OUTPUT),
_cs(csPin, OUTPUT)
{}
// Simplified constructor. For hardware SPI.
DirectInteract(uint8_t csPin) :
_cs(csPin, OUTPUT)
{}
// Empty constructor
DirectInteract() {}
// Enable the line
void enable() const
{
_cs.off();
}
// Latch the data into chip
void latch() const
{
_cs.on();
}
void transfer(uint8_t data) const
{
_data.shiftOut(_clock, data);
}
private:
// A pin on the Arduino where data gets shifted out (DIN).
// Data is shifted out of this pin
DirectPin _data;
// The clock is signaled on this pin (CLK)
DirectPin _clock;
// This one is driven LOW for chip selection (CS)
DirectPin _cs;
};
|
Python
|
UTF-8
| 1,277 | 2.90625 | 3 |
[] |
no_license
|
from Patient import *
from Personnel import *
import uuid
# quarantine is very similar to hospital therefore so are the functions
class quarantine:
def __init__(self, name, capacity):
self.ID = str(uuid.uuid1())
self.name = name
self.capacity = int(capacity)
self.patients = []
self.staff = []
def occupancy(self):
if self.capacity != 0:
return 100 * len(self.patients) / self.capacity
return 0
def admission(self, name, dob):
p = Patient(name, dob)
self.patients.append(p)
def serialize(self):
return {
'id': self.ID,
'name': self.name,
'capacity': self.capacity,
'occupancy': self.occupancy(),
}
def addPersonnel(self, name, dob, type_):
s = Staff(name, dob, type_)
self.staff.append(s)
def getPersonnelByName(self, name_):
for n in self.staff:
if n.name == name_:
return n
return None
def removePersonnel(self, name_):
s = self.getPersonnelByName(name_)
if s is not None:
self.staff.remove(s)
return f"{s} has been removed from the hospital staff"
|
C++
|
UTF-8
| 643 | 2.9375 | 3 |
[] |
no_license
|
class Solution {
public:
string convert(string s, int numRows) {
vector<string> tmp(numRows);
string res;
int size = s.size();
if(1 == numRows) return s;
if(s.empty() || numRows < 1) return res;
for(int i = 0; i < size; i++){
int ans = i / (numRows - 1);
int cur = i % (numRows - 1);
if(ans % 2 == 0){
tmp[cur].push_back(s[i]);
}else{
tmp[numRows - 1 - cur].push_back(s[i]);
}
}
for(int i = 0; i < tmp.size(); i++){
res += tmp[i];
}
return res;
}
};
|
JavaScript
|
UTF-8
| 1,844 | 2.578125 | 3 |
[] |
no_license
|
import React, { Component } from "react";
import { Form, Button, Col } from "react-bootstrap";
import { toast } from "react-toastify";
/* Services*/
import { saveDepot, updateDepot, getDepot } from "../Services/depotservice";
export default function ArticleForm(props) {
/*Form State*/
const [name, setName] = React.useState("");
const [address, setAdress] = React.useState("");
/*On Component Mount */
React.useEffect(() => {
async function fetchData() {
if (props.id != "") {
const { data: depot } = await getDepot(props.id);
setName(depot.name);
setAdress(depot.adresse);
}
}
fetchData();
}, []);
const handleSubmit = async () => {
try {
const depot = {
name: name,
adresse: address,
};
if (props.id != "") {
await updateDepot(props.id, depot);
toast.success("Dépot Modifié !");
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
await saveDepot(depot);
toast.success("Dépot Ajoutée ! ");
setTimeout(() => {
window.location.reload();
}, 1500);
}
} catch (e) {}
};
return (
<Form>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Nom</Form.Label>
<Form.Control
value={name}
placeholder="Nom"
onChange={(e) => setName(e.target.value)}
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Adresse</Form.Label>
<Form.Control
placeholder="Adresse"
value={address}
onChange={(e) => setAdress(e.target.value)}
/>
</Form.Group>
</Form.Row>
<Button variant="primary" onClick={handleSubmit}>
Valider
</Button>
</Form>
);
}
|
Python
|
UTF-8
| 120 | 2.578125 | 3 |
[] |
no_license
|
import time
if __name__=='__main__':
s = 60
print("Delaying other process by {} seconds".format(s))
time.sleep(s)
|
Java
|
UTF-8
| 917 | 2.40625 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bonarea.myfirstwebapp.interceptores;
import java.util.Arrays;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
/**
*
* @author alumne
*/
@Interceptor
@Log
public class LoggingInterceptor {
@AroundInvoke
public Object logMethodEntry(InvocationContext ctx) throws Exception {
System.out.print("Start Interceptor logMethodEntry");
System.out.print("Entering Method: " + ctx.getMethod().getName());
System.out.print("Show method parameters values: "
+ Arrays.toString(ctx.getParameters()));
System.out.println("Finish Interceptor logMethodEntry");
return ctx.proceed();
}
}
|
C
|
UTF-8
| 3,824 | 2.921875 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <math.h>
#include "../include/structures.h"
#define SWAP(a, b) dumm=(a); (a)=(b); (b)=dumm
void ec_init(struct ec_parameters *ec, const int points_count){
void *buf = NULL;
int buf_size;
ec->a = 486662;
ec->b = 1;
ec->sign1 = ec->sign2 = 1;
ec->xs_4_y0 = NULL;
ec->points = NULL;
ec->n = 0;
ec->max_points = MINIMUM_LIMIT_FOR_POINTS;
ec->precision_numerator = 2;
ec->precision_denominator = 1;
if(points_count > 0){
ec->n = (unsigned)points_count;
buf_size = points_count*2;
ec->max_points = (buf_size > MINIMUM_LIMIT_FOR_POINTS)?buf_size:MINIMUM_LIMIT_FOR_POINTS;
}
buf_size = 3*sizeof(double) + (ec->max_points)*sizeof(struct point);
buf = calloc(buf_size, sizeof(char) );
ec->xs_4_y0 = (double*)buf;
if(buf != NULL){
buf_size = 3*sizeof(double);
ec->points = (struct point*)(buf + buf_size);
} else {
ec->n = ec->max_points;
}
}
double ec_y_square(const double x, const double a, const double b){
return x*x*x + a*x + b;
}
// x_4_y0: what is the value of x on the head of elliptic curve (meaning y = 0);
double x_4_y0(const double a, const double b){
double sqr, d, pi2_per_3, dumm;
sqr = b*b/4.0;
dumm = a*a*a/27.0;
d = sqr + dumm;
if(d > 0.0){
sqr = sqrt(d);
dumm = -0.5*b;
d = cbrt(dumm + sqr) + cbrt(dumm - sqr);
} else if(d < 0.0){
d = 1.5*b/a*sqrt(-3.0/a);
dumm = acos(d)/3.0;
pi2_per_3 = atan(1.0)*8.0/3.0;// = \pi*2/3;
sqr = sqrt(a/-3.0)*2.0;
d = sqr*cos(dumm);
dumm -= pi2_per_3;
if(sqr*cos(dumm) < d) d = sqr*cos(dumm);
dumm -= pi2_per_3;
if(sqr*cos(dumm) < d) d = sqr*cos(dumm);
} else {
sqr = 3.0*b/a;
dumm = -1.5*b/a;
d = (sqr < dumm)?sqr:dumm;// min(sqr, dumm);
}
return d;
}
// all_xs_4_y0: same as above but it writes all 3 values into xs[] and returns binary check which are important {0, 1, 3, 7};
int all_xs_4_y0(double *xs/*[3]*/, const double a, const double b){
double sqr, pi2_per_3, dumm;
int validity = 0;// significance;
sqr = b*b/4.0;
dumm = a*a*a/27.0;
xs[0] = sqr + dumm;
if(xs[0] > 0.0 || a == 0.0){
sqr = sqrt(xs[0]);
dumm = -0.5*b;
xs[0] = cbrt(dumm + sqr) + cbrt(dumm - sqr);
validity = 1;
} else if(xs[0] < 0.0){
xs[0] = 1.5*b/a*sqrt(-3.0/a);
dumm = acos(xs[0])/3.0;
pi2_per_3 = atan(1.0)*8.0/3.0;// = \pi*2/3;
sqr = sqrt(a/-3.0)*2.0;
xs[0] = sqr*cos(dumm);
dumm -= pi2_per_3;
xs[1] = sqr*cos(dumm);
dumm -= pi2_per_3;
xs[2] = sqr*cos(dumm);
if(xs[0] > xs[1]){// swap;
SWAP(xs[0], xs[1]);
}
if(xs[0] > xs[2]){
SWAP(xs[0], xs[2]);
}
if(xs[1] > xs[2]){
SWAP(xs[1], xs[2]);
}
validity = 7;
} else {
xs[0] = -1.5*b/a;
xs[1] = 3.0*b/a;
if(xs[1] < xs[0]){
SWAP(xs[0], xs[1]);
}
validity = 3;
}
return validity;
}
double critical_proportion(const double a, const double b){
return a*a*a*4.0 + b*b*27.0;// hope != 0;
}
unsigned set_symmetric_points(struct point *points/*[n]*/, const unsigned n, const double a, const double b, const double precision){
double xs[3], b2 = b, ystep = 0.0;
unsigned i = 1, j, validity, count_xs;
if(n < 1 || precision < 1.0e-7) return 0;
validity = all_xs_4_y0(xs/*[3]*/, a, b2);
count_xs = 1;
if( (validity&2) ) count_xs++;
if( (validity&4) ) count_xs++;
for(i = 0; i < count_xs && i < n; i++){
(points + i)->x = xs[i];
(points + i)->y = 0.0;
}
while(i < n){
ystep += precision;
b2 = b - ystep*ystep;
validity = all_xs_4_y0(xs, a, b2);
count_xs = 1;
if( (validity&2) ) count_xs++;
if( (validity&4) ) count_xs++;
j = 0;
while(j < count_xs && i < n){
(points + i)->x = xs[j];
(points + i)->y = ystep;
i++;
if(i < n){
(points + i)->x = xs[j];
(points + i)->y = -1.0*ystep;
i++;
}
j++;
}
}
return i;
}
void ec_free(struct ec_parameters ec){
if(ec.xs_4_y0 != NULL) free((void*)(ec.xs_4_y0) );
}
|
JavaScript
|
UTF-8
| 207 | 3.828125 | 4 |
[] |
no_license
|
// String repeat
function repeatStr(n, s) {
let newString = "";
for (let i = 0; i < n; i++) {
newString += s;
}
return newString;
}
let test = repeatStr(5, "Ade");
console.log(test);
|
Markdown
|
UTF-8
| 5,583 | 3.890625 | 4 |
[] |
no_license
|
# 列挙子 Enum の使い方(発展)
ここでは、日本の硬貨を例にして、Enum の発展した使い方を見ていく。
日本の硬貨を enum にすると次のようになる。
``` java
enum CoinType {
ONE,
FIVE,
TEN,
FIFTY,
HUNDRED,
FIVE_HUNDRED,
;
}
```
Enum の基本的な取り扱い方を知りたい場合は、以下にアクセスしてほしい。
列挙子 Enum の使い方(基本)
https://github.com/fs5013-furi-sutao/java-enum-basic
## 定数と値を対応させる
このままでは定義だけで、金額といった実際に使い道のある値への対応づけができていない。
enum 値(インスタンス)と int 値を対応づけたい場合は、クラスと同じようにコンストラクタを使ってフィールドへ値を代入する。
``` java
enum CoinType {
ONE(1),
FIVE(5),
TEN(10),
FIFTY(50),
HUNDRED(100),
FIVE_HUNDRED(500),
;
private int price;
CoinType(int price) {
this.price = price;
}
public int getPrice() {
return this.price;
}
}
```
### private なコンストラクタ
ただし、注意してほしいのは enum のコンストラクタは private を記述しなくても、暗黙的に private になること。
なぜなら、各 Enum 値(インスタンス)は、実行されるプログラム中でただ 1 つになることを保障しなければならないように設計されているからである。
### 定数それぞれがフィールドを持っている
Enum は内部的には、特殊なクラスとして扱われている。
上記のコード例から分かるように、定数それぞれがフィールドを持ったインスタンスになっている。
## さらに複数の値を対応づける
使い勝手を良くするために、フィールド jpName を追加する。
``` java
enum CoinType {
ONE("1円玉", 1),
FIVE("5円玉", 5),
TEN("10円玉", 10),
FIFTY("50円玉", 50),
HUNDRED("100円玉", 100),
FIVE_HUNDRED("500円玉", 500),
;
private String jpName;
private int price;
CoinType(String jpName, int price) {
this.jpName = jpName;
this.price = price;
}
public String getJpName() {
return this.jpName;
}
public int getPrice() {
return this.price;
}
}
```
### enum インスタンスを使ってみる
定義した CoinType を使ってみる。
``` java
for (CoinType c : CoinType.values()) {
System.out.printf("%5s: %3d%n", c.getJpName(), c.getPrice());
}
```
実行結果:
``` output
1円玉: 1
5円玉: 5
10円玉: 10
50円玉: 50
100円玉: 100
500円玉: 500
```
Stream API とラムダ式を使うと上記のコードは次のように書き換えられる。
``` java
Arrays.stream(CoinType.values())
.forEach(e ->
System.out.printf("%5s: %3d%n", e.getJpName(), e.getPrice())
);
```
## 金額から enum 値を返すメソッドを追加する
金額から enum 値(インスタンス)を返す static メソッド priceOf() を追加すると enum は次のようになる。
``` java
import java.util.Arrays;
enum CoinType {
ONE("1円玉", 1),
FIVE("5円玉", 5),
TEN("10円玉", 10),
FIFTY("50円玉", 50),
HUNDRED("100円玉", 100),
FIVE_HUNDRED("500円玉", 500),
UNKNOWN("存在しない", -1)
;
private String jpName;
private int price;
CoinType(String jpName, int price) {
this.jpName = jpName;
this.price = price;
}
public String getJpName() {
return this.jpName;
}
public int getPrice() {
return this.price;
}
public static CoinType priceOf(int price) {
return Arrays.stream(CoinType.values())
.filter(e -> price == e.getPrice())
.findFirst()
.orElse(CoinType.UNKNOWN);
}
}
```
この enum を main メソッドから利用してみる。
``` java
System.out.println(CoinType.priceOf(50).getJpName());
System.out.println(CoinType.priceOf(60).getJpName());
```
実行結果:
``` output
50円玉
存在しない
```
### 凝集度を考えて
以下は、enum 的な話を越えた、設計的な余談になる。
クラス設計を考えると、凝集度を高めるために、getter を外部に漏らしたくない。そうすると、enum と enum を使う側のコードは次のようになる。
```java title="Cointype.java"
enum CoinType {
// ・・・中略
public static CoinType priceOf(int price) {
return Arrays.stream(CoinType.values())
.filter(e -> price == e.getPrice())
.findFirst()
.orElse(CoinType.UNKNOWN);
}
public static String getJpNameFromPriceOf(int price) {
return priceOf(price).getJpName();
}
}
```
```java
System.out.println(CoinType.getJpNameFromPriceOf(50));
System.out.println(CoinType.getJpNameFromPriceOf(60));
```
## まとめ
Enum の各値には複数の値を対応づけることができる。static メソッドを自作することで、値から逆引きして enum 値(インスタンス)を取得することもできる。
この機能を使えば、アプリ内での設定値の管理が楽になり、処理の見通しも良くなる。
ただし、設定値が数百個単位となってくると、管理が大変になる。
そうした場合は、DB で設定値を管理する方法のほうがベターか、検討する余地がある。
|
C++
|
UTF-8
| 4,173 | 2.6875 | 3 |
[] |
no_license
|
#include <PDFdeal.h>
int extract_pdf(char *pdf_path, char **pageslist, char *out_path,char *password){
int count = 1; //源代码中是为了获取后续的命令行参数,这里不用
fz_context* ctx = NULL;
ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
if (!ctx) {
cerr << "程序异常,不能创建mupdf上下文" << endl;
exit(EXIT_FAILURE);
}
pdf_write_options this_write = pdf_default_write_options;
pdf_clean_file(ctx, pdf_path, out_path, password, &this_write,count,pageslist); // 提取PDF
fz_drop_context(ctx);
return EXIT_SUCCESS;
}
int merge_pdf(vector<string> pdf_path, int merge_nums, string out_path) {
pdf_write_options this_write = pdf_default_write_options;
fz_context *dst_ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
fz_context *src_ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
if (!dst_ctx||!src_ctx) {
cerr << "程序异常,不能创建mupdf上下文" << endl;
exit(EXIT_FAILURE);
}
pdf_document* out_pdf = pdf_create_document(dst_ctx);
for (int i = 0;i< merge_nums;i++) {
const char *this_path = pdf_path[i].c_str(); // 每个文件的路径
pdf_document *input_pdf = pdf_open_document(src_ctx, this_path);
pdf_graft_page(dst_ctx, out_pdf, -1, input_pdf, 0);
//pdf_graft_mapped_page();
pdf_drop_document(src_ctx, input_pdf);
input_pdf = NULL;
}
pdf_save_document(dst_ctx, out_pdf, out_path.c_str(), &this_write);
pdf_drop_document(dst_ctx, out_pdf);
fz_flush_warnings(src_ctx);
fz_drop_context(src_ctx);
fz_drop_context(dst_ctx);
return EXIT_SUCCESS;
}
int pdf2img(string pdf_path, string img_path, int page_num,float sx, float sy, int rotate){
int page_count = 0; //页数
fz_context* ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
fz_document* pdf = NULL;
fz_pixmap* pix = NULL;
fz_matrix ctm = fz_scale(sx,sy); // 缩放0-1 取0时会出错
ctm = fz_pre_rotate(ctm, rotate); // 旋转-360
if (!ctx) {
cerr << "程序异常,不能创建mupdf上下文" << endl;
exit(EXIT_FAILURE);
}
/* Register the default file types to handle. */
fz_register_document_handlers(ctx);
pdf = fz_open_document(ctx, pdf_path.c_str());
page_count = fz_count_pages(ctx, pdf);
if (page_num == -1 || page_num-1 > page_count) {
//打印所有页
cout << "打印全页" << endl;
for (int i = 0; i < page_count; i++) { // pdf 从0开始计算页数
cout << "开始打印第" << i+1 << "页"<< endl;
string this_file_name = img_path + to_string(i+1) + ".png";
pix = fz_new_pixmap_from_page_number(ctx, pdf, i, ctm, fz_device_rgb(ctx), 0);
fz_save_pixmap_as_png(ctx, pix, this_file_name.c_str());
fz_drop_pixmap(ctx, pix);
}
}
else {
//打印指定页
cout << "打印指定页:" << page_num << endl;
string this_file_name = img_path + to_string(page_num) + ".png";
pix = fz_new_pixmap_from_page_number(ctx, pdf, page_num-1, ctm, fz_device_rgb(ctx), 0);
fz_save_pixmap_as_png(ctx, pix, this_file_name.c_str());
fz_drop_pixmap(ctx, pix);
}
fz_drop_document(ctx, pdf);
fz_drop_context(ctx);
return EXIT_SUCCESS;
}
int convert(vector<string> input_path, int input_num, const char* out_path, const char* format, const char* options, const char* password){
fz_context* ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
fz_document_writer *out;
fz_document *input_doc;
//float layout_w = 21.1;
//float layout_h = 30.0;
//float layout_em = 14.0;
fz_register_document_handlers(ctx);
out = fz_new_document_writer(ctx, out_path, format, options);
for (int i = 0; i < input_num; i++) {
input_doc = fz_open_document(ctx, input_path[i].c_str());
if (fz_needs_password(ctx, input_doc)) {
if (!fz_authenticate_password(ctx, input_doc, password)){
cout << "文件:" << input_path[i] << "需要密码" << endl;
exit(EXIT_FAILURE);
}
}
//fz_layout_document(ctx, input_doc, layout_w, layout_h, layout_em); // 设置转出文件大小
fz_write_document(ctx,out,input_doc); // 写入文档
fz_drop_document(ctx, input_doc);
input_doc = NULL;
}
fz_close_document_writer(ctx, out);
fz_drop_document_writer(ctx, out);
fz_drop_context(ctx);
return EXIT_SUCCESS;
}
|
JavaScript
|
UTF-8
| 911 | 3.453125 | 3 |
[] |
no_license
|
let img;
function preload(){
img = loadImage('bird.png');
}
function setup() {
createCanvas(img.width*18, img.height*18);
background(255);
btn1 = createButton('픽셀을 원으로 그리기');
btn2 = createButton('픽셀을 네모로 그리기');
btn1.mousePressed(circlePixels);
btn2.mousePressed(squarePixels);
image(img, 0, 0);
}
function circlePixels(){
background(0);
img.loadPixels();
for(let y = 0; y < img.height; y++){
for(let x = 0; x < img.width; x++){
let xyColor = img.get(x, y);
fill(xyColor);
noStroke();
circle(x*18+9, y*18+9, 16);
}
}
image(img, 0, 0);
}
function squarePixels(){
background(0);
img.loadPixels();
for(let y = 0; y < img.height; y++){
for(let x = 0; x < img.width; x++){
let xyColor = img.get(x, y);
fill(xyColor);
noStroke();
square(x*18, y*18, 16);
}
}
image(img, 0, 0);
}
|
Markdown
|
UTF-8
| 6,286 | 2.703125 | 3 |
[] |
no_license
|
# vue2.0仿手机版美图官网
看着各位大神的vue项目泉涌而出,本阶段正在学习Vue的小小白也打算亲自操起键盘来感受一把Vue世界的美好~~
**线上体验** <br>
[在线demo](https://zsqio.github.io/vue-meitu-demo/vuex-meitu-demo/index.html#/) (切换到移动端模式预览效果更佳~)<br>
[Github源码](https://github.com/zsqio/vue-meitu) <br>
**技术栈** <br>
* vue2.0
* vue-router spa开发
* vuex 专为 Vue.js 应用程序开发的状态管理模式,集中式存储管理应用的所有组件的状态
* axios 一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端
* mint-ui 基于vue.js的移动端组件库 帮助快速搭建页面
* easy-mock 前后端分离,提供数据接口
* html5 css3 <br>
**页面预览** <br>
 <br>
 <br>
## 主要实现功能 <br>
**商品信息展示** <br>
* 轮播图
* mint-ui navbar 切换商品信息,产品参数
* Toast 用户提醒信息
* 主页面展示 <br>
**手机预约** <br>
预约功能的实现主要在state中添加一个预约商品数组,当预约了商品后就使用数组的push方法将商品加入预约数组中,然后再我的预约页面就可以查看你预约的商品,同时你也可以取消预约,这就更简单了,直接将预约数组清空,当然这只只有一条预约消息的情况下,如果有多条记录,就可以借助splice方法进行数组切割。详细实现可以参考代码。 <br>
### 购物车 <br>
* **加入购物车** <br>
包括两种状态: <br>
1. 加入的商品在购物车中已经存在, 该商品已经存在购物车中,此时商品数量+1即可 <br>
2. 商品不在购物车,将新加入的商品信息push进cartList <br>
* **删除商品** <br>
根据根据选中即将删除商品的id在cartList中遍历出该商品并给予删除,因为我在state里是一个数组暂存购物车中的商品, <br>
所以可以使用数组的splice方法将指定下标的某个商品删除,即 cartList.splice(index, 1) <br>
* **商品支付** <br>
根据用户选中前往支付的商品动态的显示需要支付的总金额,此时购物车中的商品如同一个个复选按钮,可选可不选,可单选可多选, <br>
使用户的购物体验更好,这些共享状态之间相互切换,来及时驱动界面的渲染
* **用户登录状态判断** <br>
在提交订单和立即购买时,需要对用户的登录状态进行判断 <br>
通过return this.$store.state.login 来获取登录状态
* **用户收货地址生成** <br>
提交订单时 若用户未生成收货地址 前往设置收货地址 <br>
此处我借用localstorage来存储收货地址信息,当用户再次登录时,则不需要再次设置收货地址 <br>
* **生成订单** <br>
用户选中商品后生成相应订单 <br>
commit mutations ['CREATE_ORDER'] <br>
* **查看订单** <br>
支付操作完成后,在登录的情况下用户可在个人中心查看我的订单 <br>
* **购物车更新** <br>
已经支付生成订单的商品从购物车中“消失”,已经加入购物车但还未支付的商品继续保留其原有的状态 <br>
这些状态间的切换,以及组件的更新都仰仗Vuex的响应式状态存储
## 小结
1. 采用rem 自适应布局,移动端必备,但使用时需注意rem是相对于根元素<html>,建议项目初期就严格使用rem进行布局,会减少后期的适配工作
2. 初学vue,使用methods和computed可能会存在一定误区,首先需要明白computed是计算属性,实时响应数据的更新,而methods是方法,必须有一定条件去触发,可能这样说上去还是不够清晰明了,那么就请仔细阅读下面这段话:
计算属性是基于它的依赖缓存。计算属性只有在它的相关依赖发生改变时才会重新取值。这就意味着只要 message 没有发生改变,
多次访问 reversedMessage 计算属性会立即返回之前的计算结果,而不必再次执行函数。每当重新渲染的时候,method 调用总会执行函数。
也就是说只要不是直接使用浏览器刷新页面,当我们改变数据、DOM操作等引起页面重新渲染时,计算属性会直接使用缓存,不会重新执行函数。
适合那些计算量很大且改变频率很低的属性;如果使用methods,每次页面重新渲染时都会重新执行methods函数。
3. v-if 和 v-show 的使用,两者都是动态的显示DOM元素,但两者存在区别,性能消耗也不同,若是频繁的切换状态建议使用v-show
4. vuex使用:
- Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,
那么相应的组件也会相应地得到高效更新。
- 我们不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交(commit) mutations。<br>
关于Vuex你想了解更多?一起去看文档吧(https://vuex.vuejs.org/zh-cn/) 这样你离大牛又进了一步~
5. 本项目需要继续完善的模块: <br>
* 搜索功能 现在已经可以搜索了,主要是依赖easy-mock 构造假数据,然后根据输入的关键字匹配,axios异步请求数据,再将数据渲染到页面上
* 手机预约 这个功能也已经初步实现,但还略显粗糙,会进一步完善~ 毕竟学习永远没有尽头,就像喝了脉动一样,根本停不下来~~~ <br>
## Build Setup
```
bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
|
PHP
|
UTF-8
| 1,043 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
<?php
class ValidateIntegerValueObject extends PHPUnit_Framework_TestCase
{
public function testCreateInteger()
{
$integer = new Enabler\Object\Integer(10);
$this->assertEquals(10, $integer->getValue());
}
/**
* @expectedException InvalidArgumentException
*/
public function testWrongValueForInteger()
{
$integer = new Enabler\Object\Integer(10.1);
}
/**
* @expectedException InvalidArgumentException
*/
public function testWrongValueWithAnString()
{
$integer = new Enabler\Object\Integer("abcd");
}
/**
* @expectedException InvalidArgumentException
*/
public function testPercentageIsEqualThanInteger()
{
$integer = new Enabler\Object\Integer(10);
$percentage = new Enabler\Object\Percentage(
new Enabler\Object\Integer(10)
);
$this->assertTrue($integer->equals($percentage));
}
public function testIntegerIsEqualThanInteger()
{
$integer = new Enabler\Object\Integer(10);
$secondInteger = new Enabler\Object\Integer(10);
$this->assertTrue($integer->equals($secondInteger));
}
}
|
Python
|
UTF-8
| 539 | 3.0625 | 3 |
[] |
no_license
|
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
dict = {}
n = len(num)
if n == 1:
return num[0]
for i in num:
if i in dict:
count = dict[i]
count += 1
if count > n/2:
return i
else:
dict[i] = count
else:
dict[i] = 1
#Majority Element
#https://oj.leetcode.com/problems/majority-element/
|
Markdown
|
UTF-8
| 11,091 | 3.0625 | 3 |
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
## 重构巨石应用至服务
本章节本电子书的第七章。章节一介绍了微服务架构模式,讨论了使用微服务的优缺点。接下来的章节,讨论了微服务架构图的不同方面:使用API网关,进程间通信,服务发现,事件驱动的数据管理和微服务部署。本章节我们将讨论将巨石应用迁移到微服务的策略方案。
我希望这本电子书能让你充分了解微服务架构,它的优点和缺点,以及何时使用它。也许微服务架构非常适合你的组织。
但是,你很可能正在处理一个大型的、复杂的巨石应用。你每天对开发与部署巨石应用的体验是缓慢与痛苦。微服务看起来是遥不可及的天堂。幸运的是,有一些策略可以用来摆脱巨石的地狱。在本篇中,我将会描述如何循序渐进的将巨石应用重构成一组微服务。
### 微服务重构概述
将巨石应用程序重构成微服务的过程是[应用程序现代化](https://en.wikipedia.org/wiki/Software_modernization)的一种形式。这是开发人员几十年来一直在做的事情。因此,在将应用程序重构为微服务时,我们可以重用一些思想。
一种不应该使用的策略是“大爆炸(Big Bang)”重写。这就是当你将所有开发工作集中在从头开始构建基于微服务的新应用程序的时候。虽然听起来很吸引人,但它风险极大,很可能以失败而告终。正如Martin Fowler所[报道](http://www.randyshoup.com/evolutionary-architecture)的那样,“大爆炸重写保证的唯一一件事就是大爆炸!”
你应该循序渐进的重构巨石应用,而不是大爆炸重写。以微服务的形式逐步添加新功能与创建现有功能的扩展 - 以互补的方式修改巨石程序,并同时运行微服务和修改后的巨石应用。随着时间的推移,巨石应用实现的功能数量逐渐缩小,直到它完全消失或者变成另一个微服务。这种策略类似于在汽车在高速公路上以每小时70英里的速度行驶的同时维修汽车 - 具有挑战性,但风险远低于尝试大爆炸重写。
Martin Fowler将这种应用程序现代化策略称为[Strangler应用](http://www.martinfowler.com/bliki/StranglerApplication.html)。这个名字来自在热带雨林中发现的绞杀藤(亦称 绞杀榕)。绞杀藤围绕着树成长,为了能吸收森林树冠上的阳光。有时,树死了,留下了树形藤蔓。应用程序现代化遵循相同的模式。我们将围绕遗留应用构建一个由微服务组成的新应用,遗留应用程序将会收缩,甚至最终死亡。

让我们讨论下完成该重构的不同策略。
#### 策略一:停止挖掘
洞穴定律说,只要你在洞里,就应该停止挖掘。当巨石应用变得无法管理时,这是一个很好且应该被遵循的建议。换句话说,你应该停止让巨石应用变的更大。这意味着在实现新功能时,不应向巨石应用添加更多代码。相反,这个策略的主要思想是将新代码放在一个独立的微服务中。
图7-1 使用该方案后的系统架构

图7-1 以单独服务的形式实现新功能,而不是将模块添加到巨石应用
除了新服务和传统巨石应用之外,还有另外两个组件。第一个是请求路由器,它处理进来的(HTTP)的请求,类似于在章节二中所描述的API网关。路由器将对应于新功能的请求发送到新服务,将遗留请求路由到巨石应用。
另一个组件是胶水代码,它将服务与巨石应用结合在一起。服务很少能孤立存在,并且通常需要访问巨石应用所拥有的数据。胶水代码,要么存在于巨石应用,服务或两者中,负责数据集成。服务使用胶水代码来读取和写入巨石应用所拥有的数据。
服务可以使用三种策略来访问巨石应用的数据:
- 调用巨石应用提供的远程API
- 直接访问巨石应用的数据库
- 维护自己的数据副本,该数据与巨石应用的数据库同步
胶水代码有时被称为反腐败层,这是因为胶水代码阻止了具有其自己的原始域模型的服务被传统巨石的域模型中的概念污染。胶水代码在两种不同的模型之间进行转换。反腐败层一词首先出现在Eric Evans的必读书“[领域驱动设计](http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?ie=UTF8&s=books&qid=1238687848&sr=8-1)”中,然后在[白皮书](https://docs.scala-lang.org/overviews/core/futures.html)中进行了细化。制定反腐败层可能是一件非常重要的事情。但是如果你想要从巨石应用的地狱中走出来,那么创造一个是至关重要的。
将新功能实现为轻量级服务有几个好处。它可以防止巨石应用变得更难以管理。该服务可以独立于巨石应用进行开发,部署和扩展。你可以体验微服务架构为你创建的每项新服务带来的好处。
但是,这种方法无法解决巨石应用的问题。要解决这些问题,你需要打破巨石。让我们来看看这样做的策略。
#### 策略二:拆分前端与后端
缩小巨石应用的一个策略是将表示层从业务逻辑层和数据访问层中分开。典型的企业应用包含至少三种不同类型的组件:
- 表示层 - 处理HTTP请求,并实现(REST)API或基于HTML的Web UI的组件。在具有复杂用户界面的应用程序中,表示层通常有大量代码。
- 业务逻辑层 - 应用的核心组成部分,实现业务规则
- 数据访问层 - 访问基础设施组件,例如数据库和消息代理
在表示层与业务逻辑层和数据访问层之间存在清晰的分离。业务层具有粗粒度API,其由一个或多个模式组成,其封装业务逻辑组件。API是一个天然缝隙,你可以沿着该缝隙将巨石应用分割为两个较小的应用程序。一个应用包含表示层。另一个应用程序包含业务和数据访问逻辑。分割后,表示层逻辑应用对业务层逻辑应用进行远程调用。
图7-2 重构前后的架构

图7-2 重构现有应用
以这种方式拆分巨石应用有两个主要好处。你能够独立地开发,部署和扩展这两个应用程序。特别是,它允许表示层开发人员在用户界面上快速迭代并轻松执行A|B测试。这种方法的另一个好处是它暴露了一个可以被你开发的微服务所调用的远程API。
然而,这种策略只是部分解决方案。这两个应用程序中的一个或两个很可能将会成为一个难以管理的巨石应用。你需要使用第三个策略来消除剩余的巨石应用。
#### 策略三:提取服务
第三种重构策略是将巨石应用内的现有模块转变为独立的微服务。每次提取模块并将其转换为服务时,巨石应用都会缩小。一旦你转换了足够的模块,巨石应用将不再是一个问题。它要么完全消失,要么变得足够小以至于它只是另一个服务。
##### 为需要转换为服务的模块确定优先级
一个庞大而复杂的单片应用程序由数十个或数百个模块组成,所有这些模块都是提取的候选模块。确定首先转换哪些模块通常具有挑战性。一个好的方法是从一些易于提取的模块开始。这将为你从整体上提供微服务经验,特别是提取过程。之后,你应该提取那些可以带来最大益处的模块。
将模块转换为服务通常很耗时。你应该按照获得的好处对模块进行排名。提取经常变化的模块通常是有益的。一旦将模块转换为服务后,你可以独立于巨石应用进行开发和部署,这将加速开发。
提取与巨石应用中其它模块相比有明显不同资源需求的模块是有益的。例如,将具有内存数据库的模块转换为服务是有用的,可以将其部署在具有大量内存的主机上,无论是物理服务器,虚拟机还是云实例。类似地,提取实现计算昂贵算法的模块是值得的,因为该服务可以部署在具有大量CPU的主机上。通过将具有特定资源需求的模块转换为服务,你可以使应用程序更容易伸缩,并且成本更低。
在确定要提取哪些模块时,查找现有的粗粒度边界(缝隙)很有用,它们使模块转换为服务变得更容易,成本更低。比如,有个模块,它只能通过异步消息与应用的其余部分进行通信,可以以相对较低的成本与难易度将该模块转换为微服务。
##### 如何提取模块
提取模块的第一步是在模块和巨石应用之间定义粗粒度接口,通常是一个双向API,由于巨石应用需要服务拥有的数据,反之亦然。由于模块与应用其余部分之间存在复杂的依赖关系和细粒度的交互模式,因此实现此类API通常具有挑战性。由于域模型和类之间存在大量关联,因此使用域模型模式实现的业务逻辑对于重构尤其具有挑战性。你通常需要进行显著的代码更改以打破这些依赖关系。
图7-3 重构

图7-3 巨石应用中的模块可以成为微服务
实现粗粒度接口后,即可将模块转换为独立服务。为此,你必须编写代码以使巨石应用和服务能够通过使用进程间通信(IPC)机制的API进行通信。图7-3展示了重构前,中与后的架构。
在此示例中,模块Z是要提取的候选模块。它的组件被模块X使用,同时使用模块Y。重构步骤第一步是定义一对粗粒度的API。第一个接口是入站接口,模块X使用它来调用模块Z。第二个接口是模块Z用于调用模块Y的出站接口。
重构步骤第二步将模块转换为独立服务。入站和出站接口由使用IPC机制的代码实现。你很可能需要通过将模块Z与处理横切关注点(如服务发现)的微服务底盘框架相结合来构建服务。
一旦提取了一个模块,就又有了一个可以独立于巨石应用与其它服务而进行开发,部署与扩展的服务。你甚至可以从头开始重写服务; 在这种情况下,将服务与巨石应用集成的API代码成为一个反腐败层,可在两个域模型之间进行转换。每次提取服务时,你都会朝着微服务的方向迈出新的一步。随着时间的推移,整体结构将缩小,你将拥有越来越多的微服务。
## 总结
将现有应用程序迁移到微服务的过程是应用程序现代化的一种形式。不应该通过从头开始重写应用以转移到微服务。相反,应该逐步将应用程序重构为一组微服务。可以使用三种策略:将新功能实现为微服务; 从业务和数据访问组件中拆分表示组件; 将巨石应用中的现有模块转换为服务。随着时间的推移,微服务的数量将会增长,开发团队的敏捷性和速度将会提高。
|
Markdown
|
UTF-8
| 4,400 | 3.359375 | 3 |
[] |
no_license
|
---
layout: post
title: Java Unit Test
date: 2014-12-06
---
最近在用Java进行一些开发,在写的过程中需要进行单元测试工作。选用的是JUnit作为单测框架,后续使用了EasyMock,和PowerMock进行一些mock工作。EasyMock主要来完成对对象级别的Mock,而PowerMock则是用来完成对于静态方法、构造函数的Mock。
至于上述mock是怎么做的,暂时还没有进行深入研究。这篇博客主要是记录下怎么使用的,为的是后面再用的时候能够快速的使用。
## 要测试的类
有A,B,C三个类,其中A是我们要测试的类,A类中包含B类,又会调用C的静态函数。
{% highlight java %}
public class B {
public boolean check() {
return true;
}
}
public class C {
public static String hello() {
return "Hello";
}
}
public class A {
private B b;
public A(B b) {
this.b = b;
}
public boolean check() {
return b.check();
}
public void print() {
C.hello();
}
}
{% endhighlight %}
其中A是要进行测试的类,而B,C则是依赖的类,需要Mock掉
## EasyMock
使用EasyMock可以Mock掉依赖的B从而能够控制返回。具体的测试代码如下
{% highlight java %}
import junit.framework.Assert;
import org.easymock.EasyMock;
import org.junit.Test;
public class ATest {
// 如果为了期待有异常抛出可以使用如下的方式
// @Test(expected = XxxException.class)
@Test
public void testCheck() {
B mockB = EasyMock.createMock(B.class);
// 这里的anyTimes是为了保证check()多次调用的时候都会返回我们设定的值
// 在anyTimes这里我就遇到了一个非常大的坑,
// 结果搞了很久才发现是自己Mock的问题。
EasyMock.expect(mockB.check()).andReturn(false).anyTimes();
EasyMock.replay(mockB);
// 将Mock的对象传入。
A a = new A(mockB);
Assert.assertFalse(a.check());
}
}
{% endhighlight %}
上面就是EasyMock的一个基本的使用方式。稍微有点复杂的就是对于没有返回值的函数需要进行Mock的时候可以使用如下的方式。
正常的方式是
{% highlight java %}
EasyMock.expect(mockB.check()).andReturn(false).anyTimes();
{% endhighlight %}
如果对于没有返回值那么需要改成
{% highlight java %}
mockB.noReturnFunc();
EasyMock.expectLastCall().andXXX()
{% endhighlight %}
对于一般的情况,EasyMock就足够了。
## PowerMock
对于一些静态方法,以及New Object这种调用,那么EasyMock则是无能为力了。这时候就是PowerMock大显身手的时候了。对于上述对于C类静态方法调用的Mock方式如下
{% highlight java %}
import junit.framework.Assert;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
// 这里需要指定使用PowerMockRunner,因为PowerMock可能需要修改一些字节码之类的东西
@RunWith(PowerMockRunner.class)
// 这里告诉PowerMock对log4j不要进行Mock,然后可以正常打印,并且在启动命令行中,增加“-Dlog4j.ignoreTCL=true”
@PowerMockIgnore("org.apache.log4j.*")
// 这里需要告诉PowerMock需要Mock什么类。多个类的话可以使用{A.class, B.class}方式
@PrepareForTest({C.class})
public class ATest {
@Test
public void testPrint() {
// 这里是说要Mock C类的静态方法。
PowerMock.mockStatic(C.class);
// 设定静态方法Mock掉的方式
EasyMock.expect(C.hello()).andReturn("world").anyTimes();
PowerMock.replay(C.class);
A a = new A(new B());
Assert.assertEquals("world", a.print());
}
}
{% endhighlight %}
至此,两种Mock的方式就都介绍完了,基本上够用了。当然了,对于具体这些Mock的实现机制,我还没有去看,如果要真的明白了的话,可能会对Java会有更加深刻的了解。
## 后续
在后续使用PowerMock的时候还是遇到了不少的坑,都在下述逐步增加
1. 在增加javassist会导致所有的静态函数Mock都失败,可以使用如下方式解决。在JVM启动参数中增加"-XX:-UseSplitVerifier"参数
|
Markdown
|
UTF-8
| 624 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
# People.framework
[](https://github.com/Carthage/Carthage)
This is an example framework for iOS & Mac.
## Installation
[Carthage](https://github.com/carthage/carthage) is the recommended way to install People. Add the following to your Cartfile:
``` ruby
github "soffes/ExampleFramework"
```
For manual installation, I recommend adding the project as a subproject to your project or workspace and adding the framework as a target dependency.
## Usage
```swift
import People
let person = Person(name: "Sam")
```
Enjoy.
|
C++
|
UTF-8
| 650 | 3.5625 | 4 |
[] |
no_license
|
#include "MergeSort.h"
void MergeSort(int* arr, int s, int e) {
if(e > s) {
int mid = (s + e) / 2;
MergeSort(arr, s, mid);
MergeSort(arr, mid + 1, e); // Divide array into two parts.
int p = s, q = mid + 1, i = 0;
int* temp = (int*) malloc((e - s + 1) * sizeof(int));
while(true) { // Merge two array
if(p > mid && q > e) break;
else if(p > mid != q > e) temp[i++] = (p > mid ? arr[q++] : arr[p++]);
else if(arr[p] > arr[q]) temp[i++] = arr[q++];
else temp[i++] = arr[p++];
}
for(int j = 0; j < i; j++)
arr[j + s] = temp[j]; // Copy temporary array into existing array.
free(temp);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.