language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 20,414 | 1.992188 | 2 | [] | no_license | package nl.zeesoft.zodb.database;
import java.io.File;
import java.io.IOException;
import java.util.List;
import nl.zeesoft.zodb.Generic;
import nl.zeesoft.zodb.Locker;
import nl.zeesoft.zodb.Messenger;
import nl.zeesoft.zodb.WorkerUnion;
import nl.zeesoft.zodb.database.gui.GuiController;
import nl.zeesoft.zodb.database.index.IdxClass;
import nl.zeesoft.zodb.database.index.IdxObject;
import nl.zeesoft.zodb.database.index.IdxUniqueConstraint;
import nl.zeesoft.zodb.database.model.MdlModel;
import nl.zeesoft.zodb.database.server.SvrController;
import nl.zeesoft.zodb.event.EvtEvent;
import nl.zeesoft.zodb.event.EvtEventPublisher;
import nl.zeesoft.zodb.event.EvtEventSubscriber;
import nl.zeesoft.zodb.file.FileIO;
/**
* This is the main database controller
*
* The handleMainMethodsArguments method is just one possible way to use this controller.
* Use any of the public methods to construct and manage a more specific implementation.
*/
public final class DbController extends EvtEventPublisher {
private static final String INSTALL_SCRIPT_FILE = "install.bat";
public static final String DB_INSTALLING = "DB_INSTALLING";
public static final String DB_INSTALLED = "DB_INSTALLED";
public static final String DB_STARTING = "DB_STARTING";
public static final String DB_STARTED = "DB_STARTED";
public static final String DB_STOPPING = "DB_STOPPING";
public static final String DB_STOPPED = "DB_STOPPED";
public static final String DB_INITIALIZING_MODEL = "DB_INITIALIZING_MODEL";
public static final String DB_INITIALIZED_MODEL = "DB_INITIALIZED_MODEL";
public static final String DB_REVERTING_MODEL = "DB_REVERTING_MODEL";
public static final String DB_REVERTED_MODEL = "DB_REVERTED_MODEL";
public static final String DB_UPDATING_MODEL = "DB_UPDATING_MODEL";
public static final String DB_UPDATED_MODEL = "DB_UPDATED_MODEL";
private static DbController controller = null;
private Object controllerIsLockedBy = null;
private DbControllerStatusWorker statusWorker = null;
private DbControllerCommandWorker commandWorker = null;
private boolean stopped = false;
private DbController() {
statusWorker = new DbControllerStatusWorker();
commandWorker = new DbControllerCommandWorker();
}
public static DbController getInstance() {
if (controller==null) {
controller = new DbController();
}
return controller;
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
/**
* if the database is installed
* then
* if args==null OR args[0].lenght==0 then start the database
* else if args[0].equals("STOP") then stop the database
* else if args[0].equals("UPDATE") then update the abstract data model
* else if args[0].equals("REVERT") then revert changes to the database data model
* else if args[0].equals("SHOW_GUI") then show the database control GUI
* else install the database, optional arguments: [1]=jarFileName [2]=memorySettingLow [3]=memorySettingHigh
*
* @param args The String array with arguments
*/
public void handleMainMethodsArguments(String[] args) {
if (DbConfig.getInstance().fileExists()) {
DbConfig.getInstance().unserialize();
if (args==null || args.length==0 || args[0]==null || args[0].length()==0) {
if (checkWorking()) {
Messenger.getInstance().debug(this, "ZODB is already working in: " + DbConfig.getInstance().getDataDir());
showGUI();
} else {
GuiController.getInstance().initializeMainFrame(false);
GuiController.getInstance().setProgressFrameTitle("Starting database ...");
GuiController.getInstance().showProgressFrame();
if (start(DbConfig.getInstance().isShowGUI())) {
if (FileIO.fileExists(INSTALL_SCRIPT_FILE)) {
try {
FileIO.deleteFile(INSTALL_SCRIPT_FILE);
} catch (IOException e) {
Messenger.getInstance().warn(this,"Unable to delete " + INSTALL_SCRIPT_FILE);
}
}
checkOpenServer();
}
GuiController.getInstance().hideProgressFrame();
}
} else if (args[0].equals(DbControllerCommandWorker.DB_COMMAND_STOP)) {
if (checkWorking()) {
stop();
}
} else if (args[0].equals(DbControllerCommandWorker.DB_COMMAND_UPDATE)) {
if (checkWorking()) {
update();
}
} else if (args[0].equals(DbControllerCommandWorker.DB_COMMAND_REVERT)) {
if (checkWorking()) {
revert();
}
} else if (args[0].equals(DbControllerCommandWorker.DB_COMMAND_SHOW_CONTROLLER)) {
if (checkWorking()) {
showGUI();
}
} else {
Messenger.getInstance().error(this, "Unhandled action: " + args[0]);
}
} else {
StringBuilder errorText = DbConfig.getInstance().getModel().getErrorText();
if (errorText.length()==0) {
String jarFileName = "";
String memorySetting1 = "";
String memorySetting2 = "";
String memorySettings = "";
if (args!=null && args.length>1 && args[1]!=null) {
jarFileName = args[1].toLowerCase();
}
if (args!=null && args.length>2 && args[2]!=null) {
memorySetting1 = args[2];
}
if (args!=null && args.length>3 && args[3]!=null) {
memorySetting2 = args[3];
}
if (memorySetting1.length()>0 && memorySetting2.length()>0) {
memorySettings = memorySetting1 + " " + memorySetting2;
}
if (!installDefault(jarFileName,memorySettings)) {
System.exit(1);
} else {
System.exit(0);
}
} else {
Messenger.getInstance().start();
Messenger.getInstance().error(this,"Model has errors:\n" + errorText);
Messenger.getInstance().addSubscriber(new EvtEventSubscriber() {
@Override
public void handleEvent(EvtEvent e) {
// Ignore
}
});
Messenger.getInstance().stop();
System.exit(1);
}
}
}
public boolean checkWorking() {
boolean working = false;
lockController(this);
working = statusWorker.checkWorking();
unlockController(this);
return working;
}
public boolean getStopped() {
boolean r = false;
lockController(this);
r = stopped;
unlockController(this);
return r;
}
public boolean start(boolean showProgress) {
boolean success = false;
if (ifLockController(this)) {
stopped = false;
if (showProgress) {
Messenger.getInstance().addSubscriber(GuiController.getInstance());
} else {
Messenger.getInstance().addSubscriber(new EvtEventSubscriber() {
@Override
public void handleEvent(EvtEvent e) {
// Ignore
}
});
}
Messenger.getInstance().start();
publishEvent(new EvtEvent(DB_STARTING,this,null));
Messenger.getInstance().debug(this, "Starting ZODB in: " + DbConfig.getInstance().getDataDir());
boolean error = false;
if (modelFileExists()) {
statusWorker.start();
commandWorker.start();
DbConfig.getInstance().getModel().unserialize(MdlModel.getFullFileName());
if (!DbConfig.getInstance().getModel().check() && DbConfig.getInstance().getModel().createDirectories(this)) {
DbIndex.getInstance().unserialize(this);
DbIndex.getInstance().startWorkers(true);
} else {
error = true;
}
} else {
error = true;
}
if (error) {
stop(false);
System.exit(1);
} else {
success = true;
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
DbController.getInstance().stop(true);
}
});
}
unlockController(this);
// It seems certain contexts need a little pause before the database is ready
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Messenger.getInstance().error(this,"Startup pause interrupted: " + e);
}
publishEvent(new EvtEvent(DB_STARTED,this,success));
}
return success;
}
public void stop() {
DbControllerCommandWorker.issueCommand(DbControllerCommandWorker.DB_COMMAND_STOP);
}
public void update() {
DbControllerCommandWorker.issueCommand(DbControllerCommandWorker.DB_COMMAND_UPDATE);
}
public void revert() {
DbControllerCommandWorker.issueCommand(DbControllerCommandWorker.DB_COMMAND_REVERT);
}
public void showGUI() {
if (DbConfig.getInstance().isShowGUI()) {
DbControllerCommandWorker.issueCommand(DbControllerCommandWorker.DB_COMMAND_SHOW_CONTROLLER);
}
}
public boolean checkOpenServer() {
boolean error = false;
if (DbConfig.getInstance().isOpenServer()) {
error = !openServer();
}
return !error;
}
public boolean openServer() {
closeServer();
return SvrController.getInstance().open();
}
/**
* Basic installation required by the database
*
* @param jarFileName the optional jar file name
* @param memorySettings the optional jar file name
* @return true if the installation was successful
*/
public boolean installDefault(String jarFileName,String memorySettings) {
return install(jarFileName,memorySettings,false);
}
public boolean install(String jarFileName,String memorySettings,boolean databaseOnly) {
publishEvent(new EvtEvent(DB_INSTALLING,this,null));
if (!databaseOnly) {
if (jarFileName.length()==0) {
jarFileName = "zodb.jar";
}
if (memorySettings.length()==0) {
memorySettings = "-Xms128m -Xmx1024m";
}
}
boolean error = false;
error = !installDatabase();
if (!error) {
// Debug logging for install.log
DbConfig.getInstance().setDebug(true);
DbConfig.getInstance().setDebugPerformance(true);
DbConfig.getInstance().setDebugRequestLogging(true);
DbConfig.getInstance().getCacheConfig().setDebug(true);
if (!databaseOnly) {
// TODO: Create UNIX style script installation
installZODBWindowsScripts(jarFileName,memorySettings);
}
start(false);
initializeDbModel();
stop(false);
DbConfig.getInstance().getCache().reinitialize(this);
error = Messenger.getInstance().isError();
}
publishEvent(new EvtEvent(DB_INSTALLED,this,!error));
return error;
}
public boolean initializeDbModel() {
return updateDbModelPublishEvents(DB_INITIALIZING_MODEL,DB_INITIALIZED_MODEL);
}
// Called by controller command worker and protocol
public boolean updateDbModel() {
return updateDbModelPublishEvents(DB_REVERTING_MODEL,DB_REVERTED_MODEL);
}
// Called by controller command worker
protected boolean updateMdlModel() {
boolean converted = false;
if (ifLockController(this)) {
publishEvent(new EvtEvent(DB_UPDATING_MODEL,this,null));
DbRequestQueue.getInstance().setReadOnly(true,this);
MdlModel useModel = DbConfig.getInstance().getNewModel();
List<String> originalFullNames = useModel.getFullNames();
useModel.unserialize(MdlModel.getFullFileName());
DbModelConverter converter = new DbModelConverter();
converted = converter.updateMdlModel(useModel,originalFullNames,false);
if (converted) {
Messenger.getInstance().debug(this,"Updating database ...");
if (useModel.createDirectories(this)) {
if (addUniqeConstraintIndexes(converter.getAddIndexes())) {
// Remove index directories
for (IdxObject removeIndex: converter.getRemoveIndexes()) {
boolean deleted = false;
try {
String dirName = removeIndex.getDirName();
if (removeIndex instanceof IdxClass) {
dirName = ((IdxClass) removeIndex).getClassDirName();
}
if (FileIO.fileExists(dirName)) {
deleted = FileIO.deleteDirectory(dirName);
if (!deleted) {
Messenger.getInstance().error(this,"Failed to remove index directory: " + dirName);
}
}
} catch (IOException e) {
Messenger.getInstance().error(this,"Exception while removing index directories: " + e);
}
}
addNonUniqeConstraintIndexes(converter.getAddIndexes());
// Update working model
useModel.serialize(MdlModel.getFullFileName());
DbConfig.getInstance().getModel().unserialize(MdlModel.getFullFileName());
useModel.cleanUp();
Messenger.getInstance().debug(this,"Updated database");
} else {
Messenger.getInstance().error(this,"Failed to update database, error while updating unique indexes");
converted = false;
}
} else {
Messenger.getInstance().error(this,"Failed to update database");
converted = false;
}
}
boolean stoppedIndex = DbIndex.getInstance().stopWorkers(false);
DbRequestQueue.getInstance().setReadOnly(false,this);
if (stoppedIndex) {
DbIndex.getInstance().restart(this);
if (converted && converter.isRevert()) {
converter.updateDbModel(DbConfig.getInstance().getModel());
}
}
publishEvent(new EvtEvent(DB_UPDATED_MODEL,this,converted));
unlockController(this);
}
return converted;
}
public void stop(boolean showProgress) {
lockController(this);
if (!stopped) {
stopped = true;
if (showProgress) {
GuiController.getInstance().setProgressFrameTitle("Stopping database ...");
GuiController.getInstance().showProgressFrame();
}
publishEvent(new EvtEvent(DB_STOPPING,this,null));
closeServer();
Messenger.getInstance().debug(this, "Stopping ZODB in: " + DbConfig.getInstance().getDataDir());
DbIndex.getInstance().stopWorkers(showProgress);
if (statusWorker.isWorking()) {
statusWorker.stop();
}
if (showProgress) {
GuiController.getInstance().incrementProgressFrameDone();
}
if (commandWorker.isWorking()) {
commandWorker.stop();
}
if (showProgress) {
GuiController.getInstance().incrementProgressFrameDone();
}
Messenger.getInstance().stop();
if (showProgress) {
GuiController.getInstance().incrementProgressFrameDone();
}
WorkerUnion.getInstance().stopWorkers(commandWorker);
if (showProgress) {
GuiController.getInstance().incrementProgressFrameDone();
}
publishEvent(new EvtEvent(DB_STOPPED,this,null));
}
unlockController(this);
}
/**************************** PRIVATE METHODS **************************/
private synchronized boolean ifLockController(Object source) {
boolean locked = false;
if (!controllerIsLocked()) {
lockController(source);
locked = true;
}
return locked;
}
private synchronized void lockController(Object source) {
int attempt = 0;
while (controllerIsLocked()) {
try {
wait();
} catch (InterruptedException e) {
}
attempt ++;
if (attempt>=1000) {
Messenger.getInstance().warn(this,Locker.getLockFailedMessage(attempt,source));
attempt = 0;
}
}
controllerIsLockedBy = source;
}
private synchronized void unlockController(Object source) {
if (controllerIsLockedBy==source) {
controllerIsLockedBy=null;
notifyAll();
}
}
private synchronized boolean controllerIsLocked() {
return (controllerIsLockedBy!=null);
}
private boolean updateDbModelPublishEvents(String beforeEvent,String afterEvent) {
boolean updated = false;
if (ifLockController(this)) {
publishEvent(new EvtEvent(beforeEvent,this,null));
DbModelConverter converter = new DbModelConverter();
updated = converter.updateDbModel(DbConfig.getInstance().getModel());
publishEvent(new EvtEvent(afterEvent,this,updated));
unlockController(this);
}
return updated;
}
private boolean closeServer() {
boolean closed = false;
if (SvrController.getInstance().isOpen()) {
closed = SvrController.getInstance().close();
}
return closed;
}
private boolean modelFileExists() {
boolean exists = true;
File modelFile = new File(MdlModel.getFullFileName());
if (!modelFile.exists()) {
Messenger.getInstance().error(this, "Unable to find model file: " + MdlModel.getFullFileName());
exists = false;
}
return exists;
}
private boolean addUniqeConstraintIndexes(List<IdxObject> indexes) {
boolean error = false;
for (IdxObject index: indexes) {
if (index instanceof IdxUniqueConstraint) {
DbIndexBuilder builder = new DbIndexBuilder(index);
if (!builder.buildIndex()) {
error = true;
break;
}
}
}
return !error;
}
private boolean addNonUniqeConstraintIndexes(List<IdxObject> indexes) {
boolean error = false;
for (IdxObject index: indexes) {
if (!(index instanceof IdxUniqueConstraint)) {
DbIndexBuilder builder = new DbIndexBuilder(index);
if (!builder.buildIndex()) {
error = true;
break;
}
}
}
return !error;
}
private boolean installDatabase() {
boolean error = false;
Messenger.getInstance().debug(this, "Installing ZODB in: " + DbConfig.getInstance().getDataDir());
File confDir = new File(DbConfig.getInstance().getConfDir());
if (!confDir.exists()) {
confDir.mkdir();
}
if (!confDir.exists()) {
Messenger.getInstance().error(this, "Unable to create configuration directory: " + DbConfig.getInstance().getConfDir());
error = true;
}
if (!error) {
File dataDir = new File(DbConfig.getInstance().getDataDir());
if (!dataDir.exists()) {
dataDir.mkdir();
}
if (!dataDir.exists()) {
Messenger.getInstance().error(this, "Unable to create data directory: " + DbConfig.getInstance().getDataDir());
error = true;
}
}
if (!error) {
DbConfig.getInstance().serialize();
if (!DbConfig.getInstance().fileExists()) {
Messenger.getInstance().error(this, "Unable to create configuration file: " + DbConfig.getInstance().getFullFileName());
error = true;
}
}
if (!error) {
DbConfig.getInstance().getModel().serialize(MdlModel.getFullFileName());
File modelFile = new File(MdlModel.getFullFileName());
if (!modelFile.exists()) {
Messenger.getInstance().error(this, "Unable to create model file: " + MdlModel.getFullFileName());
error = true;
}
}
if (!error) {
error = !DbConfig.getInstance().getModel().createDirectories(this);
}
return !error;
}
/**
* Windows ZODB script installation
*
* @param jarFileName the file name of the jar (see handleMainMethodsArguments)
* @param memorySettings optional java executable memory setting parameters
*/
private void installZODBWindowsScripts(String jarFileName,String memorySettings) {
String dir = DbConfig.getInstance().getInstallDir();
File binDir = new File(dir + "bin/");
File outDir = new File(dir + "out/");
if (
((binDir.exists() && (binDir.isDirectory())) || (binDir.mkdir())) &&
((outDir.exists() && (outDir.isDirectory())) || (outDir.mkdir()))
) {
FileIO file = new FileIO();
file.writeFile(Generic.dirName(binDir.getAbsolutePath()) + "caller.bat", getCallerScript(memorySettings,jarFileName));
file.writeFile(Generic.dirName(binDir.getAbsolutePath()) + "background.vbs", getBackgroundScript());
file.writeFile(dir + "start.bat", getStartScript());
file.writeFile(dir + "stop.bat", getStopScript());
file.writeFile(dir + "control.bat", getGUIScript());
}
}
private String getCallerScript(String memorySettings,String jarFileName) {
return
"@ECHO OFF" + "\r\n" +
"java " + memorySettings + " -jar lib/" + jarFileName + " %2 %3 1>out\\\"%1\".log 2>out\\\"%1\"Errors.log" + "\r\n";
}
private String getBackgroundScript() {
return
"set args = WScript.Arguments" + "\r\n" +
"num = args.Count" + "\r\n" +
"if num = 0 then" + "\r\n" +
" WScript.Echo \"Usage: [CScript | WScript] background.vbs aScript.bat <some script arguments>\"" + "\r\n" +
" WScript.Quit 1" + "\r\n" +
"end if" + "\r\n" +
"sargs = \"\"" + "\r\n" +
"if num > 1 then" + "\r\n" +
" sargs = \" \"" + "\r\n" +
" for k = 1 to num - 1" + "\r\n" +
" anArg = args.Item(k)" + "\r\n" +
" sargs = sargs & anArg & \" \"" + "\r\n" +
" next" + "\r\n" +
"end if" + "\r\n" +
"Set WshShell = WScript.CreateObject(\"WScript.Shell\")" + "\r\n" +
"WshShell.Run \"\"\"\" & WScript.Arguments(0) & \"\"\"\" & sargs, 0, False" + "\r\n"
;
}
private String getStartScript() {
return
"@ECHO OFF" + "\r\n" +
"wscript.exe bin\\background.vbs bin\\caller.bat start" + "\r\n";
}
private String getStopScript() {
return
"@ECHO OFF" + "\r\n" +
"wscript.exe bin\\background.vbs bin\\caller.bat stop " + DbControllerCommandWorker.DB_COMMAND_STOP + "\r\n";
}
private String getGUIScript() {
return
"@ECHO OFF" + "\r\n" +
"wscript.exe bin\\background.vbs bin\\caller.bat control " + DbControllerCommandWorker.DB_COMMAND_SHOW_CONTROLLER + "\r\n";
}
}
|
JavaScript | UTF-8 | 2,327 | 3.859375 | 4 | [] | no_license | /*
//GAME FUNCTION
-player must guess a no. betweel 1 and 10
-player gets a certain fixed amout of guess
-notify the player about the guesses remaining
-notify the payer of the correct answer if loose
-let player choose to play again
*/
//gsne values
let min=4,
max=10,
winningnum=getrandomnumber(min,max),
guessesleft=3;
//UI Elements
const game =document.querySelector('#game'),
minnum=document.querySelector('.min-num'),
maxnum=document.querySelector('.max-num'),
guessbtn=document.querySelector('#guess-btn'),
guessinput=document.querySelector('#guess-input'),
message=document.querySelector('.message');
minnum.textContent=min;
maxnum.textContent=max;
//play again event listener
game.addEventListener('mousedown',function(e){
if(e.target.classname==='play-again'){
window.location.reload();
}
})
guessbtn.addEventListener('click',function(){
let guess=parseInt(guessinput.value);
console.log(guess);
if(isNaN(guess) || guess < min || guess > max){
setmessage(`enter the number between ${min} and ${max}`,'red');
};
//check if won
if(guess===winningnum){
// guessinput.disabled=true;
// // guessinput.style.borderColor='green';
// setmessage(`You Win!!..${winningnum} is the correct answer `,'green');
gameover(true,`You Win!!..${winningnum} is the correct answer `,'green');
}
else{
guessesleft -= 1;
if(guessesleft===0){
// guessinput.disabled=true;
// setmessage(`You loose!!the correct answer is ${winningnum}`,'red');
gameover(false,`You loose!!the correct answer is ${winningnum}`,'red');
}else{
guessinput.value='';
setmessage(`guesses left ${guessesleft}`,'red')
}
}
});
function gameover(won,msg,color){
guessinput.disabled=true;
// guessinput.style.borderColor='green';
setmessage(msg,color);
//play again
guessbtn.value='play again';
guessbtn.classname+='play-again';
}
function getrandomnumber(min,max){
console.log(Math.floor(Math.random()*(max-min+1)+min));
}
function setmessage(msg,color){
guessinput.style.borderColor=color;
message.style.color=color;
message.textContent=msg;
}
//error part is not working
//random number generation not working |
JavaScript | UTF-8 | 550 | 3.453125 | 3 | [] | no_license | class Person {
constructor(first_name, last_name) {
this.first_name = first_name;
this.last_name = last_name;
}
getFullName() {
return this.first_name + " " + this.last_name;
}
}
class Indian extends Person {
constructor(first_name, last_name, aadhar_card_number) {
super(first_name, last_name);
this.aadhar_card_number = aadhar_card_number;
}
getFullName() {
return this.last_name + ", " + this.first_name;
}
}
let anshul = new Indian("Anshul", "Gupta", 12345)
console.log(anshul.getFullName()); |
JavaScript | UTF-8 | 558 | 3.515625 | 4 | [] | no_license | var randomNumber1=Math.floor(Math.random()*6+1);
var randomNumber2=Math.floor(Math.random()*6+1);
document.querySelector("img").setAttribute("src","images/dice"+randomNumber1+".png");
document.querySelectorAll("img")[1].setAttribute("src","images/dice"+randomNumber2+".png");
if(randomNumber1>randomNumber2)
{
document.querySelector("h1").innerHTML="🏁 winer is player 1";
}
else if(randomNumber2>randomNumber1){
document.querySelector("h1").innerHTML="winer is player 2";
}
else{
document.querySelector("h1").innerHTML="there is no winer here";
}
|
Python | UTF-8 | 1,514 | 3.34375 | 3 | [] | no_license | '''
developer: Wendy
date: Aug 26,2020
version: 1.0
function: air quality index calculations
'''
def cal_linear(iaqi_lo,iaqi_hi, bp_lo, bp_hi, cp):
'''
范围缩放
'''
iaqi = (iaqi_hi - iaqi_lo) * (cp - bp_lo)/(bp_hi - bp_lo) + iaqi_lo
def cal_pm_iaqi(pm_val):
'''
calculate pm iaqi
'''
if 0 <= pm_val < 36:
iaqi = cal_linear(0, 50, 0, 35, pm_val)
elif 36<= pm_val < 76:
iaqi = cal_linear(50, 100, 35, 75, pm_val)
elif 76 <= pm_val < 116:
iaqi = cal_linear(100, 150, 75, 115, pm_val)
elif 76 <= pm_val < 116:
iaqi = cal_linear(100, 150, 75, 115, pm_val)
elif 76 <= pm_val < 116:
iaqi = cal_linear(100, 150, 75, 115, pm_val)
def cal_co_iaqi(co_val):
'''
calculate co iaqi
'''
pass
def cal_aqi(param_list):
pm_val = param_list[0]
co_val = param_list[1]
pm_iaqi = cal_pm_iaqi(pm_val)
am_iaqi = cal_co_iaqi(co_val)
iaqi_list = []
iaqi_list.append(pm_iaqi)
iaqi_list.append(co_iaqi)
aqi = max(iaqi_list)
return aqi
def main():
input('Please provide the information, devided by a space:')
input_str = input('(1)PM2.5 (2)CO:')
str_list = input_str.split(' ')
pm_val = float(str_list[0])
co_val = float(str_list[1])
param_list = []
param_list.append(pm_val)
param_list.append(co_val)
aqi_val = cal_aqi(param_list)
print('air quality index is: {}'.format(aqi_val))
if __name__=='__main__':
main() |
Java | UTF-8 | 227 | 2.8125 | 3 | [] | no_license | package ejercicio10;
public enum Categoria {
JEFE('J'), ENCARGADO('E'), EMPLEADO('D');
private char initial;
Categoria(char initial){
this.initial=initial;
}
public char getCodigo() {
return initial;
}
}
|
Swift | UTF-8 | 3,594 | 3.6875 | 4 | [] | no_license | //
// lesson_3(enum,struct).swift
// homeWork_lesson_2
//
// Created by user155176 on 6/24/19.
// Copyright © 2019 user155176. All rights reserved.
//
//-------------------------------------------------------------------------------------------------------------------------------------------
/*
1. Описать несколько структур – любой легковой автомобиль и любой грузовик.
2. Структуры должны содержать марку авто, год выпуска, объем багажника/кузова, запущен ли двигатель, открыты ли окна, заполненный объем багажника.
3. Описать перечисление с возможными действиями с автомобилем: запустить/заглушить двигатель, открыть/закрыть окна, погрузить/выгрузить из кузова/багажника груз определенного объема.
4. Добавить в структуры метод с одним аргументом типа перечисления, который будет менять свойства структуры в зависимости от действия.
5. Инициализировать несколько экземпляров структур. Применить к ним различные действия.
6. Вывести значения свойств экземпляров в консоль.
*/
//--------------------------------------------------------------------------------------------------------------------------------------------
import Foundation
struct Car {
var model:String;
var dateOfrelease:Int;
var carTrunk:Float;
var cost:Int;
enum EngineCapacity: Int{
case unknown = 0, microCar = 1, smallCar, medium, powerful
init(){
self = .unknown
}
func insuarence() -> (Int){
if self.rawValue == 1{
return 1000
} else if self.rawValue == 2{
return 2000
} else if self.rawValue == 3{
return 3000
} else if self.rawValue == 0{
return 0
} else {
return 6000
}
}
}
var status = EngineCapacity()
}
var testTwo = Car(model: "lada", dateOfrelease: 2222, carTrunk: 1.7, cost: 2222, status: Car.EngineCapacity.microCar)
var test = Car.EngineCapacity.microCar.insuarence()
print(testTwo)
print(testTwo.status.insuarence())
struct UsageOfCar {
var engineStart:Bool;
var usedValueOfTrunk:Float;
init (){
engineStart = false;
usedValueOfTrunk = 0.0;
}
//3. Описать перечисление с возможными действиями с автомобилем: запустить/заглушить двигатель, открыть/закрыть окна, погрузить/выгрузить из кузова/багажника груз определенного объема.
/*
enum StatusOfCar{
case windows(
leftWindow:String,
rightWindow:String,
status:Bool)
case carLock(Bool)
case loadTrunk(Int)
case engineStatus(Bool)
func checkUp() -> (String){
switch self{
case .windows(leftWindow: <#T##String#>, rightWindow: <#T##String#>, status: <#T##Bool#>)
}
}
}
*/
//mutating func checkCarStatus(_)
}
|
Shell | UTF-8 | 983 | 3.296875 | 3 | [] | no_license | #!/bin/sh
# Derived from https://www.kubeflow.org/docs/distributions/ibm/deploy/install-kubeflow-on-iks/#storage-setup-for-a-classic-ibm-cloud-kubernetes-cluster
# Retrieved May 3 2021
ibmcloud ks cluster config --cluster $1
# Set the File Storage with Group ID support as the default storage class.
export NEW_STORAGE_CLASS=ibmc-file-gold-gid
export OLD_STORAGE_CLASS=$(kubectl get sc -o jsonpath='{.items[?(@.metadata.annotations.storageclass\.kubernetes\.io\/is-default-class=="true")].metadata.name}')
kubectl patch storageclass ${NEW_STORAGE_CLASS} -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
# Remove other default storage classes
kubectl patch storageclass ${OLD_STORAGE_CLASS} -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'
# List all the (default) storage classes
echo "You should see only ibmc-file-gold-gid (default) listed below:"
kubectl get storageclass | grep "(default)"
|
C++ | GB18030 | 3,091 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// ߣʶ
/// ϵߣ94458936@qq.com
///
/// std:c++20
/// 汾0.9.0.11 (2023/06/08 19:33)
#ifndef MATHEMATICS_INTERSECTION_DYNAMIC_FIND_INTERSECTOR_SEGMENT3_TRIANGLE3_H
#define MATHEMATICS_INTERSECTION_DYNAMIC_FIND_INTERSECTOR_SEGMENT3_TRIANGLE3_H
#include "Mathematics/MathematicsDll.h"
#include "Mathematics/Intersection/DynamicIntersector.h"
#include "Mathematics/Objects3D/Segment3.h"
#include "Mathematics/Objects3D/Triangle3.h"
namespace Mathematics
{
template <typename Real>
class DynamicFindIntersectorSegment3Triangle3 : public DynamicIntersector<Real, Vector3>
{
public:
using ClassType = DynamicFindIntersectorSegment3Triangle3<Real>;
using ParentType = DynamicIntersector<Real, Vector3>;
using Vector3 = Vector3<Real>;
using Segment3 = Segment3<Real>;
using Triangle3 = Triangle3<Real>;
using Vector3Tools = Vector3Tools<Real>;
using Math = typename ParentType::Math;
public:
DynamicFindIntersectorSegment3Triangle3(const Segment3& segment,
const Triangle3& triangle,
Real tmax,
const Vector3& lhsVelocity,
const Vector3& rhsVelocity,
const Real epsilon = Math::GetZeroTolerance());
CLASS_INVARIANT_OVERRIDE_DECLARE;
NODISCARD Segment3 GetSegment() const noexcept;
NODISCARD Triangle3 GetTriangle() const noexcept;
NODISCARD Real GetSegmentParameter() const noexcept;
NODISCARD Real GetTriangleBary0() const noexcept;
NODISCARD Real GetTriangleBary1() const noexcept;
NODISCARD Real GetTriangleBary2() const noexcept;
/// Щּڶ̬ҽѯ֮á
/// ڡFind()ѯʹGetSegmentParameter()GetTriangleBary?()ԼӴ㡣
NODISCARD int GetQuantity() const noexcept;
NODISCARD Vector3 GetPoint(int index) const;
private:
/// ̬ҽѯ еʱͨGetPoint(0)ʵһ㣻
/// ýһΣͨGetPoint(0)GetPoint(1)ʵһ㣬£ȡĵǶζ˵㡣
/// һνͨGetContactTime()ʵġ
void Find();
private:
// ҪཻĶ
Segment3 segment;
Triangle3 triangle;
// йع̶Ϣ
Real segmentParameter;
Real triangleBary0;
Real triangleBary1;
Real triangleBary2;
// йض̬Ϣ
int quantity;
Vector3 point0;
Vector3 point1;
};
}
#endif // MATHEMATICS_INTERSECTION_DYNAMIC_FIND_INTERSECTOR_SEGMENT3_TRIANGLE3_H
|
Java | UTF-8 | 20,587 | 2.390625 | 2 | [] | no_license | package net.trizmo.mtgcards;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.Random;
import net.trizmo.mtgcards.deckeditor.DeckManagerButton;
import net.trizmo.mtgcards.inCameCards.BattlefieldCard;
import net.trizmo.mtgcards.inCameCards.ExiledCard;
import net.trizmo.mtgcards.inCameCards.GraveyardCard;
import net.trizmo.mtgcards.inCameCards.HandCard;
import net.trizmo.mtgcards.inCameCards.LibraryCard;
import net.trizmo.mtgcards.inCameCards.ZoomCard;
import net.trizmo.mtgcards.input.ButtonHandler;
public class CardHandler {
public static boolean mouseDown;
public static Rectangle[] spotLocations = new Rectangle[5];
public static CardInteract interactionCard;
public static int firstOpen;
public static boolean alreadyScanned = false;
public static boolean moved;
public static boolean terminate = false;
public static Point par1Point = new Point(0,0);
public static ZoomCard zoomCard;
public static DeckManagerButton[] counterButtons;
public static void mousePressed(MouseEvent e)
{
mouseDown = true;
if(!Screen.zoom ){
if(Screen.scene == 2) interactionCard = getInteractCard(e);
Rectangle rect = new Rectangle(Screen.width - 100, 100, 100, 120);
if(Screen.scene == 2)
{
if(rect.contains(e.getPoint()))
{
LifeHandler.changeLife(e);
}
rect = null;
}
}
}
public static void mouseDragged(MouseEvent e)
{
if(interactionCard != null && zoomCard == null){
moved = true;
moveCard();
}
}
public static void mouseReleased(MouseEvent e)
{
mouseDown = false;
if(interactionCard != null && Screen.scene == 2 && e.getButton() != 2 && moved && interactionCard.getLocation() != 5)
{
if(spotLocations[0].contains(e.getPoint()))
{
for(int i = Screen.libraryCards.length - 1; i >= 0; i--)
{
if (Screen.libraryCards[i] == null)
{
firstOpen = i;
}
}
Screen.libraryCards[firstOpen] = new LibraryCard(Screen.battlefieldCards[interactionCard.getArrayLocation()].getCardName(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getImage(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getRarity());
Screen.battlefieldCards[interactionCard.getArrayLocation()] = null;
}else if(spotLocations[1].contains(e.getPoint()))
{
for(int i = Screen.handCards.length - 1; i >= 0; i--)
{
if(Screen.handCards[i] == null)
{
firstOpen = i;
}
}
Screen.handCards[firstOpen] = new HandCard(Screen.battlefieldCards[interactionCard.getArrayLocation()].getCardName(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getImage(), firstOpen, Screen.battlefieldCards[interactionCard.getArrayLocation()].getRarity());
Screen.battlefieldCards[interactionCard.getArrayLocation()] = null;
}else if(spotLocations[3].contains(e.getPoint()))
{
for(int i = Screen.graveyardCards.length - 1; i >= 0; i--)
{
if (Screen.graveyardCards[i] == null) firstOpen = i;
}
Screen.graveyardCards[firstOpen] = new GraveyardCard(Screen.battlefieldCards[interactionCard.getArrayLocation()].getCardName(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getImage(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getRarity());
Screen.battlefieldCards[interactionCard.getArrayLocation()] = null;
}else if(spotLocations[4].contains(e.getPoint()))
{
for(int i = Screen.exiledCards.length - 1; i >= 0; i--)
{
if (Screen.exiledCards[i] == null) firstOpen = i;
}
Screen.exiledCards[firstOpen] = new ExiledCard(Screen.battlefieldCards[interactionCard.getArrayLocation()].getCardName(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getImage(), Screen.battlefieldCards[interactionCard.getArrayLocation()].getRarity());
Screen.battlefieldCards[interactionCard.getArrayLocation()] = null;
}
interactionCard = null;
}else if(interactionCard != null && moved && e.getButton() != 2 && Screen.scene == 2 && interactionCard.getLocation() == 5)
{
for(int i = 0; i < spotLocations.length; i++)
{
if(spotLocations[i] != null && spotLocations[i].contains(e.getPoint())){
terminate = true;
}
}
if(terminate)
{
Screen.tokenBattlefield[interactionCard.getArrayLocation()] = null;
StackManager.shiftTokenBattlefield();
Screen.tokenBattlefield = shrinkTokenBattlefield(Screen.tokenBattlefield);
terminate = false;
}
interactionCard = null;
}
moved = false;
}
private static BattlefieldCard[] shrinkTokenBattlefield(BattlefieldCard[] tokenBattlefield) {
BattlefieldCard[] newBattlefield = new BattlefieldCard[tokenBattlefield.length - 1];
for(int i = 0; i < newBattlefield.length; i++)
{
for(int j = 0; j < tokenBattlefield.length; j++)
{
if(newBattlefield[i] == null && tokenBattlefield[j] != null)
{
newBattlefield[i] = tokenBattlefield[j];
tokenBattlefield[j] = null;
}
}
}
return newBattlefield;
}
public static void splitByState()
{
Screen.battlefieldCards = new BattlefieldCard[Screen.totalCardsInDeck];
Screen.exiledCards = new ExiledCard[Screen.totalCardsInDeck];
Screen.graveyardCards = new GraveyardCard[Screen.totalCardsInDeck];
Screen.libraryCards = new LibraryCard[Screen.totalCardsInDeck];
Screen.handCards = new HandCard[Screen.totalCardsInDeck];
for(int i = 0; i < Screen.deckCard.length; i++)
{
int state = 0;
if(Screen.deckCard[i] != null){
if(Screen.deckCard[i].getIsInLibrary())
{
state = 1;
}else if(Screen.deckCard[i].getIsInGraveyard())
{
state = 2;
}else if(Screen.deckCard[i].getIsExiled())
{
state = 3;
}else if(Screen.deckCard[i].getIsBattlefield())
{
state = 4;
}else if(Screen.deckCard[i].getIsInHand())
{
state = 5;
}
}
switch (state)
{
case 1:
putInLibrary(i);
break;
case 2:
putInGraveyard(i);
break;
case 3:
putInExile(i);
break;
case 4:
putInBattlefield(i);
break;
case 5:
putInHand(i);
break;
}
}
}
public static void putInLibrary(int index)
{
for(int i = 0; i < Screen.libraryCards.length; i++)
{
if(Screen.libraryCards[i] == null)
{
Screen.libraryCards[i] = new LibraryCard(Screen.deckCard[index].getCardName(), Screen.deckCard[index].getTextureImage(), Screen.deckCard[index].getRarity());
break;
}
}
}
public static void putInGraveyard(int index)
{
for(int i = 0; i < Screen.graveyardCards.length; i++)
{
if(Screen.graveyardCards[i] == null)
{
Screen.graveyardCards[i] = new GraveyardCard(Screen.deckCard[index].getCardName(), Screen.deckCard[index].getTextureImage(), Screen.deckCard[index].getRarity());
break;
}
}
}
public static void putInExile(int index)
{
for(int i = 0; i < Screen.exiledCards.length; i++)
{
if(Screen.graveyardCards[i] == null)
{
Screen.exiledCards[i] = new ExiledCard(Screen.deckCard[index].getCardName(), Screen.deckCard[index].getTextureImage(), Screen.deckCard[index].getRarity());
break;
}
}
}
public static void putInBattlefield(int index)
{
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] == null)
{
Screen.battlefieldCards[i] = new BattlefieldCard(Screen.deckCard[index].getCardName(), Screen.deckCard[index].getTextureImage(), Screen.deckCard[index].getX(),
Screen.deckCard[index].getY(),Screen.deckCard[index].getRarity(), Screen.deckCard[index].getTapped());
break;
}
}
}
public static void putInHand(int index)
{
for(int i = 0; i < Screen.handCards.length; i++)
{
if(Screen.handCards[i] == null)
{
Screen.handCards[i] = new HandCard(Screen.deckCard[index].getCardName(), Screen.deckCard[index].getTextureImage(), i, Screen.deckCard[index].getRarity());
break;
}
}
}
public static CardInteract getInteractCard(MouseEvent e)
{
CardInteract par1, par2, par3, par4, par5, par6;
par1 = checkLibraryClicked(e);
par2 = checkHandClicked(e);
par3 = checkBattlefieldClicked(e);
par4 = checkGraveyardClicked(e);
par5 = checkExileClicked(e);
par6 = checkTokenBattlefieldClicked(e);
if(par3 != null){
return par3;
}else if (par6 != null){
return par6;
}else if (par2 != null){
return par2;
}else if (par1 != null){
return par1;
}else if (par4 != null){
return par4;
}else if (par5 != null){
return par5;
}else{
return null;
}
}
public static CardInteract checkLibraryClicked(MouseEvent e)
{
Rectangle rect = new Rectangle(Screen.width - ((Screen.cardWidth + 30) * 3) - 15, Screen.height - ((Screen.cardHeight + 15) - (15 / 2)), Screen.cardWidth, Screen.cardHeight);
if(rect.contains(e.getPoint())){
int index = -1;//, par1Index = (Integer) null;
for(int i = Screen.libraryCards.length - 1; i >= 0; i--)
{
if(Screen.libraryCards[i] != null)
{
index = i;
break;
}
}
return new CardInteract(0, index);
} else {
return null;
}
}
public static CardInteract checkHandClicked(MouseEvent e)
{
int index = -1;
for(int i = 0; i < Screen.handCards.length; i++)
{
if(Screen.handCards[i] != null)
{
if(Screen.handCards[i].contains(e))
{
index = i;
}
}
}
if(index != -1)
{
return new CardInteract(1, index);
}else
{
return null;
}
}
public static CardInteract checkBattlefieldClicked(MouseEvent e)
{
int index = -1;
for(int i = Screen.battlefieldCards.length - 1; i >= 0; i--)
{
if(Screen.battlefieldCards[i] != null)
{
if(Screen.battlefieldCards[i].contains(e))
{
index = i;
break;
}
}
}
if(index != -1)
{
return new CardInteract(2, index);
}else
{
return null;
}
}
public static CardInteract checkTokenBattlefieldClicked(MouseEvent e)
{
int index = -1;
if(Screen.tokenBattlefield!= null) for(int i = Screen.tokenBattlefield.length - 1; i >= 0; i--)
{
if(Screen.tokenBattlefield[i] != null && Screen.tokenBattlefield[i].contains(e))
{
index = i;
break;
}
}
if(index != -1)
{
return new CardInteract(5, index);
}else
{
return null;
}
}
public static CardInteract checkGraveyardClicked(MouseEvent e)
{
int index = -1;
for(int i = Screen.graveyardCards.length - 1; i >= 0; i--)
{
if(Screen.graveyardCards[i] != null ) {
if( CardHandler.spotLocations[3].contains(e.getPoint()))
{
index = i;
break;
}
}
}
if(index != -1)
{
return new CardInteract(3, index);
}else
{
return null;
}
}
public static CardInteract checkExileClicked(MouseEvent e)
{
int index = -1;
for(int i = Screen.exiledCards.length - 1; i >= 0; i--)
{
if(Screen.exiledCards[i] != null)
{
if(CardHandler.spotLocations[4].contains(e.getPoint()))
{
index = i;
break;
}
}
}
if(index != -1)
{
return new CardInteract(4, index);
}else
{
return null;
}
}
public static void moveCard()
{
int mouseX = (int) MouseInfo.getPointerInfo().getLocation().getX() - Screen.frameX;
int mouseY = (int) MouseInfo.getPointerInfo().getLocation().getY() - Screen.frameY;
switch(interactionCard.getLocation())
{
case 0:
//Transfer a library card to the battlefield for movement.
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] == null)
{
Screen.battlefieldCards[i] = new BattlefieldCard(Screen.libraryCards[interactionCard.getArrayLocation()].getCardName(), Screen.libraryCards[interactionCard.getArrayLocation()].getImage(), mouseX, mouseY, Screen.libraryCards[interactionCard.getArrayLocation()].getRarity(), false);
Screen.libraryCards[interactionCard.getArrayLocation()] = null;
interactionCard = new CardInteract(2, i);
break;
}
}
break;
case 1:
//Transfer a hand card to the battlefield for movement
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] == null)
{
Screen.battlefieldCards[i] = new BattlefieldCard(Screen.handCards[interactionCard.getArrayLocation()].getCardName(), Screen.handCards[interactionCard.getArrayLocation()].getTextureImage(), mouseX, mouseY, Screen.handCards[interactionCard.getArrayLocation()].getRarity(), false);
Screen.handCards[interactionCard.getArrayLocation()] = null;
interactionCard = new CardInteract(2, i);
break;
}
}
break;
case 2:
//Transfer a battlefield card to a battlefield card to bring it to the front and move it
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] == null && i != interactionCard.getArrayLocation() - 1)
{
Screen.battlefieldCards[i] = new BattlefieldCard(Screen.battlefieldCards[interactionCard.getArrayLocation()]);
Screen.battlefieldCards[interactionCard.getArrayLocation()] = null;
interactionCard = new CardInteract(2, i);
break;
}
}
if(!alreadyScanned){
par1Point = new Point(Screen.battlefieldCards[interactionCard.getArrayLocation()].getPosOnCard(mouseX, mouseY));
alreadyScanned = true;
}
Screen.battlefieldCards[interactionCard.getArrayLocation()].setPos((int)(mouseX - par1Point.getX()), (int) (mouseY - par1Point.getY()));
break;
case 3:
//Transfer a graveyard card to the battlefield for movement
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] == null)
{
Screen.battlefieldCards[i] = new BattlefieldCard(Screen.graveyardCards[interactionCard.getArrayLocation()].getCardName(), Screen.graveyardCards[interactionCard.getArrayLocation()].getImage(), mouseX, mouseY, Screen.graveyardCards[interactionCard.getArrayLocation()].getRarity(), false);
Screen.graveyardCards[interactionCard.getArrayLocation()] = null;
interactionCard = new CardInteract(2, i);
break;
}
}
break;
case 4:
//Transfer an exiled card to the battlefield for movement.
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] == null)
{
Screen.battlefieldCards[i] = new BattlefieldCard(Screen.exiledCards[interactionCard.getArrayLocation()].getCardName(), Screen.exiledCards[interactionCard.getArrayLocation()].getImage(), mouseX, mouseY, Screen.exiledCards[interactionCard.getArrayLocation()].getRarity(), false);
Screen.exiledCards[interactionCard.getArrayLocation()] = null;
interactionCard = new CardInteract(2, i);
break;
}
}
break;
case 5:
//Move a token to the front when being moved
BattlefieldCard currentCard = Screen.tokenBattlefield[interactionCard.getArrayLocation()];
Screen.tokenBattlefield[interactionCard.getArrayLocation()] = null;
StackManager.shiftTokenBattlefield();
Screen.tokenBattlefield[Screen.tokenBattlefield.length - 1] = currentCard;
interactionCard = new CardInteract(5, Screen.tokenBattlefield.length - 1);
if(!alreadyScanned){
par1Point = new Point(Screen.tokenBattlefield[interactionCard.getArrayLocation()].getPosOnCard(mouseX, mouseY));
alreadyScanned = true;
}
Screen.tokenBattlefield[interactionCard.getArrayLocation()].setPos((int)(mouseX - par1Point.getX()), (int)(mouseY - par1Point.getY()));
}
}
public static void doDraw(MouseEvent e)
{
CardInteract par1 = checkBattlefieldClicked(e);
CardInteract par2 = checkTokenBattlefieldClicked(e);
if(par1 != null){
if(par1.getLocation() == 2)
{
if(Screen.battlefieldCards[par1.getArrayLocation()].getTapped())
{
Screen.battlefieldCards[par1.getArrayLocation()].setTapped(false);
}else
{
Screen.battlefieldCards[par1.getArrayLocation()].setTapped(true);
}
}
}else if(par2 != null){
if(par2.getLocation() == 5)
{
if(Screen.tokenBattlefield[par2.getArrayLocation()].getTapped())
{
Screen.tokenBattlefield[par2.getArrayLocation()].setTapped(false);
}else
{
Screen.tokenBattlefield[par2.getArrayLocation()].setTapped(true);
}
}
}else{
ButtonHandler.scene2Click(e);
}
}
public static void reshuffle()
{
Random rand = new Random();
LibraryCard[] par1temp = new LibraryCard[Screen.libraryCards.length];
for(int k = 0; k < par1temp.length; k++)
{
par1temp[k] = Screen.libraryCards[k];
}
for(int j = 0; j < Screen.libraryCards.length; j++)
{
Screen.libraryCards[j] = null;
}
for(int i = 0; i < par1temp.length; i++)
{
int par2 = rand.nextInt(Screen.libraryCards.length);
if(par1temp[i] != null)
{
while(Screen.libraryCards[par2] != null)
{
par2 = rand.nextInt(Screen.libraryCards.length);
}
Screen.libraryCards[par2] = par1temp[i];
}
}
}
public static void mullagain(int mNum)
{
for(int i = 0; i < Screen.handCards.length; i++)
{
if(Screen.handCards[i] != null)
{
for(int j = Screen.libraryCards.length - 1; j > 0; j--)
{
if(Screen.libraryCards[j] == null)
{
Screen.libraryCards[j] = new LibraryCard(Screen.handCards[i].getCardName(), Screen.handCards[i].getTextureImage(), Screen.handCards[i].getRarity());
Screen.handCards[i] = null;
break;
}
}
}
}
reshuffle();
for(int i = 1; i < 8 - mNum; i++) StackManager.drawCard();
}
public static void zoom()
{
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
if(zoomCard != null)
{
if(zoomCard.getPlace().equals("battlefield"))
{
Screen.battlefieldCards[zoomCard.getArrayIndex()].setCounterInfo(zoomCard.getCounterInfo());
}
zoomCard = null;
}else{
for(int i = Screen.exiledCards.length - 1; i >= 0; i--)
{
if(Screen.exiledCards[i] != null)
{
if(Screen.exiledCards[i].contains(mousePoint))
{
zoomCard = new ZoomCard(Screen.exiledCards[i].getImage(), "exile", i);
break;
}else {
break;
}
}
}
for(int i = Screen.graveyardCards.length - 1; i >= 0; i--)
{
if(Screen.graveyardCards[i] != null)
{
if(Screen.graveyardCards[i].contains(mousePoint))
{
zoomCard = new ZoomCard(Screen.graveyardCards[i].getImage(), "graveyard", i);
break;
}else {
break;
}
}
}
for(int i = Screen.handCards.length - 1; i >= 0; i--)
{
if(Screen.handCards[i] != null)
{
if(Screen.handCards[i].contains(mousePoint))
{
zoomCard = new ZoomCard(Screen.handCards[i].getTextureImage(), "hand", i);
break;
}
}
}
for(int i = 0; i < Screen.tokenBattlefield.length; i++)
{
if(Screen.tokenBattlefield[i] != null && Screen.tokenBattlefield[i].contains(mousePoint)) zoomCard = new ZoomCard(Screen.tokenBattlefield[i].getImage(), Screen.tokenBattlefield[i].getCounterInfo(), "token", i);
}
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] != null && Screen.battlefieldCards[i].contains(mousePoint)) zoomCard = new ZoomCard(Screen.battlefieldCards[i].getImage(), Screen.battlefieldCards[i].getCounterInfo(), "battlefield", i);
}
}
}
public static void drawZoomCard(Graphics g)
{
if(zoomCard != null)
{
Screen.zoom = true;
g.drawImage(zoomCard.getImage(), (Screen.width / 2) - Screen.cardWidth, (Screen.height / 2) - Screen.cardHeight * 2, Screen.cardWidth * 2, Screen.cardHeight * 2, null);
if(zoomCard.getPlace().equals("battlefield") || zoomCard.getPlace().equals("token")) for(int i = 0; i < counterButtons.length; i++) counterButtons[i].drawButton(g);
}else
{
Screen.zoom = false;
}
}
public static void tapAllLands()
{
for(int i = 0; i < Screen.battlefieldCards.length; i++)
{
if(Screen.battlefieldCards[i] != null && Screen.battlefieldCards[i].getRarity() == 4)
{
Screen.battlefieldCards[i].setTapped(true);
}
}
}
public static void checkCounterButtons(MouseEvent e)
{
int par1 = 9;
for(int i = 0; i < counterButtons.length; i++)
{
if(counterButtons[i].getClicked(e))
{
par1 = i;
}
}
//power/toughness counter
switch(par1)
{
case 0:
zoomCard.getCounterInfo().addPower();
break;
case 1:
zoomCard.getCounterInfo().subPower();
break;
case 2:
zoomCard.getCounterInfo().addToughness();
break;
case 3:
zoomCard.getCounterInfo().subToughness();
break;
case 4:
zoomCard.getCounterInfo().addCounter();
break;
case 5:
zoomCard.getCounterInfo().subCounter();
}
}
} |
Java | UTF-8 | 2,205 | 2.328125 | 2 | [] | no_license | package VerificationItem.java;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import AbstractTest.java.ConnexionWowHead;
import OutilsProjet.java.PageAccueil;
import OutilsProjet.java.PageLardeur;
import OutilsProjet.java.PagePremierResultat;
public class WowHeadTest {
WebDriver driver;
String browser =System.getProperty("browser").toLowerCase().trim();
@Before
public void setupTest() {
if (browser.equals("chrome")) {
// System.setProperty("webdriver.chrome.driver", "C:\\Installation\\driver\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equals("firefox")) {
// System.setProperty("webdriver.chrome.driver", "C:\\Installation\\driver\\geckodriver.exe");
driver = new FirefoxDriver();
} else if (browser.equals("ie")) {
// System.setProperty("webdriver.chrome.driver", "C:\\Installation\\driver\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
}
@Test
public void wowHeadTest () throws InterruptedException {
driver.manage().window().maximize();
driver.get("https://fr.wowhead.com");
System.out.println("---------------------- Acceptation des cookies ------------------------");
//Cliquer sur le bouton continuer du cookie
PageAccueil accueil = PageFactory.initElements(driver, PageAccueil.class);
accueil.acceptCookie();
System.out.println(" ---------------- Accession à la page premier résultat -----------------");
PagePremierResultat pagePremier = accueil.searchElement("Lardeur");
pagePremier.clickOngletPNJ();
System.out.println(" -------------------- Accession à la page lardeur ----------------------");
PageLardeur pageLardeur = pagePremier.clickOnTeteDeMort();
Thread.sleep(6000);
System.out.println(" -------------------- Clique sur la page lardeur ----------------------");
pageLardeur.checkLardeur();
}
@After public void close() {
driver.close();
}
}
|
Markdown | UTF-8 | 23 | 2.53125 | 3 | [] | no_license | # .net
.netapplication
|
Python | UTF-8 | 861 | 2.53125 | 3 | [] | no_license | from models.smiles_vae import VAE, VAETrainer, vae_parser
from models.jtvae import JTVAE, JTVAETrainer, jtvae_parser
class ModelsStorage():
def __init__(self):
self._models = {}
self.add_model('smiles_vae', VAE, VAETrainer, vae_parser)
self.add_model('jtvae', JTVAE, JTVAETrainer, jtvae_parser)
def add_model(self, name, class_, trainer_, parser_):
self._models[name] = {'class': class_,
'trainer': trainer_,
'parser': parser_}
def get_model_names(self):
return list(self._models.keys())
def get_model_trainer(self, name):
return self._models[name]['trainer']
def get_model_class(self, name):
return self._models[name]['class']
def get_model_train_parser(self, name):
return self._models[name]['parser']
|
C# | UTF-8 | 917 | 2.625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace WarehouseManagement.Services
{
public class MNBService
{
ServiceReference.MNBArfolyamServiceSoapClient client = new ServiceReference.MNBArfolyamServiceSoapClient();
public async Task<decimal> GetEuroRate()
{
var ratesResponseBody = await client.GetCurrentExchangeRatesAsync(null);
var resultAsString = ratesResponseBody.GetCurrentExchangeRatesResponse1.GetCurrentExchangeRatesResult;
XDocument xdoc = XDocument.Parse(resultAsString);
var rates = xdoc.Descendants("Rate");
var rate = rates.Where(m => m.Attribute("curr").Value == "EUR").FirstOrDefault().Value;
decimal convertedRate = Convert.ToDecimal(rate.Replace(",", "."));
return convertedRate;
}
}
}
|
JavaScript | UTF-8 | 133 | 2.90625 | 3 | [
"MIT"
] | permissive | // JavaScript Document
var now = new Date();
document.getElementById("now").innerText = (now.getMonth() + 1) + "/" + (now.getDate()); |
Java | UTF-8 | 1,177 | 3.625 | 4 | [] | no_license | package baekjoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
* fibonacci(0) = 0 , fibonacci(1) = 1
* 이후 호출되는 n에 대하여 0과 1을 출력 횟수를 출력하시오
*/
public class Main_B1003_피보나치함수 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int input[] = new int[T];
for (int t = 0; t < T; t++) {
int N = Integer.parseInt(br.readLine());
input[t] = N;
}
for (int i = 0; i < T; i++) {
int N = input[i];
int memo[][] = new int[N+1][2];
fibonacci(N,memo);
System.out.println(memo[N][0] + " " + memo[N][1]);
}
}
private static int[] fibonacci(int n, int[][] memo) {
if(n==0) {
memo[n][0] = 1;
memo[n][1] = 0;
return memo[n];
}
else if(n==1) {
memo[n][1] = 1;
memo[n][0] = 0;
return memo[n];
}else {
if(memo[n][0] > 0 || memo[n][1] > 0) return memo[n];
else {
memo[n][0] = fibonacci(n-1,memo)[0] + fibonacci(n-2,memo)[0];
memo[n][1] = fibonacci(n-1,memo)[1] + fibonacci(n-2,memo)[1];
return memo[n];
}
}
}
}
|
Markdown | UTF-8 | 6,902 | 2.515625 | 3 | [] | no_license | 一五六
何冲道:“但宫内戒备森严,勾魂仙娘又是个极难缠的女人,不如你我里应外合,容易得手。”
鬼偷想了一会,问道:“分宫里可有什么厉害的机关消息吗?”
何冲道:“机关井不可畏,但宫里养着两头异种雪拂,嗅觉极敏,夜间放出陷藏在树上,任是轻功多高的人,也瞒不过雪拂耳目,两头畜牲都有一人高,力大无穷,窜跃又灵活,颇难应付。”
鬼偷邢彬哂笑道:“区区两头畜牲,谅也难不倒老偷儿,咱们还是凭真工夫干吧,犯不上以身试险了。”
何冲道:“水中技艺,小弟或堪使用,陆上丁夫,自知难与邢老哥比拟,反正小弟已经帮不了老哥大忙,何妨去碰碰运气,她许倒能获得方便,助老哥成功。”
鬼偷邢彬道:“你一定要去,老偷儿也不便拦阻,但如因此闹出意外,譬如受到折伤,却不好对帮主交待。”
何冲毅然道:“任何后果,小弟愿一身承当,死亦无憾,决不连累老哥受责就是了。”
鬼偷邢彬无可奈何地道:“好吧!咱们就照你的意思试试,不过,你得答应老偷儿一件事,假如不幸失算,万不可徒逞意气,招致杀身之祸,总须忍耐待机,帮主一到,不难救你脱险二老偷地说句不怕难为情的话,除了手上工夫和轻功尚足自负,要我真刀真枪,只怕救不了你,反把自己也一井断送了。”
何冲大笑起来,于是先将入山途径方向,宫中房舍位置,大略对鬼偷解说一遍,两人才起身步出酒楼。
鬼偷邢彬寻了一家客栈,寄妥马匹,又购备了足够的干粮及应用工具的物件,最后,更买了两壶烈酒,配了几色药物,一切齐全,才随着何冲向城西而来。
两人一前一后,故作不识,何冲仍然乘马,鬼偷却徒步遥遥跟在后面五大开外,尾随而行。
何冲按辔径往城西,直到城门附近一家药材铺前下马,缓步踱进店里,向柜台中伙计道;“有上等的何首乌没有广
伙计微微一怔,忙笑道:“有!客官要多少?”
何冲道:“五百斤。”
伙计更讶,笑道:“要这么多?敢问作什么用途的?”
何冲漫声道:“做引子用。”
伙计笑道:“药引子何须这么多,有五两就足够了,不过,小店的药材全是最上等药材,价钱贵一些,而且现钱现货,谢绝欠账,请客官多原谅。”
何冲微微一笑,取出一样东西递给那伙计,道:“这块银子够了吗?”
伙计低头一看,竞是一面银牌,牌卜镶着“金陵分坛坛主”六个字,脸色顿时变得凝重,恭恭敬敬道:“客官请稍候。”随即匆匆转人店后去了。
鬼偷邢彬远远站在对街阴暗处,凝神倾注,私下不期替何冲捏着一把冷汗。
片刻之后,那伙计含笑而出,侧身道:“请客官后面看看货色!”
何冲略一颔首,昂然迈步走了进去。
穿过两层院落,一间敞厅中笑着迎出一个面貌清瘦的青衣老人,抱拳道:“何坛主来得正好,快请进来,今天真是幸会,先后竟到了两位贵宾。”
何冲认识那青衣老人姓马名文魁,号称“追魂郎中”,正是负责接待第五分宫往来访客的首席护法,论地位,不在分宫宫主之下,连忙拱手肃容道:“属下冒昧,请护法海涵。”
追魂郎中马文魁哈哈笑道:“自家人,千万别客套,请还请不到呢,何坛主试猜一猜老配所说还有一位贵宾是谁?
何冲摇头笑道:“属下哪里猜得到,不知是否总宫有人来厂?”
马文魁抚掌大笑道:“好精明!竟被你一猜就猜中啦!
何冲一面跟随马文魁走进敞厅侧客室,一面却心里忑忐不c,试探着问道:“总宫专使来到,必有要事,但不知来的是哪一位?
马文魁道:“正是有件要事,而目,这事还应在何坛主身上
何冲骇然一震,猛地却步,诧问道:“真的?属下有什么事,值得总宫特派专使赶来?”
马文魁笑道:“瞧你竟急成这样,欲知详情,何不当面一问?快请吧!老朽等着向你贺喜了。”
何冲本已情虚,正欲提聚真力抢先下手,听了最后一句话,不觉又暗暗松下一口气,讶问道:“属下何喜何贺?”
马文魁故作神秘笑道:“天机不可泄漏,且请室中详谈。”说着,笑盈盈亲手掀起客室垂帘,侧身肃客。”
何冲满腹疑云,略一沉吟,便壮胆举步而人,谁知一脚跨进室门,顿时惊噫出声,眼中几乎冒出怒火来……
原来客室中正悠然坐着一个三十岁左右,剑眉朗目,唇红齿白,黄姿奕奕的俊美书生。
那书生身穿一件蜀锦缎的儒衫,神采飞扬,堪称翩翩浊世佳公子,唯一美中不足的是那一双闪烁的眼神,包含着太多的狡猾,邪恶和淫凶。
他,正是曹克武的第四位爱徒,也就是何冲的夺妻仇人“玉面郎君”司马青臣。
仇人见面,价外眼红,何冲怒从心起,几乎就想拔剑出手,狠狠在那色魔身上,戳他几个血淋淋的窟窿。
但理智却告诉他不能轻举妄动,自己的辱妾仇恨同然重要,为卧龙庄上取回刀剑却更为重要,何况身在虎窟,追魂郎中和司马青臣武功都非比寻常,尤其司马青臣可算得是阿儿汗宫有数高手之一,倘若一击不成,自己生死事小,破坏了盗剑计谋,怎能对得起卧龙庄主桑琼?
何冲像貌看似赳赳武失,心思却极缜密,意念电转,终于把满腔怒火强自压抑厂下去,深深吸了一口气,藉着轻噫之声,假作惊喜之色,抢近一步,拱手道:“想不到竞是司马少侠亲莅,贵宾!果然是难得的贵宾……”
随着一阵哈哈大笑,司马青臣也从座椅中站起身米,亲切地拉住何冲手臂,笑道:“何兄!大喜大喜!小弟是奉宫主亲谕,特来向何见贺喜的!”
何冲微怔道:“属下不知喜从何来?”
司马青臣笑道:“龙剑风刀得手,既获千金重赏,又刻日荣升第五分宫副宫主要职,这还不算天大的喜讯么?”
何冲恍然一哦,忙道:“原来为这个,属下只是略尽本份,托宫主洪福,诸位同门鼎助,侥幸得手,怎敢居功?宫主实在褒赐太厚了。”
追魂郎中马文魁哈哈大笑道:“何兄太谦了,若非绝世身手,怎能于强敌云集之际,取得神兵利剑,老朽秃为地主,略备水酒一来替二位接风洗尘,二来为何兄荣升致贺,请人席再慢慢谈吧!”
|
Ruby | UTF-8 | 1,930 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'test_helper'
class RangeOverlapTest < Minitest::Test
def setup
@degree_range = MultiRange.new([0...360])
@empty_range = MultiRange.new([])
@multi_range = MultiRange.new([0..100, 200..300, 500..600])
@float_range = MultiRange.new([1.2..1.5, 1.7..1.8, 3.5..7.2])
end
def test_empty_range
assert_equal false, @empty_range.overlaps?(5..10)
assert_equal false, @empty_range.overlaps?(-999..999)
end
def test_when_full_cover_excluded_range
assert_equal true, @degree_range.overlaps?(50..120)
end
def test_when_right_cover_excluded_range
assert_equal true, @degree_range.overlaps?(-10..20)
end
def test_when_left_cover_excluded_range
assert_equal true, @degree_range.overlaps?(330..400)
end
def test_when_not_cover_excluded_range
assert_equal true, @degree_range.overlaps?(-30..400)
end
def test_when_smaller_and_not_overlap
assert_equal false, @degree_range.overlaps?(-30..-10)
end
def test_when_larger_and_not_overlap
assert_equal false, @degree_range.overlaps?(370..400)
end
def test_multi_range
assert_equal true, @multi_range.overlaps?(50..550)
end
def test_other_multi_range
assert_equal true, @multi_range.overlaps?(MultiRange.new([50..60, 110..120, 180..550, 700]))
end
def test_other_multi_range_and_not_overlap
assert_equal false, @multi_range.overlaps?(MultiRange.new([-10..-5, 105..199, 400, 700..900]))
end
def test_float
assert_equal false, @float_range.overlaps?(1.6..1.65)
assert_equal false, @float_range.overlaps?(1.6..1.69)
assert_equal false, @float_range.overlaps?(1.6...1.7)
assert_equal true, @float_range.overlaps?(1.6..1.7)
assert_equal true, @float_range.overlaps?(1.6..1.71)
val = 1.7 - Float::EPSILON
assert_equal false, @float_range.overlaps?(1.6..val)
assert_equal false, @float_range.overlaps?(1.6...val)
end
end
|
Python | UTF-8 | 245 | 4.03125 | 4 | [] | no_license | # # nested list comprehension (list inside list)
#
# nestedlist=[]
# for i in range(3):
# nestedlist.append([1,2,3])
# print(nestedlist)
#
# # now by list comprehension
# new_list=[[i for i in range(1,4)] for j in range(3)]
# print(new_list) |
Rust | UTF-8 | 1,018 | 3.21875 | 3 | [] | no_license | use cpu::Cpu;
use ops::op::{Matcher, Op};
use std::fmt;
pub struct ReturnFromSubroutine;
impl Op for ReturnFromSubroutine {
fn execute(&self, cpu: Cpu) -> Cpu {
Cpu {
pc: cpu.stack[cpu.sp as usize],
sp: cpu.sp - 1,
..cpu
}
}
}
impl Matcher for ReturnFromSubroutine {
const MASK: u16 = 0x00EE;
fn new(_opcode: u16) -> ReturnFromSubroutine {
ReturnFromSubroutine {}
}
}
impl fmt::Display for ReturnFromSubroutine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RET")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn executes_return_from_subroutine() {
let op = ReturnFromSubroutine::new(0x00EE);
let cpu = Cpu {
stack: [2; 16],
sp: 1,
..Cpu::new()
};
assert_eq!(
Cpu {
pc: 2,
sp: 0,
..cpu
},
op.execute(cpu)
);
}
}
|
C | UTF-8 | 459 | 3.296875 | 3 | [] | no_license | #include "sort.h"
static int compare_Int(void *array, int i1, int i2)
{
int n1 = *((int *) array + i1);
int n2 = *((int *) array + i2);
return (n1 - n2);
}
int main()
{
int a[8] = {0, 4,6,7,5,9,3,8};
int n = 8;
//insertionSort(a, n, sizeof(int), compare_Int);
//bubbleSort(a, n, sizeof(int), compare_Int);
//heapSort(a, n, sizeof(int), compare_Int);
msort(a, 1, 7, compare_Int, sizeof(int));
for(int i = 1; i<n; i++)
printf("%d ", a[i]);
} |
C# | UTF-8 | 1,260 | 2.90625 | 3 | [] | no_license | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ConsoleApp20;
using System.Collections.Generic;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var vo1 = new VirtualObject(new List<int>(), 1, 2);
var vo2 = new VirtualObject(new List<int>(), 1, 2);
Assert.AreEqual(vo1.Equals(vo2), true);
}
[TestMethod]
public void TestMethod2()
{
var p1 = new Box(1, 2, 3);
var p2 = new Box(2, 3, 3);
Assert.AreEqual(p1.Equals(p2), false);
}
[TestMethod]
public void TestMethod3()
{
List<int> numbers = new List<int>() { 1, 2, 3, 45 };
List<int> numbers2 = new List<int>() { 1, 2, 3, 45 };
var numbers3 = numbers;
var p1 = new VirtualObject(numbers, 2, 3);
var p2 = new VirtualObject(numbers, 3, 2);
var p3 = new VirtualObject(numbers3, 2, 3);
Assert.AreEqual(p1.Equals(p2), false);
Assert.AreEqual(p1.Equals(p3), true);
Assert.AreEqual(numbers.Equals(numbers2), false);
}
}
}
|
Ruby | UTF-8 | 2,642 | 3.203125 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | require 'delegate'
module Sass
module Util
# A hash that normalizes its string keys while still allowing you to get back
# to the original keys that were stored. If several different values normalize
# to the same value, whichever is stored last wins.
class NormalizedMap
# Create a normalized map
def initialize(map = nil)
@key_strings = {}
@map = {}
map.each {|key, value| self[key] = value} if map
end
# Specifies how to transform the key.
#
# This can be overridden to create other normalization behaviors.
def normalize(key)
key.tr("-", "_")
end
# Returns the version of `key` as it was stored before
# normalization. If `key` isn't in the map, returns it as it was
# passed in.
#
# @return [String]
def denormalize(key)
@key_strings[normalize(key)] || key
end
# @private
def []=(k, v)
normalized = normalize(k)
@map[normalized] = v
@key_strings[normalized] = k
v
end
# @private
def [](k)
@map[normalize(k)]
end
# @private
def has_key?(k)
@map.has_key?(normalize(k))
end
# @private
def delete(k)
normalized = normalize(k)
@key_strings.delete(normalized)
@map.delete(normalized)
end
# @return [Hash] Hash with the keys as they were stored (before normalization).
def as_stored
Sass::Util.map_keys(@map) {|k| @key_strings[k]}
end
def empty?
@map.empty?
end
def values
@map.values
end
def keys
@map.keys
end
def each
@map.each {|k, v| yield(k, v)}
end
def size
@map.size
end
def to_hash
@map.dup
end
def to_a
@map.to_a
end
def map
@map.map {|k, v| yield(k, v)}
end
def dup
d = super
d.send(:instance_variable_set, "@map", @map.dup)
d
end
def sort_by
@map.sort_by {|k, v| yield k, v}
end
def update(map)
map = map.as_stored if map.is_a?(NormalizedMap)
map.each {|k, v| self[k] = v}
end
def method_missing(method, *args, &block)
if Sass.tests_running
raise ArgumentError.new("The method #{method} must be implemented explicitly")
end
@map.send(method, *args, &block)
end
def respond_to_missing?(method, include_private = false)
@map.respond_to?(method, include_private)
end
end
end
end
|
Python | UTF-8 | 415 | 3.03125 | 3 | [] | no_license | from tkinter import *
top = Tk()
top.geometry("200x200")
top.title("pack widget")
redbutton = Button(top, text='Red', fg='red')
redbutton.pack(side=LEFT)
greenbutton = Button(top, text='Green', fg='green')
greenbutton.pack(side=RIGHT)
blackbutton = Button(top, text='Black', fg='Black')
blackbutton.pack(side=TOP)
bluebutton = Button(top, text='Blue', fg='blue')
bluebutton.pack(side=BOTTOM)
top.mainloop() |
Python | UTF-8 | 822 | 3.515625 | 4 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env/python3
def iterate_revert_string(s: list) -> list:
"""
revert list iterate method
"""
i = 0
j = len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return s
def recursion_revert_string(s: list) -> list:
"""
revert list elements recursion method
"""
if len(s) == 0:
return []
return [s.pop()] + recursion_revert_string(s)
if __name__ == "__main__":
t1 = ["f", "e", "d", "u", "s", "i", "a"]
t2 = ["0", "q", " ", "1", "\\"]
assert iterate_revert_string(t1), ["a", "i", "s", "u", "d", "e", "f"]
assert recursion_revert_string(t1), ["a", "i", "s", "u", "d", "e", "f"]
assert iterate_revert_string(t2), ["\\", "1", " ", "q", "0"]
assert recursion_revert_string(t2), ["\\", "1", " ", "q", "0"]
|
Markdown | UTF-8 | 11,315 | 3.140625 | 3 | [] | no_license | # Command iptables
# MỤC LỤC
- [1.Cú pháp](#1)
- [2.Command](#2)
- [3.Matches](#3)
- [3.1.Generic matches](#3.1)
- [3.2.Implicit matches](#3.2)
- [3.2.1.TCP matches](#3.2.1)
- [3.2.2.UDP matches](#3.2.2)
- [3.2.3.ICMP matches](#3.2.3)
<a name="1"></a>
# 1.Cú pháp
```
iptables [-t table] command [chain] [match] [target/jump]
```
\- Thứ tự các tham số có thể thay đổi nhưng cú pháp trên là dễ hiểu nhất.
\- Nếu không chỉ định `table`, mặc định sẽ là table filter.
\- `command` sẽ chỉ định chương trình phải làm gì.
VD: Insert rule hoặc thêm rule đến cuối của chains.
\- `chain` phải phù hợp với `table` được chỉ định.
\- `match` là phần của rule mà chúng ta gửi cho kernel để biết chi tiết cụ thể của gói tin, điều gì làm cho nó khác với các gói tin khác.
VD: địa chỉ IP, port, giao thức hoặc bất cứ điều gì.
\- Cuối cùng là `target` của gói tin. Nếu phù hợp với match, chúng tôi sẽ vói với kernel phải làm những gì với gói tin này.
<a name="2"></a>
# 2.Command
\- command nói cho iptables biết phải làm gì với phần còn lại của rule. Thông thường chúng ta muốn thêm hoặc xóa 1 cái gì đó trong bảng. Các command sau có sẵn trong iptables.
\- **command**
|Command|Ví dụ|Ý nghĩa|
|---|---|---|
|-A, --append|iptables -A INPUT|thêm rule vào cuối của chains.|
|-D, --delete|iptables -D INPUT --dport 80 -j DROP **hoặc** iptables -D INPUT 1|xóa rule của chain. Điều này có thể được thực hiện theo 2 cách; bằng cách nhập cả rule để khớp (như trong vd đầu tiên), hoặc bằng cách chỉ định số thứ tự của rule mà bạn muốn xóa. Các rules được đánh số từ đầu đến cuối đối với mỗ chain, bắt đầu với số thứ tự 1.|
|-R, --replace|iptables -R INPUT 1 -s 192.168.0.1 -j DROP|thay thế rule cũ tại dòng chỉ định. Nó sẽ làm việc tương tự như câu lệnh --delete, nhưng thay vì xóa, nó sẽ thay thế nó bằng mục nhập mới.|
|-I, --insert|iptables -I INPUT 1 --dport 80 -j ACCEPT|Insert rule vào chain. Rule được insert vào như rule đầu tiên. Nói cách khác, trong ví dụ trên, rule sẽ được chèn vào làm rule 1 trong chain INPUT.|
|-L, --list|iptables -L INPUT|Liệt kê tất cả các rules trong chain chỉ định. Nếu không chỉ định chain, nó sẽ liệt kê tất cả các chain trong table. Đầu ra phụ thuộc bởi các tùy chọn khác như tùy chọn -n và -v, …|
|-F, --flush|iptables -F INPUT|xóa tất cả các rule trong chain chỉ định trong bảng chỉ định.|
|-Z, --zero|iptables -Z INPUT|This command tells the program to zero all counters in a specific chain, or in all chains.|
|-N, --new-chain|iptables -N allowed|Câu lệnh nói với kernel tạo chain mới với tên được chỉ định trong table chỉ định. Trong ví dụ trên, chúng ta tạo chain được gọi là allowed. Tên của chain mới không được giống tên của chain và target đã tồn tại.|
|-X, --delete chain|iptables -X allowed|Xóa chain được chỉ định từ tables. Bạn phải xóa tất cả các rule của chain trước khi xóa chain. Nếu lệnh này sử dụng với không tùy chọn, tất cả các chains được xây dựng sẽ bị xóa.|
|-P, --policy|iptables -P INPUT DROP|Câu lệnh nói với kernel để thiết lập target mặc định, hoặc policy của chain. Tất cả các gói tin không phù hợp với bất kỳ rule nào sẽ bị buộc phải sử dụng policy của chain. Target thường là DROP hoặc ACCEPT.|
|-E, --rename-chain|iptables -E allowed disallowed|Câu lệnh nói với iptables rằng cần thay đổi tên của chain. VD trên, tên chain được thay đổi từ **allowed** đến **disallowed**. Chú ý: Điều này sẽ không ảnh hướng đến phương thức thực tế của tables sẽ làm việc.|
\- **Option**
|Option|các command được sử dụng với|Ý nghĩa|
|---|---|---|
|-v, --verbose|--list, --append, --insert, --delete, --replace|- Lệnh thường được sử dụng với tùy chọn **--list**. Nếu được sử dụng với tùy chọn **--list**, output sẽ là các địa chỉ interface, tùy chọn của rule và TOS masks. Lệnh **--list** cũng bao gồm bộ đếm bytes và gói tin cho mỗi rule, nếu tùy chọn **--verbose** được thiết lập. Bộ đếm sử dụng hệ số nhân K (x1000), M(x1000.000) và G (x1000.000.000). Để nhận kết quả chính xác bạn có thể sử dụng tùy chọn **-x**.|
|-x, --exact|--list|Output từ lệnh **--list** sẽ không chứa hệ số nhân K, M hoặc G. Thay vào đó, chúng ta sẽ nhận được kết quả chính xác từ các gói tin và bytes.|
|-n, --numeric|--list|Tùy chọn nói với iptables rằng đầu ra các giá trị số. Địa chỉ IP và số port sẽ được in ra sử dụng giá trị số và không sử dụng hostname, tên network hoặc tên tên ứng dụng.|
|--line-numbers|--list|Được sử dụng để đầu ra bao gồm số thứ tự dòng.|
|-c, --set-counters|--insert, --append, --replace||
|--modprobe|All||
<a name="3"></a>
# 3.Matches
<a name="3.1"></a>
## 3.1.Generic matches
|Math|Ví dụ|Ý nghĩa|
|---|---|---|
|-p, --protocol|iptables -A INPUT -p tcp|math này được sử dụng để kiểm tra giao thức. VD của protocols là TCP, UDP và ICMP. Giao thức phải là 1 trong các chỉ định TCP, UDP và ICMP. Nó cũng có thể là các giá trị được chỉ định trong file `/etc/protocols`. VD: giao thức ICP là giá trị 1, TCP là 6 và UDP là 17. Nó cũng có thể lấy giá trị **ALL**, **ALL** có nghĩa là nó phù hợp TCP, UDP và ICMP. lệnh này cũng có thể lấy 1 danh sách các giao thức được phân cách bởi dấu phẩy, như **udp,tcp**. math có thể sử dụng kí tự !. VD: --protocol ! tcp có nghĩa là để phù hợp với UDP và ICMP.|
|-s, --src, --source|iptables -A INPUT -s 192.168.1.1|Đây là so sánh nguồn, dựa trên địa chỉ IP nguồn. Nó có thể được sử dụng để so sánh 1 địa chỉ IP hoặc 1 dải địa chỉ IP. VD về 1 địa chỉ IP : 192.168.1.1 . VD về 1 dải địa chỉ IP: 192.168.0.0/24 hoặc 192.168.0.0/255.255.255.0. VD về số sánh đảo ngược: --source ! 192.168.0.0/24 , sẽ so sánh tất cả các gói tin với địa chỉ IP nguồn không đến từ dải 192.168.0.x.|
|-d, --dst, --destination|iptables -A INPUT -d 192.168.1.1|Đây là so sánh đích, dựa trên địa chỉ IP đích. Nó có thể được sử dụng để so sánh 1 địa chỉ IP hoặc 1 dải địa chỉ IP. VD về 1 địa chỉ IP : 192.168.1.1 . VD về 1 dải địa chỉ IP: 192.168.0.0/24 hoặc 192.168.0.0/255.255.255.0. VD về số sánh đảo ngược: --destination ! 192.168.0.1 , sẽ so sánh tất cả các gói tin với địa chỉ IP đích không phải 192.168.0.1.|
|-i, --in-interface|iptables -A INPUT -i eth0|So sánh này được sử dụng cho interface gói tin đến. Tùy chọn này chỉ sử dụng cho các chain INPUT, FORWARD và PREROUTING. Nếu interface không được chỉ định, nó sử giả trị giá trị là dấu +. Dấu + được sử dụng để khớp với với 1 chuỗi chữ cái và số, điều này có nghĩa là chấp nhất tất cả các gói tin mà xem xét nó đến interface nào. Dấu + cũng có thể được nối vào interface, **eth0+** sẽ là tất các thiết bị Ethernet. Chúng ta có thể đảo ngược ý nghĩa của tùy chọn với dấu !. VD: -i ! eth0 sẽ phù hợp với tất cả gói tin đến từ các interface, ngoại trừ eth0.|
|-o, --out-interface|iptables -A FORWARD -o eth0|So sánh này được sử dụng cho interface gói tin rời đi. Tùy chọn này chỉ sử dụng cho các chain OUTPUT, FORWARD và POSTROUTING. Nếu interface không được chỉ định, nó sử giả trị giá trị là dấu +. Dấu + được sử dụng để khớp với với 1 chuỗi chữ cái và số, điều này có nghĩa là chấp nhất tất cả các gói tin mà xem xét nó rời đi từ interface nào. Dấu + cũng có thể được nối vào interface, **eth0+** sẽ là tất các thiết bị eth. Chúng ta có thể đảo ngược ý nghĩa của tùy chọn với dấu !. VD: -i ! eth0 sẽ phù hợp với tất cả gói tin rời đi từ các interface, ngoại trừ eth0.|
|-f, --fragment|iptables -A INPUT -f||
<a name="3.2"></a>
## 3.2.Implicit matches
<a name="3.2.1"></a>
### 3.2.1.TCP matches
|Match|Ví dụ|Ý nghĩa|
|---|---|---|
|--sport, --source-port|iptables -A INPUT -p tcp --sport 22|So sánh **--source-port** được sử dụng để só sánh sựa trên port nguồn. Math này có thể lấy tên dịch vụ hoặc số port. Nếu bạn chỉ định tên dịch vụ, tên dịch vụ phải trong file `/etc/services`, **iptables** sẽ sử dụng file này để tìm. Nếu chỉ định port bởi số, rule sẽ tải nhanh hơn, **iptables** không phải kiểm tra tên dịch vụ. Bạn có thể sử dụng **--source-port** để chị định 1 dải **ports**, **--source-port 22:80**. Nếu bạn không chỉ định port đầu, mặc định sẽ là port 0, **--source-port :80** sẽ là port từ 0 -> 80. Nếu không chỉ định port cuối, mặc định sẽ là port là 65535, **--source-port 22:**. Nếu bạn viết **--source-port 80:22**, nó tương đường với **--source-port 22:80**. Bạn có thể đảo ngược so sánh bằng cách thêm dấu !. VD: **--source-port ! 22** nghĩa là tất cả các ports nhưng không phải port 22. hoặc **--source-port ! 22:80**|
|--dport, --destination-port|iptables -A INPUT -p tcp --dport 22|math này được sử dụng cho gói tin TCP, theo port đích. Cú pháp tương tự **--source-port**|
|--tcp-flags|iptables -p tcp --tcp-flags SYN,FIN,ACK SYN||
|--tcp-option|iptables -p tcp --tcp-option 16||
<a name="3.2.2"></a>
### 3.2.2.UDP matches
|Math|Ví dụ|Ý nghĩa|
|---|---|---|
|--sport, --source-port|iptables -A INPUT -p udp --sport 53|tương tự như TCP|
|--dport, --destination-port|iptables -A INPUT -p udp --dport 53|tương tự như TCP|
<a name="3.2.3"></a>
### 3.2.3.ICMP matches
\- Xem ICMP types tại: http://www.faqs.org/docs/iptables/icmptypes.html
\-
|Math|Ví dụ|Ý nghĩa|
|---|---|---|
|--icmp-type|iptables -A INPUT -p icmp --icmp-type 8|Math này được sử dụng để chỉ ICMP type phù hợp. ICMP type có thể được xác định bằng giá trị số hoặc tên của chúng. Giá trị số được chỉ định trong RFC 792. Để xem danh sách các gái trị tên ICMP, thực hiện lệnh **iptables --protocol icmp --help**. Match này có thể được đảo ngược với dấu **!**, **--icmp-type ! 8**. Lưu ý: 1 số ICMP type đã lỗi thời.|
|
JavaScript | UTF-8 | 4,828 | 2.546875 | 3 | [] | no_license | //----dependencias------
'use strict'
const bcrypt = require("bcryptjs");
const Caracteristica = require('../models/caracteristica');
exports.findCaracteristicas = (req,res) => {
Caracteristica.where({estatus:'A'||'a'}).fetchAll()
.then(function(data){
res.status(200).json({ error : false, data : data.toJSON() });
})
.catch(function (err) {
res.status(500).json({ error: true, data: {message: err.message} });
});
}
exports.createCaracteristica = (req,res) => {
let newData = {
nombre: req.body.nombre,
descripcion: req.body.descripcion,
caracteristica_base_id: req.body.caracteristica_base_id,
estatus: 'A'
}
Caracteristica.forge(newData).save()
.then(function(data){
res.status(200).json({ error: false, data: { message: 'caracteristica creada' } });
})
.catch(function (err) {
res.status(500).json({ error: true, data: {message: err.message} });
});
}
exports.findOneCaracteristica = (req,res) => {
let conditions = { id: req.params.id };
Caracteristica.forge(conditions).fetch()
.then(function(data){
if(!data) return res.status(404).json({ error : true, data : { message : 'caracteristica no existe' } });
res.status(200).json({ error : false, data : data.toJSON() })
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} })
})
}
exports.findOneCaracteristicaByBase = (req,res) => {
let conditions = { caracteristica_base_id: req.params.caracteristica_base_id };
Caracteristica.where(conditions).fetchAll()
.then(function(data){
if(!data) return res.status(404).json({ error : true, data : { message : 'caracteristica no existe' } });
res.status(200).json({ error : false, data : data.toJSON() })
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} })
})
}
exports.updateCaracteristica = (req,res) => {
let conditions = { id: req.params.id };
Caracteristica.forge(conditions).fetch()
.then(function(caracteristica){
if(!caracteristica) return res.status(404).json({ error : true, data : { message : 'caracteristica no existe' } });
caracteristica.save(req.body)
.then(function(data){
res.status(200).json({ error : false, data : { message : 'caracteristica actualizada'} });
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} });
})
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} })
})
}
exports.cambiarEstatus = (req,res) => {
let conditions = { id: req.params.id };
Caracteristica.forge(conditions).fetch()
.then(function(caracteristica){
if(!caracteristica) return res.status(404).json({ error : true, data : { message : ' caracteristica no existe' } });
caracteristica.save({estatus:req.body.estatus})
.then(function(data){
res.status(200).json({ error : false, data : { message : 'estatus del tipo de la caractertica actualizado'} });
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} });
})
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} })
})
}
exports.deleteCaracteristica = (req,res) => {
let conditions = { id: req.params.id };
Caracteristica.forge(conditions).fetch()
.then(function(caracteristica){
if(!caracteristica) return res.status(404).json({ error : true, data : { message : 'caracteristica no existe' } });
caracteristica.save({estatus:'I'})
.then(function(data){
res.status(200).json({ error : false, data : {message : 'caracteristica eliminado'} })
})
.catch(function(err){
res.status(500).json({error : true, data : {message : err.message}});
})
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} })
})
}
exports.borrarCaracteristica = (req,res) => {
let conditions = { id: req.params.id };
Caracteristica.forge(conditions).fetch()
.then(function(caracteristica){
if(!caracteristica) return res.status(404).json({ error : true, data : { message : 'caracteristica no existe' } });
caracteristica.destroy()
.then(function(data){
res.status(200).json({ error : false, data : {message : 'caracteristica eliminado'} })
})
.catch(function(err){
res.status(500).json({error : true, data : {message : err.message}});
})
})
.catch(function(err){
res.status(500).json({ error : false, data : {message : err.message} })
})
} |
Java | UTF-8 | 201 | 1.617188 | 2 | [] | no_license | package test_01;
import java.util.List;
/**
* @author dshvedchenko on 6/3/16.
*/
public interface PStates {
List<String> getStatesList();
String getMessages();
TrickyBean getTB();
}
|
Python | UTF-8 | 9,143 | 3.125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 23 11:03:10 2017
@author: akash.a
"""
import numpy as np
from scipy import stats
from past.builtins import xrange
class KNearestNeighbor(object):
""" a kNN classifier with L2 distance """
def __init__(self):
pass
def train(self, X, y):
self.X_train = X
self.y_train = y
print('Done')
def predict(self, X, k=1, num_loops=0):
if num_loops == 0:
dists = self.compute_distances_no_loops(X)
elif num_loops == 1:
dists = self.compute_distances_one_loop(X)
elif num_loops == 2:
dists = self.compute_distances_two_loops(X)
else:
raise ValueError('Invalid value %d for num_loops' % num_loops)
return self.predict_labels(dists, k=k)
def compute_distances_two_loops(self, X):
num_test = X.shape[0]
num_train = self.X_train.shape[0]
dists = np.zeros((num_test, num_train))
for i in xrange(num_test):
for j in xrange(num_train):
dists[i,j] = sum((X[i]-self.X_train[j])*(X[i]-self.X_train[j]))
return dists
def compute_distances_one_loop(self, X):
num_test = X.shape[0]
num_train = self.X_train.shape[0]
dists = np.zeros((num_test, num_train))
for i in xrange(num_test):
dists[i,:] = ((self.X_train-X[i])*(self.X_train-X[i])).sum(axis=1)
return dists
def compute_distances_no_loops(self, X):
a = self.X_train
b = X
mult_term = np.dot(b,np.transpose(a))
x_term = np.dot(np.zeros((b.shape[0],1))+1, np.reshape((a*a).sum(axis=1),(1,a.shape[0])))
y_term = np.dot(np.reshape((b*b).sum(axis=1),(b.shape[0],1)), np.zeros((1,a.shape[0]))+1)
return (x_term + y_term -2*mult_term)
def predict_labels(self, dists, k=1):
"""
Given a matrix of distances between test points and training points,
predict a label for each test point.
Inputs:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
gives the distance betwen the ith test point and the jth training point.
Returns:
- y: A numpy array of shape (num_test,) containing predicted labels for the
test data, where y[i] is the predicted label for the test point X[i].
"""
num_test = dists.shape[0]
y_pred = np.zeros(num_test)
for i in xrange(num_test):
# A list of length k storing the labels of the k nearest neighbors to
# the ith test point.
idx = np.argpartition(dists[i],k)
closest_y = self.y_train[idx[:k]]
y_pred[i] = stats.mode(closest_y)[0][0]
return y_pred
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
from __future__ import print_function
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Load the raw CIFAR-10 data.
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# As a sanity check, we print out the size of the training and test data.
print('Training data shape: ', X_train.shape)
print('Training labels shape: ', y_train.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
num_classes = len(classes)
samples_per_class = 7
for y, cls in enumerate(classes):
idxs = np.flatnonzero(y_train == y)
idxs = np.random.choice(idxs, samples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
plt.subplot(samples_per_class, num_classes, plt_idx)
plt.imshow(X_train[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls)
plt.show()
# Subsample the data for more efficient code execution in this exercise
num_training = 5000
mask = list(range(num_training))
X_train = X_train[mask]
y_train = y_train[mask]
num_test = 500
mask = list(range(num_test))
X_test = X_test[mask]
y_test = y_test[mask]
# Reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
print(X_train.shape, X_test.shape)
############################################################
#import cs231n.classifiers.k_nearest_neighbor
classifier = KNearestNeighbor()
classifier.train(X_train, y_train)
# Open cs231n/classifiers/k_nearest_neighbor.py and implement
# compute_distances_two_loops.
# Test your implementation:
dists = classifier.compute_distances_two_loops(X_test)
print(dists.shape)
# We can visualize the distance matrix: each row is a single test example and
# its distances to training examples
plt.imshow(dists, interpolation='none')
plt.show()
# Now implement the function predict_labels and run the code below:
# We use k = 1 (which is Nearest Neighbor).
y_test_pred = classifier.predict_labels(dists, k=1)
# Compute and print the fraction of correctly predicted examples
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))
y_test_pred = classifier.predict_labels(dists, k=5)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))
dists1 = classifier.compute_distances_one_loop(X_test)
difference = np.linalg.norm(dists - dists1, ord='fro')
print('Difference was: %f' % (difference, ))
if difference < 0.001:
print('Good! The distance matrices are the same')
else:
print('Uh-oh! The distance matrices are different')
difference = np.linalg.norm(dists - dists2, ord='fro')
print('Difference was: %f' % (difference, ))
if difference < 0.001:
print('Good! The distance matrices are the same')
else:
print('Uh-oh! The distance matrices are different')
# Let's compare how fast the implementations are
def time_function(f, *args):
"""
Call a function f with args and return the time (in seconds) that it took to execute.
"""
import time
tic = time.time()
f(*args)
toc = time.time()
return toc - tic
two_loop_time = time_function(classifier.compute_distances_two_loops, X_test)
print('Two loop version took %f seconds' % two_loop_time)
one_loop_time = time_function(classifier.compute_distances_one_loop, X_test)
print('One loop version took %f seconds' % one_loop_time)
no_loop_time = time_function(classifier.compute_distances_no_loops, X_test)
print('No loop version took %f seconds' % no_loop_time)
num_folds = 5
k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]
X_train_folds = np.array_split(X_train, num_folds)
y_train_folds = np.array_split(y_train, num_folds)
# A dictionary holding the accuracies for different values of k that we find
# when running cross-validation. After running cross-validation,
# k_to_accuracies[k] should be a list of length num_folds giving the different
# accuracy values that we found when using that value of k.
k_to_accuracies = {}
for k in k_choices:
accuracy_k = range(num_folds)
for fold in range(num_folds):
test_x = X_train_folds[fold]
test_y = y_train_folds[fold]
train_indices = range(num_folds)
train_indices.remove(fold)
train_x = np.empty((0,X_train.shape[1]))
train_y = []
for i in train_indices:
train_x = np.append(train_x, X_train_folds[i], axis=0)
train_y = np.append(train_y,y_train_folds[i])
classifier.train(train_x, train_y)
dists = classifier.compute_distances_no_loops(test_x)
y_test_pred = classifier.predict_labels(dists, k)
num_correct = np.sum(y_test_pred == test_y)
accuracy_k[fold] = float(num_correct) / num_test
print(accuracy_k)
k_to_accuracies[k] = accuracy_k
# Print out the computed accuracies
for k in sorted(k_to_accuracies):
for accuracy in k_to_accuracies[k]:
print('k = %d, accuracy = %f' % (k, accuracy))
# plot the raw observations
for k in k_choices:
accuracies = k_to_accuracies[k]
plt.scatter([k] * len(accuracies), accuracies)
# plot the trend line with error bars that correspond to standard deviation
accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])
accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])
plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)
plt.title('Cross-validation on k')
plt.xlabel('k')
plt.ylabel('Cross-validation accuracy')
plt.show()
best_k = 10
classifier = KNearestNeighbor()
classifier.train(X_train, y_train)
y_test_pred = classifier.predict(X_test, k=best_k)
# Compute and display the accuracy
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy)) |
C# | UTF-8 | 2,981 | 2.59375 | 3 | [] | no_license | using BL.Base;
using BL.ViewModels;
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BL.AppServices
{
public class ProductAppService : BaseAppService
{
public IEnumerable<Product> GetAll()
{
List<Product> products = TheUnitOfWork.Product.GetAllProducts().ToList();
return products;
}
public Product GetById(int id)
{
return TheUnitOfWork.Product.GetById(id);
}
public void Insert(AddProductVM ProductViewModel)
{
var product = Mapper.Map<Product>(ProductViewModel);
TheUnitOfWork.Product.Insert(product);
TheUnitOfWork.Commit();
}
public bool Update(AddProductVM ProductViewModel)
{
var product = Mapper.Map<Product>(ProductViewModel);
TheUnitOfWork.Product.Update(product);
TheUnitOfWork.Commit();
return true;
}
public bool Delete(int id)
{
bool result = false;
TheUnitOfWork.Product.Delete(id);
result = TheUnitOfWork.Commit() > new int();
return result;
}
public bool CheckExists(AddProductVM productViewModel)
{
var product = Mapper.Map<Product>(productViewModel);
return TheUnitOfWork.Product.GetAny(c => c.ID == product.ID);
}
internal void DecreaseQuantity(int Id, int quantity)
{
Product product = GetById(Id);
product.Quantity -= quantity;
TheUnitOfWork.Commit();
}
public bool AssignColorToProduct(Product product, int colorId)
{
Color color = TheUnitOfWork.Color.GetById(colorId);
TheUnitOfWork.Product.AssignColorToProduct(product, color);
return TheUnitOfWork.Commit() > new int();
}
public IEnumerable<Product> GetProductsByColor(int colorId)
{
return TheUnitOfWork.Product.GetProductsByColor(colorId).ToList();
}
public IEnumerable<Product> GetProductsByCategory(int categoryId)
{
return TheUnitOfWork.Product.GetProductsByCategory(categoryId).ToList();
}
public IEnumerable<Product> GetLastProducts(int number = 0)
{
return TheUnitOfWork.Product.GetLastProducts(number).ToList();
}
public void addOrderDetails(int productId, int orderDetailsId)
{
Product product = GetById(productId);
OrderDetails orderDetails = TheUnitOfWork.OrderDetails.GetById(orderDetailsId);
TheUnitOfWork.Product.addOrderDetails(product, orderDetails);
TheUnitOfWork.Commit();
}
public IEnumerable<Product> searchByName(string name)
{
return TheUnitOfWork.Product.GetProductsByName(name).ToList();
}
}
}
|
Markdown | UTF-8 | 1,433 | 2.75 | 3 | [] | no_license | # Summit Software Notes
## Introduction
The goal of the Summit Software INSPIRE is to provide a consistent software stack
for BIP178 project members. Note however, we are not an authoritarian project and you can
use whatever software you desire.
## First steps
Run the following command:
** source /gpfs/alpine/proj-shared/bip178/Inspire_Project_Software/bin/summit_inspire_environmental_variables.sh **
This will set two key environmental variables and modify your module file path to make the
Summit INSPIRE binaries available. The 2 key environmental variables are
* INSPIRE_TARGET_MACHINE
* INSPIRE_PROJECT_SOFTWARE_TOP_LEVEL
## Loading Software
One should now be able to load the Summit INSPIRE software. Do the following command to see what
is available
** module avail Summit **
### Core Software Stack
The core software sets the environment for the gcc compiler, swig, python, and other software
to build and run in an consistent environment.
To load the core software stack do
** module load Summit/inspire_project_environment **
This command need only be done once.
### Production Software
To load a production software load the core software module then load the desired module. For
example to load AutoDock Vina do the following
** module load Summit/inspire_project_environment **
** module load Summit/autodock_vina/1.1.2 **
Recall that one need only to load the core software stack once. |
Python | UTF-8 | 105 | 2.65625 | 3 | [] | no_license | __author__ = 'Wangj1'
# Written by Junlin Wang
import mathhelp
a, b = mathhelp.getPrimes(2000000)
print sum(a) |
SQL | UTF-8 | 694 | 3.34375 | 3 | [] | no_license | create database aluno;
create database if not exists ofiSys;
drop database if exists ofiSys;
use ofiSys;
drop table Veiculo;
drop table Cliente;
drop table Servico;
select * from Veiculo;
select * from Cliente;
select * from Servico;
describe Veiculo;
describe Cliente;
describe Servico;
create table if not exists Cliente(
id mediumint primary key not null auto_increment,
nome varchar(100) not null
);
create table if not exists Veiculo(
id mediumint primary key not null auto_increment,
marca varchar(100) not null,
modelo varchar(100) not null,
ano int(4),
placa varchar(7),
km int (10),
proprietario_Id mediumint,
foreign key(proprietario_ID) references Cliente(id)
);
|
C# | UTF-8 | 18,588 | 3.203125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentManagement
{
class Manage : TakeInput
{
//Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\StudentDB.mdf;Integrated Security=True
public String connectionString = "Data Source=NIHARIKA;Initial Catalog=StudentDB;Integrated Security=True";
//public String connectionString = StudentManagement.Properties.Settings.Default.StudentDBConnectionString;
/**********************************************************************************
* Main menu *
*********************************************************************************/
public void main_menu()
{
// Main Menu
Console.WriteLine("\nEnter your command:"
+ "\n\t1 > Manage student"
+ "\n\t2 > Manage course"
+ "\n\t3 > Manage registration"
+ "\n\t0 > Exit program"
);
// To the next level of menu
int number = user_choice();
bool condition = true;
while(condition)
{
switch (number)
{
case 0:
Environment.Exit(number);
condition = false;
break;
case 1:
// Student menu complete
student_menu();
break;
case 2:
course_menu();
break;
case 3:
registration_menu();
break;
}
}
}
/**********************************************************************************
* Student menu *
*********************************************************************************/
private void student_menu()
{
Console.WriteLine("\n[1] Managing students:"
+ "\n\t1 > New student"
//+ "\n\t2 > Edit student (Does not work)"
+ "\n\t3 > Delete student"
+ "\n\t4 > Print student list"
+ "\n\t0 > Back to main menu"
);
Action new_student = () =>
{
// Take user input
String StudentID = prompt("Enter new student ID");
String StudentName = prompt("Enter new student name");
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "INSERT INTO Students "
+ "(StudentID,StudentName)"
+ "VALUES (@StudentID, @StudentName)";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@StudentID", SqlDbType.NChar, 10);
param1.Value = StudentID;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@StudentName", SqlDbType.NChar, 50);
param2.Value = StudentName;
command.Parameters.Add(param2);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("New student information added");
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
/*
Action edit_student = () =>
{
// Take user input
String StudentID = prompt("Enter student ID");
Console.WriteLine("Are you sure to overwrite?? ");
if ("N" == Console.ReadLine() || "n" == Console.ReadLine())
{
Console.WriteLine("Action cancelled.");
return;
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
String StudentName = prompt("New Name");
String sql = "Update Students "
+ "SET StudentName = @StudentName"
+ "WHERE StudentID = @StudentID";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@StudentName", SqlDbType.NChar, 50);
param1.Value = StudentID;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@StudentID", SqlDbType.NChar, 10);
param2.Value = StudentID;
command.Parameters.Add(param2);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("Student information deleted.");
connection.Close();
Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
*/
Action delete_student = () =>
{
// Take user input
String StudentID = prompt("Enter student ID");
Console.WriteLine("Are you sure to delete? ") ;
if("N" == Console.ReadLine() || "n" == Console.ReadLine()){
Console.WriteLine("Action cancelled.");
return;
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "DELETE FROM Students "
+ "WHERE StudentID = @StudentID";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@StudentID", SqlDbType.NChar, 10);
param1.Value = StudentID;
command.Parameters.Add(param1);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("Student information deleted.");
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
Action show_student = () =>
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "select * from Students";
SqlCommand command = new SqlCommand(sql, connection);
try
{
connection.Open();
Console.WriteLine("Student list: ");
SqlDataReader reader = command.ExecuteReader();
Console.WriteLine("\n\tStudent ID\tStudent Name");
while (reader.Read())
{
Console.WriteLine("\t" + reader["StudentID"].ToString() + "\t" + reader["StudentName"].ToString());
}
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
// To the next level of menu
int number = user_choice();
switch (number)
{
case 0:
main_menu();
break;
case 1:
new_student();
break;
/*
case 2:
edit_student();
break;
*/
case 3:
delete_student();
break;
case 4:
show_student();
break;
}
}
/**********************************************************************************
* Courses menu *
* *******************************************************************************/
private void course_menu()
{
Console.WriteLine("\n[2] Managing courses:"
+ "\n\t1 > New course"
//+ "\n\t2 > Edit course (Does not work)"
+ "\n\t3 > Delete course"
+ "\n\t4 > Print course list"
+ "\n\t0 > Back to main meny"
);
Action new_course = () =>
{
// Take user input
String CourseID = prompt("Enter new course ID");
String CourseName = prompt("Enter new course name");
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "INSERT INTO Courses "
+ "(CourseID,CourseName)"
+ "VALUES (@CourseID, @CourseName)";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@CourseID", SqlDbType.NChar, 10);
param1.Value = CourseID;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@CourseName", SqlDbType.NChar, 50);
param2.Value = CourseName;
command.Parameters.Add(param2);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("New course information added");
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
/*
Action edit_course = () =>
{
// Take user input
String CourseID = prompt("Enter course ID");
Console.WriteLine("Are you sure to overwrite?? ");
if ("N" == Console.ReadLine() || "n" == Console.ReadLine())
{
Console.WriteLine("Action cancelled.");
return;
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
String CourseName = prompt("New Name");
String sql = "Update Courses "
+ "SET CourseName = @CourseName"
+ "WHERE CourseID = @CourseID";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@CourseName", SqlDbType.NChar, 50);
param1.Value = CourseID;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@CourseID", SqlDbType.NChar, 10);
param2.Value = CourseID;
command.Parameters.Add(param2);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("Course information deleted.");
connection.Close();
Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
*/
Action delete_course = () =>
{
// Take user input
String CourseID = prompt("Enter course ID");
Console.WriteLine("Are you sure to delete? ") ;
if("N" == Console.ReadLine() || "n" == Console.ReadLine()){
Console.WriteLine("Action cancelled.");
return;
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "DELETE FROM Courses "
+ "WHERE CourseID = @CourseID";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@CourseID", SqlDbType.NChar, 10);
param1.Value = CourseID;
command.Parameters.Add(param1);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("Course information deleted.");
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
Action show_course = () =>
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "select * from Courses";
SqlCommand command = new SqlCommand(sql, connection);
try
{
connection.Open();
Console.WriteLine("Course list: ");
SqlDataReader reader = command.ExecuteReader();
Console.WriteLine("\n\tCourse ID\tCourse Name");
while (reader.Read())
{
Console.WriteLine("\t" + reader["CourseID"].ToString() + "\t" + reader["CourseName"].ToString());
}
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
// To the next level of menu
int number = user_choice();
switch (number)
{
case 0:
main_menu();
break;
case 1:
new_course();
break;
/*
case 2:
{
edit_course();
break;
}
*/
case 3:
delete_course();
break;
case 4:
show_course();
break;
}
}
private void registration_menu()
{
// Registration Menu
Console.WriteLine("\n[3] Student registration:"
+ "\n\t1 > Register course for student"
+ "\n\t2 > List all courses"
+ "\n\t0 > Back to main menu"
);
Action register = () =>
{
String StudentID = prompt("Enter the Student's ID");
String CourseID = prompt("Enter the Course's ID");
using (SqlConnection connection = new SqlConnection(connectionString))
{
String sql = "INSERT INTO Registration"
+ "(StudentID, CourseID, CourseName)"
+ "VALUES (@StudentID, @CourseID, (SELECT CourseName FROM Courses Where CourseID = @CourseID2))";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param1 = new SqlParameter("@StudentID", SqlDbType.NChar, 10);
param1.Value = StudentID;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@CourseID", SqlDbType.NChar, 10);
param2.Value = CourseID;
command.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("@CourseID2", SqlDbType.NChar, 10);
param3.Value = CourseID;
command.Parameters.Add(param3);
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("New course information added");
connection.Close();
return;
}
catch (Exception)
{
Console.WriteLine("Connection problem");
}
}
};
// To the next level of menu
int number = user_choice();
bool condition = true;
while(condition)
{
switch (number)
{
case 0:
main_menu();
break;
case 1:
// Student menu complete
register();
break;
}
}
}
}
}
|
Java | UTF-8 | 1,442 | 2.53125 | 3 | [] | no_license | package com.example;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.List;
/**
* Created by S.Rakhimov
*/
//@ViewScoped
@ManagedBean(name = "studentsServiceImpl")
@SessionScoped
public class StudentsServiceImpl implements StudentsService {
private List<Students>studentsList;
private Students student = new Students();
// @Inject
private final StudentsDao studentsDao;
public StudentsServiceImpl() {
studentsDao = new StudentsCrudImpl();
}
@PostConstruct
public void init(){
this.studentsList = studentsDao.getStudentList();
}
@Override
public void delete(Students students) {
studentsDao.delete(students);
studentsList.remove(students);
}
@Override
public void addStudent(Students students) {
studentsDao.addStudent(students);
studentsList = studentsDao.getStudentList();
}
@Override
public void editStudent(Students students) {
studentsDao.editStudent(students);
}
public List<Students> getStudentsList() {
return studentsList;
}
public void setStudentsList(List<Students> studentsList) {
this.studentsList = studentsList;
}
public Students getStudents() {
return student;
}
public void setStudents(Students students) {
this.student = students;
}
}
|
Shell | UTF-8 | 326 | 3.140625 | 3 | [] | no_license | #!/bin/bash
# This script is only useful for developing this application.
# This script will build the container image, and start a container using it,
# giving you a bash shell.
# The code is mounted in the /code directory.
image=$(docker build -q .)
docker run --rm -it -v $PWD/src:/code -u "$(id -u)" -w /code $image bash
|
PHP | UTF-8 | 1,839 | 3.0625 | 3 | [] | no_license | <?php
$file = "src/test";
$lines = file($file,FILE_IGNORE_NEW_LINES);
//fonction compteur de lignes
function compt_ligne($lines)
{
$c_lines=0;
foreach ($lines as $c)
{
$c_lines++;
}
return $c_lines;
}
//fonction cut permet de recuperer les données et de speare en plusieurs morceaux
function cut($temp_lignes)
{
$file = "src/test";
$lines = file($file,FILE_IGNORE_NEW_LINES);
//decoupages de mes lignes
for($i=0;$i<$temp_lignes;$i++)
{
//ignore les # et les espace vide du debut
if($lines[$i][0]==="#" OR $lines[$i][0]===" ") continue;
//remove the '-'
$cut_param_unique = explode("-", $lines[$i]);
//print_r($cut_param_unique);
//echo $cut_param_unique[0]."<br>";
for($y = 0; $y < count($cut_param_unique); $y++ )
{
$command[$i][$y] = $cut_param_unique[$y];
}
}
// echo "<br> my call request for each col X # row Y (input them manually) of array: ".$command[X][Y]."<br>";
return $command;
}
$temp_lignes = compt_ligne($lines);
$run_command = cut($temp_lignes);
//printing value from 2d array returned from command injection
echo "<br> before my call <br>";
echo "<pre>";
print_r($run_command);
echo "</pre>";
echo "<br> before call counts : ". count($run_command)."<br>";
//<-----------GAMMA PRE TESTING------------->
function indexing($run_command)
{
//compteur commande total
$compt_com=count($run_command);
$i=1;
while($i<=10)
{
//checking every aspect of Mountains pre existing in to commands
/*if($run_command[$i][0]=="M")
{
}
*/
echo $i."<br>";
sleep(2);
$i++;
}
}
//executing the test
indexing($run_command);
|
Markdown | UTF-8 | 916 | 2.546875 | 3 | [
"MIT"
] | permissive | ---
title: "The Unbearable: Toward an Antifascist Aesthetic"
link-published: "2020-08-14"
link-url: "https://www.nybooks.com/daily/2020/08/14/the-unbearable-toward-an-antifascist-aesthetic/"
date: "2020-08-17 12:00:00"
link-author: "Jon Baskin"
---
A really thought provoking article on irrational politics — and you're probably thinking of _irrational_ in an entirely pejorative way, but here it means a politics that uses symbols and myths rather than “facts” and arguments. Knausgaard contemplates the appeal of Nazism to Germans in its symbols and philosophical promise to provide simplicity and _depth_, rather than as a response to the collapse of the Weimar Republic, mass unemployment and other economic and historical factors.
It strikes me that — at the very least — we need to understand this rather than see Trump, Brexit and other modern irrationalities simply in terms of a failure of reason.
|
C# | UTF-8 | 618 | 2.5625 | 3 | [
"MIT"
] | permissive | using Microsoft.EntityFrameworkCore;
// ReSharper disable once IdentifierTypo
namespace PhonebookAPI.Models
{
public class ContactContext : DbContext
{
public ContactContext(DbContextOptions<ContactContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Number>()
.HasIndex(p => new { p.PhoneNumber })
.IsUnique();
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<Number> Numbers { get; set; }
}
}
|
Java | UTF-8 | 678 | 2 | 2 | [] | no_license | package com.hchc.alarm.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
import java.util.List;
/**
* @author wangrong
* @date 2020-06-22
*/
@Getter
@Setter
@ToString
public class PushMall {
private long hqId;
private long branchId;
private Date startTime;
private Date endTime;
private List<String> orderList;
public PushMall(long hqId, long branchId, Date start, Date end, List<String> orderList) {
this.hqId = hqId;
this.branchId = branchId;
this.startTime = start;
this.endTime = end;
this.orderList = orderList;
}
public PushMall() {
}
}
|
PHP | UTF-8 | 1,763 | 2.515625 | 3 | [] | no_license | <?php
namespace Bitreserve\Tests\Unit\Model;
use Bitreserve\Model\Ticker;
/**
* TickerTest.
*/
class TickerTest extends TestCase
{
/**
* @test
*/
public function shouldReturnInstanceOfTicker()
{
$data = array('ask' => '1');
$client = $this->getBitreserveClientMock();
$ticker = new Ticker($client, $data);
$this->assertInstanceOf('Bitreserve\BitreserveClient', $ticker->getClient());
$this->assertInstanceOf('Bitreserve\Model\Ticker', $ticker);
}
/**
* @test
*/
public function shouldReturnAsk()
{
$data = array('ask' => '1');
$client = $this->getBitreserveClientMock();
$ticker = new Ticker($client, $data);
$this->assertEquals($data['ask'], $ticker->getAsk());
}
/**
* @test
*/
public function shouldReturnBid()
{
$data = array('bid' => '1');
$client = $this->getBitreserveClientMock();
$ticker = new Ticker($client, $data);
$this->assertEquals($data['bid'], $ticker->getBid());
}
/**
* @test
*/
public function shouldReturnCurrency()
{
$data = array('currency' => 'BTC');
$client = $this->getBitreserveClientMock();
$ticker = new Ticker($client, $data);
$this->assertEquals($data['currency'], $ticker->getCurrency());
}
/**
* @test
*/
public function shouldReturnPair()
{
$data = array('pair' => '1');
$client = $this->getBitreserveClientMock();
$ticker = new Ticker($client, $data);
$this->assertEquals($data['pair'], $ticker->getPair());
}
protected function getModelClass()
{
return 'Bitreserve\Model\Ticker';
}
}
|
Java | UTF-8 | 7,777 | 1.875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.tke.v20180525.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class RegionInstance extends AbstractModel{
/**
* Region name
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("RegionName")
@Expose
private String RegionName;
/**
* Region ID
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("RegionId")
@Expose
private Long RegionId;
/**
* Region status
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("Status")
@Expose
private String Status;
/**
* Status of region-related features (return all attributes in JSON format)
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("FeatureGates")
@Expose
private String FeatureGates;
/**
* Region abbreviation
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("Alias")
@Expose
private String Alias;
/**
* Whitelisted location
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("Remark")
@Expose
private String Remark;
/**
* Get Region name
Note: this field may return null, indicating that no valid values can be obtained.
* @return RegionName Region name
Note: this field may return null, indicating that no valid values can be obtained.
*/
public String getRegionName() {
return this.RegionName;
}
/**
* Set Region name
Note: this field may return null, indicating that no valid values can be obtained.
* @param RegionName Region name
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setRegionName(String RegionName) {
this.RegionName = RegionName;
}
/**
* Get Region ID
Note: this field may return null, indicating that no valid values can be obtained.
* @return RegionId Region ID
Note: this field may return null, indicating that no valid values can be obtained.
*/
public Long getRegionId() {
return this.RegionId;
}
/**
* Set Region ID
Note: this field may return null, indicating that no valid values can be obtained.
* @param RegionId Region ID
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setRegionId(Long RegionId) {
this.RegionId = RegionId;
}
/**
* Get Region status
Note: this field may return null, indicating that no valid values can be obtained.
* @return Status Region status
Note: this field may return null, indicating that no valid values can be obtained.
*/
public String getStatus() {
return this.Status;
}
/**
* Set Region status
Note: this field may return null, indicating that no valid values can be obtained.
* @param Status Region status
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setStatus(String Status) {
this.Status = Status;
}
/**
* Get Status of region-related features (return all attributes in JSON format)
Note: this field may return null, indicating that no valid values can be obtained.
* @return FeatureGates Status of region-related features (return all attributes in JSON format)
Note: this field may return null, indicating that no valid values can be obtained.
*/
public String getFeatureGates() {
return this.FeatureGates;
}
/**
* Set Status of region-related features (return all attributes in JSON format)
Note: this field may return null, indicating that no valid values can be obtained.
* @param FeatureGates Status of region-related features (return all attributes in JSON format)
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setFeatureGates(String FeatureGates) {
this.FeatureGates = FeatureGates;
}
/**
* Get Region abbreviation
Note: this field may return null, indicating that no valid values can be obtained.
* @return Alias Region abbreviation
Note: this field may return null, indicating that no valid values can be obtained.
*/
public String getAlias() {
return this.Alias;
}
/**
* Set Region abbreviation
Note: this field may return null, indicating that no valid values can be obtained.
* @param Alias Region abbreviation
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setAlias(String Alias) {
this.Alias = Alias;
}
/**
* Get Whitelisted location
Note: this field may return null, indicating that no valid values can be obtained.
* @return Remark Whitelisted location
Note: this field may return null, indicating that no valid values can be obtained.
*/
public String getRemark() {
return this.Remark;
}
/**
* Set Whitelisted location
Note: this field may return null, indicating that no valid values can be obtained.
* @param Remark Whitelisted location
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setRemark(String Remark) {
this.Remark = Remark;
}
public RegionInstance() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public RegionInstance(RegionInstance source) {
if (source.RegionName != null) {
this.RegionName = new String(source.RegionName);
}
if (source.RegionId != null) {
this.RegionId = new Long(source.RegionId);
}
if (source.Status != null) {
this.Status = new String(source.Status);
}
if (source.FeatureGates != null) {
this.FeatureGates = new String(source.FeatureGates);
}
if (source.Alias != null) {
this.Alias = new String(source.Alias);
}
if (source.Remark != null) {
this.Remark = new String(source.Remark);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "RegionName", this.RegionName);
this.setParamSimple(map, prefix + "RegionId", this.RegionId);
this.setParamSimple(map, prefix + "Status", this.Status);
this.setParamSimple(map, prefix + "FeatureGates", this.FeatureGates);
this.setParamSimple(map, prefix + "Alias", this.Alias);
this.setParamSimple(map, prefix + "Remark", this.Remark);
}
}
|
C++ | UTF-8 | 342 | 3.40625 | 3 | [] | no_license | #include <iostream>
//verifica se o número ou não primo
using namespace std;
int main()
{
int x,i=2,p=0;
cout<<"Digite um número:";
cin>>x;
while(i<x)
{
if(x%i==0)
p++;
i++;
}
if(p==0)
cout<<"Número primo!";
else
cout<<"Número não primo!";
return 0;
}
|
Python | UTF-8 | 214 | 3.25 | 3 | [] | no_license | s = list(map(int, input()))
a = 0
b = 0
old = -1
for new in s:
if old == new:
continue
old = new
if new == 0:
a += 1
else:
b += 1
if a > b:
print(b)
else:
print(a) |
C++ | UTF-8 | 3,133 | 2.5625 | 3 | [] | no_license | #include "MatrixOperation.h"
#include <chrono>
#include <cblas.h>
#define LENGTH 14000
///usr/local/Cellar/gcc/10.2.0/bin/g++-10 main.cpp MatrixOperation.cpp -fopenmp -mavx2 -std=c++11 -I/usr/local/Cellar/openblas/0.3.10_2/include -L/usr/local/Cellar/openblas/0.3.10_2/lib -lopenBlas -O3
int main() {
cout<<"Please select which operation do you want!!!"<<endl;
cout<<"if you want to check large amount`speed please count 1"<<endl
<<"else if you want to check small amount`s vector multiply please count 2"<<endl;
int amoutJudge = 0;
cin>>amoutJudge;
if(amoutJudge==1){
matrix matrix1 = {LENGTH,LENGTH,new float [LENGTH*LENGTH]()};
// matrix1.value = new float [matrix1.rowNumber*matrix1.columnNumber]();
matrix matrix2 = {LENGTH,LENGTH,new float [LENGTH*LENGTH]()};
matrix matrixResult = {LENGTH,LENGTH,new float [LENGTH*LENGTH]()};
// checkSpeed1(matrix1,matrix2,matrixResult);
// checkSpeed1(matrix1,matrix2,matrixResult);
//
// auto start = std::chrono::steady_clock::now();
// checkSpeed1(matrix1,matrix2,matrixResult);
// auto end = std::chrono::steady_clock::now();
// auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
// cout << "matrixProduct 1 , duration = " << duration <<" ms"<< std::endl;
//
// auto start2 = std::chrono::steady_clock::now();
// checkSpeed2(matrix1,matrix2,matrixResult);
// auto end2 = std::chrono::steady_clock::now();
// auto duration2 = std::chrono::duration_cast<std::chrono::milliseconds>(end2 - start2).count();
// cout << "matrixProduct 2 , duration = " << duration2 <<" ms"<< std::endl;
//
// auto start3 = std::chrono::steady_clock::now();
// checkSpeed3(matrix1,matrix2,matrixResult);
// auto end3 = std::chrono::steady_clock::now();
// auto duration3 = std::chrono::duration_cast<std::chrono::milliseconds>(end3 - start3).count();
// cout << "matrixProduct 3 , duration = " << duration3 <<" ms"<< std::endl;
auto start4 = std::chrono::steady_clock::now();
checkSpeed4(matrix1,matrix2,matrixResult);
auto end4 = std::chrono::steady_clock::now();
auto duration4 = std ::chrono::duration_cast<std::chrono::milliseconds>(end4 - start4).count();
cout << "matrixProduct 4 , duration = " << duration4 <<" ms"<< std::endl;
auto start5 = std::chrono::steady_clock::now();
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, LENGTH, LENGTH, LENGTH, 1.0, matrix1.value, LENGTH, matrix2.value, LENGTH, 0.0, matrixResult.value, LENGTH);
auto end5 = std::chrono::steady_clock::now();
auto duration5 = std::chrono::duration_cast<std::chrono::milliseconds>(end5 - start5).count();
cout << "OpenBlas , duration = " << duration5 <<" ms"<< std::endl;
delete [] matrix1.value;
delete [] matrix2.value;
delete [] matrixResult.value;
// clear(matrix1);
// clear(matrix2);
// clear(matrixResult);
}else {
userInput();
}
return 0;
}
|
Swift | UTF-8 | 1,585 | 2.515625 | 3 | [] | no_license | //
// DetailViewController.swift
// Project
//
// Created by admin on 2019/8/14.
// Copyright © 2019 limice. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var imageName: String!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.layer.borderWidth = 1;
self.imageView.layer.borderColor = UIColor.gray.cgColor
self.imageView.image = UIImage(named: imageName)
navigationItem.largeTitleDisplayMode = .never
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(barButtonTapped))
// Do any additional setup after loading the view.
}
@objc func barButtonTapped() {
guard let image = imageView.image?.jpegData(compressionQuality: 0.8) else {
print("没有图片")
return
}
let active = UIActivityViewController(activityItems: [imageName!,image], applicationActivities: [])
active.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(active, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
Markdown | UTF-8 | 2,085 | 3.296875 | 3 | [] | no_license | # Collections demonstration in Java
## Tasks
1. Добавяне на елемент в колекция(List, Set, Map) по всички възможни начини.
2. Итериране по колекция(List, Set, Map) по всички възможни начини.
a. Премахване на произволен елемент по време на итериране по колекция.
3. Достъпване на елемент от колекция(List, Set, Map) по всички възможни начини.
4. Подменяне на елемент от колекция(List, Set, Map) по всички възможни начини.
5. Търсене на елемент в колекция(List, Set, Map) по всички възможни начини.
6. Сортиране на колекция(List, Set, Map) от String.
6.1. Сортиране на колекция(List, Set, Map) от Student{name, age}.
7. Сортиране на List от Student{name, age}
8. Попълнете List с Student{name, age}.
a. Да се направи Set от този List, който да включва всички Student на възраст между 20 и 24 години.
b. Да се направи List от всички Student чието име започва с 'А' и са на възраст между 18 и 20 години, този List да се сортира в низходящ ред по възраст, а тези с една и съща възраст да бъдат сортирани по име във възходящ ред.
c. Да се обърне последователността на списъкът получен като резултат в задача 8.2.
9. Създайте List от Student и разменете 3-ят и 5-ят елемент.
10. Създайте List от Student и създайте нов List, който съдържа елементите от 3-ти до 8-ми индекс.
11. Създайте 2 List-а от Student и ги обединете в нов List.
|
Python | UTF-8 | 487 | 2.875 | 3 | [] | no_license | #Following script doesnt work on macOS (also >python3.3) due to
#the included crypt package in macos being different,
#i cant afford a mac so its not my problem -Sudam
#(or use passlib - platform independant package)
import sys
import crypt
#Config
password=sys.argv[1]
hashedValue=crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
#salt is secure and generated from mksalt in cryptpackage
#Output
print('Value to be hashed :',sys.argv[1])
print('Hashed Value :',hashedValue)
|
C | UTF-8 | 311 | 3.46875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
div_t result1;
ldiv_t result2;
result1 = div(12345, 2345);
result2 = ldiv(123456789, 12345678);
printf("%d, %d\n", result1.quot, result1.rem);
printf("%ld, %ld\n", result2.quot, result2.rem);
printf("%g\n", fmod(23.456, 2.345));
}
|
Ruby | UTF-8 | 1,019 | 2.59375 | 3 | [] | no_license | require 'twitter'
require 'octokit'
require 'pp'
require 'dotenv'
Dotenv.load
client = Octokit::Client.new(:login => 'alexrochas', :password => ENV['GITHUB_PASS'], per_page: 200)
# client.auto_paginate = true
repos = client
.repos
.reject {|repo| repo.private }
repo_sample = repos.sample
enhance_repo = lambda { |repo|
{
name: repo.name,
url: repo.html_url,
description: repo.description,
languages: client.languages(repo.full_name)
}
}
repo = enhance_repo.call(repo_sample)
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_SECRET']
end
message = "Take a look at my repo #{repo[:name]} at (#{repo[:url]})
#{repo[:description]}, [#{repo[:languages].map{|l| l.first.to_s}.join(', ')}]\n
#github #awesomerepos"
puts message
client.update(message)
|
Ruby | UTF-8 | 766 | 2.75 | 3 | [] | no_license | require 'mongo'
require 'pp'
require 'byebug'
Mongo::Logger.logger.level = ::Logger::DEBUG
class Solution
@@db = nil
def self.mongo_client
@@db = Mongo::Client.new('mongodb://localhost:27017')
@@db = @@db.use('test')
end
def self.collection
self.mongo_client if not @@db
@@db[:zips]
end
def sample
self.class.collection.find.first
end
def self.find id
Rails.logger.debug { "getting zip #{id}" }
doc = collection.find(:_id=>id)
.projection({_id:true, city:true, state:true, pop:true})
.first
return doc.nil? ? nil : Zip.new(doc)
end
end
#byebug
db=Solution.mongo_client
#p db
zips=Solution.collection
#p zips
s=Solution.new
pp s.sample |
Java | UTF-8 | 421 | 1.789063 | 2 | [
"Apache-2.0"
] | permissive | package org.javacord.api.event.channel.server.voice;
import org.javacord.api.entity.channel.ServerVoiceChannel;
import org.javacord.api.event.channel.VoiceChannelEvent;
import org.javacord.api.event.channel.server.ServerChannelEvent;
/**
* A server voice channel event.
*/
public interface ServerVoiceChannelEvent extends ServerChannelEvent, VoiceChannelEvent {
@Override
ServerVoiceChannel getChannel();
}
|
C | UTF-8 | 1,538 | 3.453125 | 3 | [] | no_license | /*list.c*/
#include "list.h"
struct pidlist
{
pid_t pid;
struct pidlist *next;
};
struct pidlist *start = NULL;
struct pidlist *next = NULL;
int listadd(pid_t key)
{
struct pidlist *zeiger;
if(start == NULL)
{
if((start = malloc(sizeof(struct pidlist))) == NULL)
{
//Kein Spiecher da
return -1;
}
start->pid = key;
start->next =NULL;
}
else
{
zeiger = start;
while(zeiger->next != NULL)
zeiger = zeiger->next;
if((zeiger->next = malloc(sizeof(struct pidlist))) == NULL)
{
//Kein Speicher da
return -1;
}
zeiger = zeiger->next;
zeiger->pid = key;
zeiger->next = NULL;
}
return 0;
}
int listdelete(pid_t key)
{
struct pidlist *zeiger, *zeiger1;
if(start != NULL)
{
if(key == start->pid)
{
zeiger = start->next;
free(start);
start = zeiger;
}
else
{
zeiger = start;
while(zeiger->next != NULL)
{
zeiger1 = zeiger->next;
if(key == zeiger->pid)
{
zeiger->next = zeiger1->next;
free(zeiger1);
break;
}
zeiger = zeiger1;
}
}
}
else
{
return -1;
}
return 0;
}
int listcount()
{
struct pidlist *zeiger;
int count = 1;
if(start == NULL)
{
return 0;
}
else
{
zeiger = start;
while(zeiger->next != NULL)
{
zeiger = zeiger->next;
count++;
}
return count;
}
}
pid_t listgetfirst()
{
if(start == NULL)
{
return -1;
}
else
{
return start->pid;
}
}
|
Java | UTF-8 | 593 | 1.59375 | 2 | [] | no_license | /**************************************************************************************************
* Framework Generated DAO Source
* - WC_VIC_ORG_CODE_RATE_LINK -
*************************************************************************************************/
package project.conf.resource.ormapper.dao.WcVicOrgCodeRateLink;
import project.conf.resource.ormapper.dto.oracle.WcVicOrgCodeRateLink;
import zebra.base.IDao;
public interface WcVicOrgCodeRateLinkDao extends IDao {
public WcVicOrgCodeRateLink getWcVicOrgCodeRateLinkById(String wcVicOrgCodeRateLinkId) throws Exception;
} |
Python | UTF-8 | 451 | 3.015625 | 3 | [] | no_license | from train import train
class medium(train):
''' This is a medium train '''
def __init__(self, n):
''' Initializes the medium train '''
self.name = n
self.length = 2
self.capacity = 75
def getLength(self):
''' Returning the length of the train '''
return self.length
def getCapacity(self):
''' Returning the passenger capacity of the train '''
return self.capacity
|
C++ | UTF-8 | 335 | 2.625 | 3 | [
"MIT"
] | permissive | #include "error.h"
void HttpError::register_handler(http_status_code status, const Response &response) {
handlers[status] = response;
}
Response HttpError::from(http_status_code status) {
if (handlers.count(status) > 0) {
return handlers.at(status);
}
return plain(std::to_string(static_cast<int>(status)), status);
}
|
Python | UTF-8 | 1,710 | 3.703125 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python
# coding: -utf8
import user_input as ui
def every_input_ok(s):
return s
class Employee():
def __init__(self, first_name, last_name, position, separation_date):
self.first_name = first_name
self.last_name = last_name
self.position = position
self.separation_date = separation_date
def __str__(self):
return f"{self.first_name} {self.last_name} {self.position} {self.separation_date}"
def print_cel(s):
print("%-23s" % s, end="")
def print_row(left, middle, right):
print_cel(left)
print_cel("|" + middle)
print_cel("|" + right)
print("")
if __name__ == '__main__':
employees = [
Employee("John", "Johnson", "Manager", "2016-12-31"),
Employee("Tou", "Xiong", "Software Engineer", "2016-10-05"),
Employee("Michaela", "Michaelson", "District Manager", "2015-12-19"),
Employee("Jake", "Jacobson", "Programmer", ""),
Employee("Jacquelyn", "Jackson", "DBA", ""),
Employee("Sally", "Weber", "Web Developer", "2015-12-18")
]
search_string = ui.read_user_input_with_validator(
"Enter a search string: ", every_input_ok, "")
def filter_func(employee): return (
search_string in employee.last_name
or
search_string in employee.first_name)
result = filter(filter_func, employees)
print_row("Name", " Position", " Separation Date")
print_row("-----------------------",
"----------------------", "----------------------")
for employee in result:
print_row(employee.first_name + " " + employee.last_name,
" " + employee.position, " " + employee.separation_date)
|
Markdown | UTF-8 | 9,327 | 3.1875 | 3 | [] | no_license | ---
id: 311
title: IAsyncEnumerable<T> Is Your Friend, Even In .NET Core 2.x
date: 2019-12-01T06:00:00-05:00
permalink: /csharp/2019/12/01/iasyncenumerable-is-your-friend.html
categories:
- C#
- .NET Core
summary: IAsyncEnumerable is a great new feature in C# 8. This post should help clarify what they do, when to use them, and when they can be used in a particular project.
---
{: .notice--info}
This blog is one of The December 1st entries on the [2019 C# Advent Calendar](https://crosscuttingconcerns.com/The-Third-Annual-csharp-Advent). Thanks for having me again Matt!
My favorite new feature in [C# 8](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8) has got to be
[Asynchronous Streams](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams), a.k.a.
Asynchronous Enumerables. However, I think there may some confusion as to what they do, when to use them, and even if
they can be used in a particular project. This post will hopefully clarify some of these points.
## TL;DR
You can use `IAsyncEnumerable<T>` and the related C# 8 features in .NET Core 2.x or .NET Framework 4.6.1, not just .NET Core 3.0!
## Why use `IAsyncEnumerable<T>`?`
When writing efficient applications intended to handle large numbers of simultaneous operations, such as web applications,
blocking operations are the enemy. Any time an application is waiting on some kind of I/O-bound operation, such as a network
response or a hard disk read, it is always best to relinquish the thread back to the thread pool. This allows the CPU to
work on other operations while the method is waiting, and then continue the work once there is more to be done, without using up
all of the threads in the thread pool. Lots of details about why are
[available here](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming).
In many cases, it's efficient enough to simply return a regular `IEnumerable<T>` asynchronously, like so:
```cs
public async Task DoWork()
{
var query = BuildMyQuery();
IEnumerable<XYZ> queryResult = await query.ExecuteAsync();
foreach (var item in queryResult)
{
// Do work here
}
}
```
However, this is may not be the most efficient approach. There are two potential limitations, depending on the backing implementation of
`ExecuteAsync` in the example above.
1. The implementation of ExecuteAsync may return after it gets the first part of the data, or even none. If it is enumerated faster than the data is arriving it will block waiting for more items to arrive. This will block the executing thread.
2. The implementation of ExecuteAsync may wait until it has **all** of the data before returning. This delays the point where DoWork may begin processing data.
`IAsyncEnumerable<T>` and its sibling `IAsyncEnumerator<T>`, on the other hand, return a `Task` as the stream is iterated. This allows methods
such as `ExecuteAsync` to return early and then wait for more data as it is iterated, without blocking the thread.
## When **Not** To Use IAsyncEnumerable
Don't use `IAsyncEnumerable<T>` for any collection which is inherently synchronous and CPU-bound.
For those cases, continuing using `IEnumerable<T>`. The extra overhead of handling asynchronous tasks
will usually be less performant in these scenarios.
Knowing which type to use as the return type on an interface method is a bit tricker. The interface can have different
backing implementations which may or may not be synchronous. In this case, use the pattern for the most likely scenario.
If in doubt, lean towards `IAsyncEnumerable<T>` because it can be used for either scenario and is therefore more flexible.
## Returning an IAsyncEnumerable in C# 8
For simple use cases, returning an `IAsyncEnumerable<T>` using an iterator function is as easy as an `IEnumerable<T>`.
```cs
public async IAsyncEnumerable<XYZ> GetXYZAsync() {
for (var i=0; i<20; i++)
{
var item = await GetXYZById(i);
yield return item;
}
}
```
It is also possible to write an iterator method which returns `IAsyncEnumerator<T>`.
If the method supports cancellation, the CancellationToken should to be decorated with the
`EnumeratorCancellation` attribute:
```cs
public async IAsyncEnumerable<XYZ> GetXYZAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) {
for (var i=0; i<20; i++)
{
var item = await GetXYZById(i, cancellationToken);
yield return item;
}
}
```
## Consuming an IAsyncEnumerable in C# 8
To consume an IAsyncEnumerable, simply use the new `await foreach` statement within an asynchronous method.
```cs
await foreach (var item in GetXYZAsync())
{
// do things here
}
```
To control the synchronization context, `ConfigureAwait` is available, just like on `Task`.
```cs
await foreach (var item in GetXYZAsync().ConfigureAwait(false))
{
// do things here
}
```
To pass a cancellation token:
```cs
await foreach (var item in GetXYZAsync().WithCancellation(cancellationToken))
{
// do things here
}
```
## Special Compatibility Concerns
Depending on the type of project and the version of .NET being targeted, there may be concerns
about compatibility. One myth is that these features can only be used with .NET Core 3.0 and C# 8.
### Can I Use IAsyncEnumerable When Targeting .NET Core 2.x?
**Short answer**: Yes
To gain access to IAsyncEnumerable, install the compatibility NuGet package
[Microsoft.Bcl.AsyncInterfaces](https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces/). This provides
the types that are missing in .NET Standard 2.0.
However, producing and consuming IAsyncEnumerables is a bit more difficult. Here's an example consumer:
```cs
var enumerable = GetXYZAsync();
var enumerator = enumerable.GetAsyncEnumerator();
try
{
while (await enumerator.MoveNextAsync())
{
var item = enumerator.Current;
// Do things here
}
}
finally
{
await enumerator.DisposeAsync();
}
```
To get around this limitation, there are ways to access C# 8 language features, like asynchronous streams, even from .NET Core 2.x.
The requirements are:
- Use .NET Core SDK 3.0 or MSBuild Tools 2019 as the compiler.
- Use Visual Studio 2019 or VSCode as the IDE.
- Add a `<LangVersion>8</LangVersion>` property to the project file.
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<LangVersion>8</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" />
</ItemGroup>
</Project>
```
### Can I Use IAsyncEnumerable When Targeting .NET Framework
**Short answer**: Yes, 4.6.1 or later
.NET Framework 4.6.1 is compatible with .NET Standard 2.0. Therefore, so long as the project is targeting .NET Framework 4.6.1 or later,
the same rules apply as for .NET Core 2.x. Just follow the same steps as above.
### What About NuGet Packages?
**Short answer**: Yes, targeting .NET Standard 2.0 or later
When creating a NuGet package, maintaining backwards compatibility is key. This can make it difficult to use new features like
asynchronous streams. The good news is that there is a relatively easy path.
- Dual target .NET Standard 2.0 and 2.1.
- Consider targeting .NET 4.6.1 as well, see [Microsoft's guidance on cross platform targeting](https://docs.microsoft.com/en-us/dotnet/standard/library-guidance/cross-platform-targeting).
- Include [Microsoft.Bcl.AsyncInterfaces](https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces/) for the lower version targets only.
- Add a `<LangVersion>8</LangVersion>` property to the project file.
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net461;netstandard2.0;netstandard2.1</TargetFrameworks>
<LangVersion>8</LangVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' Or '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" />
</ItemGroup>
</Project>
```
However, this approach has problems if the package needs to target versions of .NET Core before 2.0, .NET Standard before 2.0,
or .NET Framework before 4.6.1. The `Microsoft.Bcl.AsyncInterfaces` package isn't compatible with frameworks prior these versions.
This can still be addressed by using preprocessor conditionals within the codebase to exclude `IAsyncEnumerable<T>` support,
but is much more cumbersome and outside the scope of this post.
## What about LINQ?
Most .NET developers love to use LINQ, either using the query syntax or using the functional
syntax like `.Where(p => p != null)` or `.Select(p => p.Property)`. Is it possible to use LINQ with `IAsyncEnumerable<T>`?
To get support for the functional LINQ syntax, such as `.Where(p => p != null)` or `.Select(p => p.Property)`, install
[System.Linq.Async](https://www.nuget.org/packages/System.Linq.Async/). This package is brought to us by the group that makes
[ReactiveX](http://reactivex.io/). Be sure to use at least version 4.0.0.
## Conclusion
Don't be afraid to use `IAsyncEnumerable<T>` in your code. It's really a lot more available than most developers think it is,
and is very easy to use.
|
Python | UTF-8 | 1,736 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | # @Author:孟祥森
# @Time:2020/9/18 16:57
import hashlib
import time
import requests
import random
import string
from urllib.parse import quote
def curlmd5(src):
m = hashlib.md5(src.encode('UTF-8'))
return m.hexdigest().upper() # 将得到的MD5值所有字符转换成大写
def get_params(plus_item): # 用于返回request需要的data内容
global params
t = time.time() # 请求时间戳(秒级),(保证签名5分钟有效)
time_stamp = str(int(t))
nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 10)) # 请求随机字符串,用于保证签名不可预测
app_id = '2156854947' # 修改成自己的id
app_key = 'mw9EgBDh407Y4P3g' # 修改成自己的key
params = {'app_id': app_id,
'question': plus_item,
'time_stamp': time_stamp,
'nonce_str': nonce_str,
'session': '10000'
}
sign_before = ''
for key in sorted(params): # 要对key排序再拼接
sign_before += '{}={}&'.format(key, quote(params[key], safe='')) # 拼接过程需要使用quote函数形成URL编码
sign_before += 'app_key={}'.format(app_key) # 将app_key拼接到sign_before后
sign = curlmd5(sign_before)
params['sign'] = sign # 对sign_before进行MD5运算
return params # 得到request需要的data内容
def get_content(plus_item):
global payload, r
url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat" # 聊天的API地址
plus_item = plus_item.encode('utf-8')
payload = get_params(plus_item)
r = requests.post(url, data=payload) # 带参请求api地址
result = r.json()["data"]["answer"]
print(result)
return result # 获得返回内容
|
Java | UTF-8 | 3,972 | 2.53125 | 3 | [] | no_license | import exceptions.SemanticParseException;
import java.util.Set;
import java.util.Map;
/* Generated By:JJTree: Do not edit this line. ASTDiv.java Version 6.1 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=true,VISITOR=false,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
public class ASTDiv extends SimpleNode {
public ASTDiv(int id) {
super(id);
this.returnType = "int";
}
public ASTDiv(Parser p, int id) {
super(p, id);
this.returnType = "int";
}
@Override
public String analyze(Descriptor descriptor, Set<String> variables) throws SemanticParseException{
MethodDescriptor functionST = (MethodDescriptor) descriptor;
SimpleNode lhsNode = this.jjtGetChild(0);
SimpleNode rhsNode = this.jjtGetChild(1);
String lhsType = lhsNode.analyze(functionST, variables);
String rhsType = rhsNode.analyze(functionST, variables);
if (!lhsType.equals(this.returnType) || !rhsType.equals(this.returnType))
this.parser.handleSemanticError(new SemanticParseException("Wrong types in division: " + lhsNode.jjtGetValue() + "[" + lhsType + "]"
+ " and " + rhsNode.jjtGetValue() + "[" + rhsType + "]"), this);
return this.returnType;
}
public void optimize(Descriptor descriptor, Map<String, Map<String, Integer>> variables) {
SimpleNode lhsNode = this.jjtGetChild(0);
SimpleNode rhsNode = this.jjtGetChild(1);
lhsNode.optimize(descriptor, variables);
rhsNode.optimize(descriptor, variables);
// If both childs are numeric substitute this node with its result
if (this.jjtGetChild(0) instanceof ASTNumeric && this.jjtGetChild(1) instanceof ASTNumeric) {
Integer leftOperand = Integer.parseInt((String) this.jjtGetChild(0).value);
Integer rightOperand = Integer.parseInt((String) this.jjtGetChild(1).value);
ASTNumeric constNode = new ASTNumeric(this.parser, ParserTreeConstants.JJTNUMERIC);
constNode.value = Integer.toString(leftOperand / rightOperand);
((SimpleNode) this.jjtGetParent()).replaceChild(this, constNode);
return;
}
// Other wise, if we shouldn't simplify (p.e. in 1st phase of conditions) set calcValue with the calculated value
Integer leftOperand = this.jjtGetChild(0).getCalcValue();
Integer rightOperand = this.jjtGetChild(1).getCalcValue();
if(leftOperand == null && this.jjtGetChild(0) instanceof ASTNumeric)
leftOperand = Integer.parseInt((String) this.jjtGetChild(0).value);
else if(rightOperand == null && this.jjtGetChild(1) instanceof ASTNumeric)
rightOperand = Integer.parseInt((String) this.jjtGetChild(1).value);
if(variables.get("#cond#") != null && leftOperand != null && rightOperand != null){
this.calcValue = leftOperand / rightOperand;
}
}
@Override
public void generateCode(Descriptor descriptor){
SimpleNode lhsNode = this.jjtGetChild(0);
SimpleNode rhsNode = this.jjtGetChild(1);
lhsNode.generateCode(descriptor);
// X / 2 ^ s: s max = 5 bits 31
if(rhsNode instanceof ASTNumeric){
int den = Integer.parseInt((String) rhsNode.jjtGetValue());
int s = powerOfTwo(den);
if( s >= 0 && s <= 31){
parser.addInstruction(JVMHelper.loadNumber((int) s));
parser.addInstruction(new JVMInstruction("ishr",-1));
return;
}
}
rhsNode.generateCode(descriptor);
parser.addInstruction(new JVMInstruction("idiv",-1));
}
public int powerOfTwo(int n)
{
if ((int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))))
return (int) (Math.log(n) / Math.log(2));
return -1;
}
}
/*
* JavaCC - OriginalChecksum=a6ae99679f76890aff99ebcee897988e (do not edit this
* line)
*/
|
C# | UTF-8 | 1,494 | 3.609375 | 4 | [] | no_license | using System;
/*
Task05
Дисциплина: "Программирование"
Группа: БПИ202
Студент: Алиева Рената
Дата: 12.09.2020
Задача: Получить от пользователя значения длин двух катетов,
вычислить и вывести на экран значение гипотенузы.
*/
namespace Task05
{
class Program
{
static void Main(string[] args)
{
double x, y;
Console.WriteLine("Первый катет: ");
while (!double.TryParse(Console.ReadLine(), out x) || x == 0) //проверяем на корректность введенный катет
{
Console.WriteLine("Некорректное значение");
Console.Write("Новое значение первого катета: ");
}
Console.WriteLine("Второй катет: ");
while (!double.TryParse(Console.ReadLine(), out y) || y == 0) //проверяем на корректность введенный катет
{
Console.WriteLine("Некорректное значение");
Console.Write("Новое значение второго катета: ");
}
double c = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));
Console.Write("Полученная гипотенуза: " + c);
}
}
}
|
Java | UTF-8 | 269 | 1.648438 | 2 | [] | no_license | package org.pmhelper.core.domain.entity.req;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 文本信息
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class TextMessageReq extends BaseMessageReq {
//消息内容
private String Content;
}
|
JavaScript | UTF-8 | 2,568 | 2.609375 | 3 | [] | no_license | const mongoose = require('mongoose');
const slugify = require('slugify');
const geocoder = require('../utils/geocoder');
const HotelSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name'],
unique: true,
trim: true
},
slug: String,
description: {
type: String,
required: [true, 'Please add a description'],
maxlength: [1000, 'Description cannot be more than 500 characters'],
trim: true
},
email: {
type: String,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please add a valid email']
},
phone: {
type: [Number],
required: [true, 'Please add phone number']
},
address: {
type: String,
required: [true, 'Please add an address']
},
city: {
type: String,
required: [true, 'Please add the city']
},
province: {
type: String,
required: [true, 'Please add the province']
},
zipcode: {
type: String,
required: [true, 'Please add the zipcode']
},
location: {
type: {
type: String,
required: true,
enum: ['Point']
},
coordinates: {
type: [Number],
required: true,
index: '2dsphere'
}
},
averageRating: {
type: Number,
min: [1, 'Rating must be at least 1'],
max: [10, 'Rating cannot be more than 10']
},
ceatedAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
},
photo: {
type: String
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true}
});
// Create a slug before save
HotelSchema.pre('save', function (next) {
this.slug = slugify(this.name, { lower: true });
next();
});
// Reverse populate with virtuals
HotelSchema.virtual('rooms', {
ref: 'Room',
localField: '_id',
foreignField: 'hotel',
justOne: false
});
// Cascade delete rooms when a hotel is deleted
HotelSchema.pre('remove', async function (next) {
await this.model('Room').deleteMany({ hotel: this._id });
next();
});
// Geocode & create location
/*
HotelSchema.pre('save', async function (next) {
const loc = await geocoder.geocode(this.zipcode);
this.location = {
type: 'Point',
coordinates: [loc[0].longitude, loc[0].latitude]
};
next();
})
*/
module.exports = mongoose.model('Hotel', HotelSchema); |
Java | UTF-8 | 630 | 3.046875 | 3 | [] | no_license | package kajal.Codingexam;
import java.util.ArrayList;
import java.util.Collections;
public class StudentComparable18p1 {
public static void main(String[] args) {
ArrayList<Student18p1> namelist = new ArrayList<Student18p1>();
namelist.add(new Student18p1(106, "kajal", "patil", "satara"));
namelist.add(new Student18p1(101, "priya", "kirdat", "pune"));
namelist.add(new Student18p1(103, "pooja", "more", "nashik"));
namelist.add(new Student18p1(102, "priyal", "mane", "pune"));
System.out.println("Before sorting" + namelist);
Collections.sort(namelist);
System.out.println("After sorting" + namelist);
}
}
|
Java | UTF-8 | 8,798 | 2.5625 | 3 | [] | no_license | import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import java.awt.FlowLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PersonalCont extends JFrame {
private JPanel contentPane;
private JTable table;
private JTextField tbFname;
private JTextField tbLname;
private JTextField tbEmail;
private JTextField tbTelephone;
private JTextField tbAddress1;
private JTextField tbAddress2;
private JTextField tbCity;
private JTextField tbPostCode;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PersonalCont frame = new PersonalCont();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PersonalCont() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 582, 348);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 99, 419, 210);
contentPane.add(scrollPane);
table = new JTable();
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
tbFname.setText(table.getValueAt(table.getSelectedRow(),1).toString());
tbLname.setText(table.getValueAt(table.getSelectedRow(),2).toString());
tbEmail.setText(table.getValueAt(table.getSelectedRow(),3).toString());
tbTelephone.setText(table.getValueAt(table.getSelectedRow(),4).toString());
tbAddress1.setText(table.getValueAt(table.getSelectedRow(),5).toString());
tbAddress2.setText(table.getValueAt(table.getSelectedRow(),6).toString());
tbPostCode.setText(table.getValueAt(table.getSelectedRow(),7).toString());
tbCity.setText(table.getValueAt(table.getSelectedRow(),8).toString());
}
});
scrollPane.setViewportView(table);
Dbconn d = new Dbconn();
table.setModel(DbUtils.resultSetToTableModel(d.GetAllPersonal()));
tbFname = new JTextField();
tbFname.setBounds(10, 22, 86, 20);
contentPane.add(tbFname);
tbFname.setColumns(10);
tbLname = new JTextField();
tbLname.setBounds(120, 22, 86, 20);
contentPane.add(tbLname);
tbLname.setColumns(10);
tbEmail = new JTextField();
tbEmail.setBounds(225, 22, 86, 20);
contentPane.add(tbEmail);
tbEmail.setColumns(10);
tbTelephone = new JTextField();
tbTelephone.setBounds(329, 22, 86, 20);
contentPane.add(tbTelephone);
tbTelephone.setColumns(10);
tbAddress1 = new JTextField();
tbAddress1.setBounds(10, 67, 86, 20);
contentPane.add(tbAddress1);
tbAddress1.setColumns(10);
tbAddress2 = new JTextField();
tbAddress2.setBounds(120, 67, 86, 20);
contentPane.add(tbAddress2);
tbAddress2.setColumns(10);
tbCity = new JTextField();
tbCity.setBounds(225, 67, 86, 20);
contentPane.add(tbCity);
tbCity.setColumns(10);
tbPostCode = new JTextField();
tbPostCode.setBounds(329, 67, 86, 20);
contentPane.add(tbPostCode);
tbPostCode.setColumns(10);
JLabel lblNewLabel = new JLabel("First Name");
lblNewLabel.setBounds(10, 11, 86, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Last Name");
lblNewLabel_1.setBounds(120, 11, 73, 14);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Email");
lblNewLabel_2.setBounds(225, 11, 73, 14);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("Telephone");
lblNewLabel_3.setBounds(329, 11, 73, 14);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("Address 1");
lblNewLabel_4.setBounds(10, 54, 73, 14);
contentPane.add(lblNewLabel_4);
JLabel lblNewLabel_5 = new JLabel("Address 2");
lblNewLabel_5.setBounds(120, 54, 73, 14);
contentPane.add(lblNewLabel_5);
JLabel lblNewLabel_6 = new JLabel("City");
lblNewLabel_6.setBounds(225, 54, 46, 14);
contentPane.add(lblNewLabel_6);
JLabel lblNewLabel_7 = new JLabel("PostCode");
lblNewLabel_7.setBounds(329, 54, 46, 14);
contentPane.add(lblNewLabel_7);
JButton btnSavenew = new JButton("Save New");
btnSavenew.setEnabled(false);
JButton btnSaveselected = new JButton ("Save Selected");
JButton btnDeleteselected = new JButton("Delete selected");
JButton btnRefresh = new JButton("Refresh ");
JButton btnAddNew = new JButton("Add New");
JButton btUpdate = new JButton("Update");
JButton btnMaineMenu = new JButton("Main Menu");
btnAddNew.setBounds(450, 21, 106, 23);
contentPane.add(btnAddNew);
btnSavenew.setBounds(450, 45, 106, 23);
contentPane.add(btnSavenew);
btnDeleteselected.setBounds(449, 185, 107, 23);
contentPane.add(btnDeleteselected);
btnRefresh.setBounds(450, 211, 106, 23);
contentPane.add(btnRefresh);
btnSaveselected.setBounds(450, 125, 106, 23);
contentPane.add(btnSaveselected);
btUpdate.setBounds(450, 102, 106, 23);
contentPane.add(btUpdate);
btnAddNew.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
btnSavenew.setEnabled(true);
btnSaveselected.setEnabled(false);
btnDeleteselected.setEnabled(false);
btnRefresh.setEnabled(false);
btnAddNew.setEnabled(false);
btUpdate.setEnabled(false);
}
});
btnSavenew.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String Fname =tbFname.getText();
String Lname =tbLname.getText();
String Email =tbEmail.getText();
String Tel =tbTelephone.getText();
String Address1 =tbAddress1.getText();
String Address2 =tbAddress2.getText();
String City =tbCity.getText();
String PostCode =tbPostCode.getText();
d.AddPersonal(Fname, Lname, Email, Tel, Address1, Address2, City, PostCode);
table.setModel(DbUtils.resultSetToTableModel(d.GetAllPersonal()));
btnSaveselected.setEnabled(false);
btnDeleteselected.setEnabled(true);
btnSavenew.setEnabled(false);
btnRefresh.setEnabled(true);
btnAddNew.setEnabled(true);
btUpdate.setEnabled(true);
}
});
btUpdate.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
btnSaveselected.setEnabled(true);
btnDeleteselected.setEnabled(false);
btnSavenew.setEnabled(false);
btnRefresh.setEnabled(false);
btnAddNew.setEnabled(false);
btUpdate.setEnabled(false);
}
});
btnSaveselected.setEnabled(false);
btnMaineMenu.setBounds(450, 263, 106, 23);
contentPane.add(btnMaineMenu);
btnSaveselected.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String Fname =tbFname.getText();
String Lname =tbLname.getText();
String Email =tbEmail.getText();
String Tel =tbTelephone.getText();
String Address1 =tbAddress1.getText();
String Address2 =tbAddress2.getText();
String City =tbCity.getText();
String PostCode =tbPostCode.getText();
String id =table.getValueAt(table.getSelectedRow(), 0). toString();
d.UpdatePersonal(Fname, Lname, Email, Tel, Address1, Address2, City, PostCode, id);
table.setModel(DbUtils.resultSetToTableModel(d.GetAllPersonal()));
btnSaveselected.setEnabled(false);
btnDeleteselected.setEnabled(true);
btnSavenew.setEnabled(false);
btnRefresh.setEnabled(true);
btnAddNew.setEnabled(true);
btUpdate.setEnabled(true);
}
});
btnRefresh.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
table.setModel(DbUtils.resultSetToTableModel(d.GetAllPersonal()));
}
});
btnDeleteselected.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int id = Integer.parseInt(table.getValueAt(table.getSelectedRow(), 0).toString());
d.DeletePersonal(id);
table.setModel(DbUtils.resultSetToTableModel(d.GetAllPersonal()));
tbFname.setText("");
tbLname.setText("");
tbEmail.setText("");
tbAddress1.setText("");
tbAddress2.setText("");
tbCity.setText("");
tbPostCode.setText("");
tbTelephone.setText("");
}
});
btnMaineMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
dispose();
}
});
}
}
|
Rust | UTF-8 | 1,761 | 3.25 | 3 | [
"MIT"
] | permissive | //! Provides an interface for smoothly changing values over time.
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT_PARAMETER_INDEX: AtomicUsize = AtomicUsize::new(0);
/// Represents a movement of one value to another over time.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Tween(pub f64);
/**
A unique identifier for a `Parameter`.
You cannot create this manually - a `ParameterId` is created
when you create a parameter with an `AudioManager`.
*/
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct ParameterId {
index: usize,
}
impl ParameterId {
pub(crate) fn new() -> Self {
let index = NEXT_PARAMETER_INDEX.fetch_add(1, Ordering::Relaxed);
Self { index }
}
}
#[derive(Debug, Clone)]
struct TweenState {
tween: Tween,
start: f64,
target: f64,
progress: f64,
}
#[derive(Debug, Clone)]
pub(crate) struct Parameter {
value: f64,
tween_state: Option<TweenState>,
}
impl Parameter {
pub fn new(value: f64) -> Self {
Self {
value,
tween_state: None,
}
}
pub fn value(&self) -> f64 {
self.value
}
pub fn set(&mut self, target: f64, tween: Option<Tween>) {
if let Some(tween) = tween {
self.tween_state = Some(TweenState {
tween,
start: self.value,
target: target,
progress: 0.0,
});
} else {
self.value = target;
}
}
pub fn update(&mut self, dt: f64) -> bool {
if let Some(tween_state) = &mut self.tween_state {
let duration = tween_state.tween.0;
tween_state.progress += dt / duration;
tween_state.progress = tween_state.progress.min(1.0);
self.value =
tween_state.start + (tween_state.target - tween_state.start) * tween_state.progress;
if tween_state.progress >= 1.0 {
self.tween_state = None;
return true;
}
}
false
}
}
|
JavaScript | UTF-8 | 891 | 4.40625 | 4 | [] | no_license | // Given a linked list, remove the n-th node from the end of list and return its head.
class ListNode {
constructor(val){
this.val = val;
this.next = null;
}
};
const removeNthFromEnd = (head, n) => {
let counter = 0;
let first = head;
// get number of nodes in linked list
for (let node = first; node.next !== null; node = node.next){
counter += 1
}
const nodeIndex = counter - n + 1
let counter2 = 0;
for (let node = first; node.next !== null; node = node.next){
if (counter2 + 1 === nodeIndex){
node.next = node.next.next
return head
}
counter2 += 1;
}
};
n1 = new ListNode(1)
n2 = new ListNode(2)
n3 = new ListNode(3)
n4 = new ListNode(4)
n5 = new ListNode(5)
n6 = new ListNode(6)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6 |
Java | UTF-8 | 1,620 | 3.84375 | 4 | [] | no_license | package exercises.m03;
import java.util.Scanner;
public class GradeScorer {
static String[] scores;
static int highestScore = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of students:");
int students = Integer.parseInt(scanner.nextLine());
System.out.println("Enter " + students + " scores:");
scores = scanner.nextLine().split(" ");
scanner.close();
for(int i = 0; i < students; i++) {
int score = Integer.parseInt(scores[i]);
if (score > highestScore) {
highestScore = score;
}
}
calculateGrades();
}
public static void calculateGrades() {
for(int i = 0; i < scores.length; i++) {
int score = Integer.parseInt(scores[i]);
int pointsOff = score - highestScore;
if (pointsOff == 0) {
System.out.println("student " + i + "'s score is " + score + " and grade is A");
} else if (-10 <= pointsOff && pointsOff <= 0) {
System.out.println("student " + i + "'s score is " + score + " and grade is A");
} else if (-20 <= pointsOff && pointsOff <= -10) {
System.out.println("student " + i + "'s score is " + score + " and grade is B");
} else if (-30 <= pointsOff && pointsOff <= -20) {
System.out.println("student " + i + "'s score is " + score + " and grade is C");
} else if (-40 <= pointsOff && pointsOff <= -30) {
System.out.println("student " + i + "'s score is " + score + " and grade is D");
} else {
System.out.println("student " + i + "'s score is " + score + " and grade is F");
}
}
}
}
|
Shell | UTF-8 | 69,532 | 2.890625 | 3 | [] | no_license | #!/bin/bash
# Please Create a user Other than root before running this script!
# ************************************************* Settings *****************************************
# Settings to decide which protocol to install
STRONGSWAN=true
OPENCONNECT=true
SHADOWSOCKS=true
SHADOWSOCKSR=true
# Settings for system and certbot
ENABLE_ICMP=true # Server will response to ICMP(ping) request
SECURE_SSH=true # Will disable root login via ssh, make sure you have another sudo account
AUTO_UPGRADE=false # auto_upgrade will reboot system based on new updates requirement, recommand false for industry usage
SSH_PORT=22 # Used to set firewall
SSH_ACCEPT_IP="192.168.1.0/24
10.0.0.0/24" # Will only accept ssh request from these address space
# Settings for STRONGSWAN
STRONGSWAN_VPN_IPPOOL="10.10.10.0/24"
STRONGSWAN_IKE="aes256gcm16-sha256-ecp521, aes256-sha256-ecp384, 3des-sha1-modp1024!"
STRONGSWAN_ESP="aes256gcm16-sha256, aes256gcm16-ecp384, 3des-sha1-modp1024!" # iOS/Mac uses AES_GCM_16_256/PRF_HMAC_SHA2_256/ECP_521
# Windows 10 uses AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/ECP_384
# Windows 7 uses 3des-sha1-modp1024
# Settings for OPENCONNECT
OC_VPN_IPPOOL="10.10.11.0/24"
OC_INSTALL_FROM_SOURCE=true
OC_VERSION="" # Specify the OpenConnect Version to Install e.g. 0.10.11, install latest if left empty
OC_PORT=443 # Same port for both UDP and TCP, default is the port for https
OC_USE_UDP=false # Disable UDP might be helpful to fix unstable connection
# Settings for SHADOWSOCKS
LIBSODIUM_DOWNLOAD="https://github.com/jedisct1/libsodium/releases/download/1.0.16/libsodium-1.0.16.tar.gz"
SS_PYTHON_DOWNLOAD="https://github.com/shadowsocks/shadowsocks/archive/master.tar.gz" # Another version: "https://github.com/shadowsocks/shadowsocks/archive/2.9.1.tar.gz"
SS_PYTHON_PORT_START=20000
SS_PYTHON_PORT_END=21000
SS_PYTHON_CIPHER=aes-256-gcm # Options: aes-256-gcm, aes-192-gcm, aes-128-gcm,
# aes-256-ctr, aes-192-ctr, aes-128-ctr,
# aes-256-cfb, aes-192-cfb, aes-128-cfb,
# camellia-128-cfb, camellia-192-cfb, camellia-256-cfb,
# xchacha20-ietf-poly1305, chacha20-ietf-poly1305, chacha20-ietf, chacha20,
# salsa20, rc4-md5
# Settings for SHADOWSOCKSR
SSR_DOWNLOAD="https://github.com/shadowsocksrr/shadowsocksr/archive/3.2.2.tar.gz"
SSR_PORT_START=30000
SSR_PORT_END=31000
SSR_CIPHER=aes-256-cfb # Options: aes-256-cfb, aes-192-cfb, aes-128-cfb,
# aes-256-cfb8, aes-192-cfb8, aes-128-cfb8,
# aes-256-ctr, aes-192-ctr, aes-128-ctr,
# chacha20-ietf, chacha20, xchacha20,
# salsa20, xsalsa20, rc4-md5
SSR_PROTOCOL=auth_aes128_md5 # Options: auth_chain_a, auth_chain_b, auth_chain_c, auth_chain_d, auth_chain_e, auth_chain_f,
# auth_aes128_md5, auth_aes128_sha1,
# auth_sha1_v4, auth_sha1_v4_compatible
# verify_deflate, origin
SSR_OBFS=tls1.2_ticket_auth_compatible # Options: plain,
# http_simple, http_simple_compatible, http_post, http_post_compatible,
# tls1.2_ticket_auth, tls1.2_ticket_auth_compatible,
# tls1.2_ticket_fastauth, tls1.2_ticket_fastauth_compatible
# ******************************************** End of Settings *********************************************
# Some Global Variables
INSTALL_VPN=false
UNINSTALL_VPN=false
SCRIPT_DIR="$(cd "$(dirname $0)"; pwd)"
LOG_DIR="${SCRIPT_DIR}/ScriptLog.log"
echo "Detailed Info Recorded in log file: $LOG_DIR" && echo "*** SYSTEM: $(uname -a)" > $LOG_DIR && echo "*** Ubuntu: $(sed 's/\\n\ \\l//g' /etc/issue)" >> $LOG_DIR # Create Log file
# Some help functions and global settings
F_RED='\033[0;31m'
F_GRN='\033[0;32m'
F_YLW='\033[1;33m'
F_BLU='\033[0;34m'
F_WHT='\033[0m'
echo_colored(){
echo -e "$1$2${F_WHT}"
}
echo_red(){
echo_colored ${F_RED} "$1"
}
echo_blue(){
echo_colored ${F_BLU} "$1"
}
echo_green(){
echo_colored ${F_GRN} "$1"
}
echo_yellow(){
echo_colored ${F_YLW} "$1"
}
echo_white(){
echo_colored ${F_WHT} "$1"
}
exception(){
echo "*** Error: $1" >> $LOG_DIR
echo_red "Error: $1"; exit 1
}
warning(){
echo "$1" >> $LOG_DIR
echo_yellow "*** Warning: $1"
}
info(){
echo "*** Info: $1" >> $LOG_DIR
echo_green "$1"
}
info_highlight(){
echo "*** Info: $1 $2" >> $LOG_DIR
echo -e "${F_GRN}$1${F_YLW}$2${F_WHT}"
}
trim() {
expand | awk 'NR == 1 {match($0, /^ */); l = RLENGTH + 1}
{print substr($0, l)}'
} # used to trim multiline strings based on first line
apt_install() {
for Package in $1; do apt -q=2 install -y $Package >> $LOG_DIR 2>&1 ; done
} # Install packages silently
apt_remove() {
for Package in $1; do apt -q=2 autoremove -y $Package >> $LOG_DIR 2>&1 ; done
}
apt_install_together() {
apt -q=2 install -y $1 >> $LOG_DIR 2>&1
}
decompress() {
# Accept two inputs, first one should be path to compressed file, second one should be target directory
[[ -d $2 ]] && [[ ! -n "$(find "$2" -maxdepth 0 -type d -empty 2>/dev/null)" ]] && warning "In decompression, path $2 already exist and not empty, will delete it"
mkdir -p $2
if [[ $1 = *.tar.gz ]]; then
tar -zxf $1 -C $2 --strip-components=1
elif [[ $1 = *.zip ]]; then
rm -rf $2
unzip $1 -d ./decompress_temp
if [[ $(find ./decompress_temp -mindepth 1 -maxdepth 1 -type d | wc -l) = 1 ]]; then
mv $(find ./decompress_temp -mindepth 1 -maxdepth 1 -type d) $2
else
mv ./decompress_temp $2
fi
rm -rf ./decompress_temp
else
exception "Unknown file type, only support tar.gz, zip"
exit 1
fi
}
# End of help functions and global settings
# Parse command
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
install|-i|--install)
INSTALL_VPN=true
shift
;;
uninstall|-u|--uninstall)
UNINSTALL_VPN=true
shift
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
set -- "${POSITIONAL[@]}"
if [[ -n $1 ]]; then
warning "Unknown arguments detected: $1"
fi
if [[ $INSTALL_VPN = false ]] && [[ $UNINSTALL_VPN = false ]]; then
warning "Missing operation. Setting default process to installation"
INSTALL_VPN=true
fi
# End of Parse Command
# Self Checking: Access Checking and Command Checking
info "Runing System Test..."
apt_install "language-pack-en moreutils" # Some Basic tools
[[ $(id -u) -eq 0 ]] || exception "Require sudo access, rerun as root. (e.g. sudo /path/to/this/script)" # Require sudo access
[[ -f /etc/debian_version ]] || exception "Only for Debian(Ubuntu) System" # Check System is Ubuntu
[[ $(lsb_release -rs | tr -cd '[[:digit:]]' ) -ge "1604" ]] || exception "Please use Ubuntu 16.04 or later" # Check 16.04 or later Ubuntu
[[ $INSTALL_VPN != $UNINSTALL_VPN ]] || exception "Confict Command. Specify what you want to do." # Cannot install and uninstall at same time
[[ -e /dev/net/tun ]] || exception "Network TUNnel and TAP not supported in this machine" # Tunnel availiable Checking
INTERFACE=$(ip route get 8.8.8.8 | awk -- '{printf $5}') # Get Interface related information
INTERFACE_IP=$(ifdata -pa $INTERFACE)
info "System Test...Passed"
# Installation Process
if [[ $INSTALL_VPN = true ]]; then
[[ $STRONGSWAN = true ]] || [[ $OPENCONNECT = true ]] || [[ $SHADOWSOCKS = true ]] || [[ $SHADOWSOCKSR = true ]] || exception "No VPN selected"
# Some Basic info for later processing
info "** Please input hostname for Let's Encrypt certificate"
DEFAULT_VPNHOST=${INTERFACE_IP}.sslip.io
read -p "Hostname(e.g. vpn.com, default: ${DEAFULT_VPNHOST}): " VPN_HOST
IP_REGEX='^((2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)\.){3}(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)$'
if [[ $VPN_HOST =~ $IP_REGEX ]]
then
# If is IP address given, append sslip.io to it
VPN_HOSTNAME=${VPN_HOST}.sslip.io
else
VPN_HOSTNAME=$VPN_HOST
fi
VPN_HOSTNAME=${VPN_HOSTNAME:-$DEFAULT_VPNHOST}
VPN_HOSTIP=$(dig -4 +short "$VPN_HOSTNAME")
[[ -n "$VPN_HOSTIP" ]] || exception "Connot resolve VPN hostname"
if [[ "$INTERFACE_IP" != "$VPN_HOSTIP" ]] ; then # Check hostIP equals to interfaceIP
warning "$VPN_HOST resolves to HOSTIP $VPN_HOSTIP, which is not same as INTERFACE_IP $INTERFACE_IP. If set StrongSwan behind NAT, VPN might not work. "
fi
info "** Please input your email for Let's Encrypt Certificate, this will also be used as default admin account for VPNs **"
read -p "Email(e.g. example@email.com): " ADMIN_EMAIL
# Install Checking
info "Start Installation Prerequisite Checking, this might take a long time..."
export DEBIAN_FRONTEND=noninteractive # Update apt and set ubuntu to noninteractive mode
apt_install "software-properties-common"
add-apt-repository -y universe >> $LOG_DIR 2>&1
add-apt-repository -y restricted >> $LOG_DIR 2>&1
add-apt-repository -y multiverse >> $LOG_DIR 2>&1
add-apt-repository -y ppa:certbot/certbot >> $LOG_DIR 2>&1
apt -q=2 -o Acquire::ForceIPv4=true update >> $LOG_DIR 2>&1
apt -q=2 -y upgrade >> $LOG_DIR 2>&1
apt_install "curl wget vim sed gawk insserv dnsutils tar xz-utils unzip"
if [[ -f /etc/letsencrypt/cli.ini ]]; then
warning "Old settings for Let's Encrypt detected, please be careful..."
apt_install "iptables-persistent unattended-upgrades"
apt -q=2 -y install certbot
else
apt_install "iptables-persistent unattended-upgrades certbot"
fi
info "Removing unused packages..."
apt -q=2 autoremove -y >> $LOG_DIR 2>&1
info_highlight "Network Interface: " "$INTERFACE"
info_highlight "External IP: " "$INTERFACE_IP"
info "Installation Prerequisite Checking...Passed"
# End of Install Checking
# Secure SSH, will restart sshd at the end of this installation
if [[ $SECURE_SSH = true ]]; then
info "Enhance System Security(SSH)..."
sed -r \
-e 's/^#?LoginGraceTime (120|2m)$/LoginGraceTime 30/' \
-e 's/^#?X11Forwarding yes$/X11Forwarding no/' \
-e 's/^#?PermitEmptyPasswords yes$/PermitEmptyPasswords no/' \
-i.original /etc/ssh/sshd_config
# use root to login will be easier for adding user: so leave it there -e 's/^#?PermitRootLogin yes$/PermitRootLogin no/'
grep -Fq "MaxStartups 1" /etc/ssh/sshd_config || echo "MaxStartups 1" >> /etc/ssh/sshd_config
grep -Fq "MaxAuthTries 2" /etc/ssh/sshd_config || echo "MaxAuthTries 2" >> /etc/ssh/sshd_config
grep -Fq "UseDNS no" /etc/ssh/sshd_config || echo "UseDNS no" >> /etc/ssh/sshd_config
info "System Security(SSH)...Level Up"
fi
# Set up auto system upgrade
if [[ $AUTO_UPGRADE = true ]]; then
info "Setting system auto-upgrade..."
sed -r \
-e 's|^//Unattended-Upgrade::MinimalSteps "true";$|Unattended-Upgrade::MinimalSteps "true";|' \
-e 's|^//Unattended-Upgrade::Mail "root";$|Unattended-Upgrade::Mail "root";|' \
-e 's|^//Unattended-Upgrade::Automatic-Reboot "false";$|Unattended-Upgrade::Automatic-Reboot "true";|' \
-e 's|^//Unattended-Upgrade::Remove-Unused-Dependencies "false";|Unattended-Upgrade::Remove-Unused-Dependencies "true";|' \
-e 's|^//Unattended-Upgrade::Automatic-Reboot-Time "02:00";$|Unattended-Upgrade::Automatic-Reboot-Time "03:00";|' \
-i /etc/apt/apt.conf.d/50unattended-upgrades
echo 'APT::Periodic::Update-Package-Lists "1";' > /etc/apt/apt.conf.d/10periodic
echo 'APT::Periodic::Download-Upgradeable-Packages "1";' >> /etc/apt/apt.conf.d/10periodic
echo 'APT::Periodic::AutocleanInterval "7";' >> /etc/apt/apt.conf.d/10periodic
echo 'APT::Periodic::Unattended-Upgrade "1";' >> /etc/apt/apt.conf.d/10periodic
info "System auto-upgrade...On"
fi
# Configure Firewall
info "Configure firewall for system..."
iptables -P INPUT ACCEPT # Change policy on chain to target
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t filter -F # Delete all existing rules
iptables -t nat -F
iptables -t mangle -F
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # accept anything already accepted
iptables -A INPUT -i lo -j ACCEPT # accept anything on loopback interface
iptables -A INPUT -m state --state INVALID -j DROP # Drop invalid packets
if [[ ! $SHADOWSOCKS = true ]] && [[ ! $SHADOWSOCKSR = true ]]; then # Because shadowsocks and shadowsocksr need lots of new connections, loose this restriction
iptables -I INPUT -i $INTERFACE -m state --state NEW -m recent --set # Set limit for repeated request from same IP
iptables -I INPUT -i $INTERFACE -m state --state NEW -m recent --update --seconds 60 --hitcount 30 -j DROP
fi
if [[ $SHADOWSOCKS = true ]]; then
info "Configure firewall rules for Shadowsocks..."
iptables -A INPUT -p tcp -m multiport --dports $SS_PYTHON_PORT_START:$SS_PYTHON_PORT_END -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports $SS_PYTHON_PORT_START:$SS_PYTHON_PORT_END -j ACCEPT
fi
if [[ $SHADOWSOCKSR = true ]]; then
info "Configure firewall rules for shadowsocks_R..."
iptables -A INPUT -p tcp -m multiport --dports $SSR_PORT_START:$SSR_PORT_END -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports $SSR_PORT_START:$SSR_PORT_END -j ACCEPT
fi
if [[ $OPENCONNECT = true ]]; then
info "Configure firewall rules for OpenConnect..."
if [[ $OC_USE_UDP = true ]]; then
iptables -A INPUT -p udp -m udp --dport $OC_PORT -m comment --comment "ocserv-udp" -j ACCEPT
fi
iptables -A INPUT -p tcp -m tcp --dport $OC_PORT -m comment --comment "ocserv-tcp" -j ACCEPT
iptables -A FORWARD -s $OC_VPN_IPPOOL -m comment --comment "ocserv-forward-in" -j ACCEPT
iptables -A FORWARD -d $OC_VPN_IPPOOL -m comment --comment "ocesrv-forward-out" -j ACCEPT
iptables -t mangle -A FORWARD -s $OC_VPN_IPPOOL -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "ocserv-mangle" -j TCPMSS --clamp-mss-to-pmtu # MSS fix
iptables -t nat -A POSTROUTING -s $OC_VPN_IPPOOL ! -d $OC_VPN_IPPOOL -m comment --comment "ocserv-postrouting" -j MASQUERADE
fi
if [[ $STRONGSWAN = true ]]; then
info "Configure firewall rules for StrongSwan..."
iptables -A INPUT -p udp -m udp --dport 500 -j ACCEPT # Accept IPSec/NAT-T for StrongSwan VPN
iptables -A INPUT -p udp -m udp --dport 4500 -j ACCEPT
iptables -A FORWARD --match policy --pol ipsec --dir in --proto esp -s $STRONGSWAN_VPN_IPPOOL -j ACCEPT # Forward VPN traffic anywhere
iptables -A FORWARD --match policy --pol ipsec --dir out --proto esp -d $STRONGSWAN_VPN_IPPOOL -j ACCEPT
iptables -t mangle -A FORWARD --match policy --pol ipsec --dir in -s $STRONGSWAN_VPN_IPPOOL -o $INTERFACE -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360 # Reduce MTU/MSS values for dumb VPN clients
iptables -t nat -A POSTROUTING -s $STRONGSWAN_VPN_IPPOOL -o $INTERFACE -m policy --pol ipsec --dir out -j ACCEPT # Exempt IPsec traffic from Masquerade
iptables -t nat -A POSTROUTING -s $STRONGSWAN_VPN_IPPOOL -o $INTERFACE -m comment --comment "strongswan-postrouting" -j MASQUERADE # Masquerade VPN traffic over interface
fi
if [[ ! $SSH_ACCEPT_IP = "" ]]; then
echo $SSH_ACCEPT_IP |tr ' ' '\n' | while read IP_RANGE ; do iptables -A INPUT -s $IP_RANGE -p tcp -m tcp --dport $SSH_PORT -j ACCEPT ; done # Only accept ssh from certain IP rangse
fi
iptables -A INPUT -p tcp -m tcp --dport $SSH_PORT -j DROP # Close SSH port to void ssh attack
if [[ $ENABLE_ICMP = true ]]; then # Enable ICMP based on settings. So we can use ping to test server
iptables -A INPUT -d $INTERFACE_IP/32 -p icmp -m icmp --icmp-type 8 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -s $INTERFACE_IP/32 -p icmp -m icmp --icmp-type 8 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
fi
iptables -A INPUT -j DROP # Deny all other requests
iptables -A FORWARD -j DROP
info "Firewall Configuration...Done"
# End of Firewall Configure
# Save Firewall Settings
info "Persist Firwall Configuration..."
debconf-set-selections <<< "iptables-persistent iptables-persistent/autosave_v4 boolean true"
debconf-set-selections <<< "iptables-persistent iptables-persistent/autosave_v6 boolean true"
dpkg-reconfigure iptables-persistent
info "Firewall Settings Saved"
# Configure Let's Encrypt
info "Applying for Let's Encrypt Certificate..."
mkdir -p /etc/letsencrypt # Configure Let's Encrypt RSA certificate
trim << EOF > /etc/letsencrypt/cli.ini
rsa-key-size = 4096
pre-hook = /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
post-hook = /sbin/iptables -D INPUT -p tcp --dport 80 -j ACCEPT
EOF
certbot certonly --non-interactive --agree-tos --standalone --preferred-challenges http --email $ADMIN_EMAIL -d $VPN_HOSTNAME >> $LOG_DIR 2>&1
grep -Fq "* * * * 7 root certbot -q renew" /etc/crontab || echo "* * * * 7 root certbot -q renew" >> /etc/crontab # Set up autorenew
info "Let's Encrypt Certificate Applied"
# Set net, including ip_forward etc.
info "Configure System Network and IP Forward"
grep -Fq "net.ipv4.ip_forward = 1" /etc/sysctl.conf || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf # for VPN
grep -Fq "net.ipv4.ip_no_pmtu_disc = 1" /etc/sysctl.conf || echo "net.ipv4.ip_no_pmtu_disc = 1" >> /etc/sysctl.conf # for UDP fragmentation
grep -Fq "net.ipv4.conf.all.rp_filter = 1" /etc/sysctl.conf || echo "net.ipv4.conf.all.rp_filter = 1" >> /etc/sysctl.conf # for security
grep -Fq "net.ipv4.conf.all.accept_redirects = 0" /etc/sysctl.conf || echo "net.ipv4.conf.all.accept_redirects = 0" >> /etc/sysctl.conf
grep -Fq "net.ipv4.conf.all.send_redirects = 0" /etc/sysctl.conf || echo "net.ipv4.conf.all.send_redirects = 0" >> /etc/sysctl.conf
grep -Fq "net.ipv6.conf.all.disable_ipv6 = 1" /etc/sysctl.conf || echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
grep -Fq "net.ipv6.conf.default.disable_ipv6 = 1" /etc/sysctl.conf || echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.conf
grep -Fq "net.ipv6.conf.lo.disable_ipv6 = 1" /etc/sysctl.conf || echo "net.ipv6.conf.lo.disable_ipv6 = 1" >> /etc/sysctl.conf
# If we have kernel 4.9+, we can use bbr to speed up VPN
# grep -Fq "net.core.default_qdisc = fq" /etc/sysctl.conf || echo "net.core.default_qdisc = fq" >> /etc/sysctl.conf
# grep -Fq "net.ipv4.tcp_congestion_control = bbr" /etc/sysctl.conf || echo "net.ipv4.tcp_congestion_control = bbr" >> /etc/sysctl.conf
sysctl -p >> $LOG_DIR 2>&1
info "System Network Configuration...Done"
# STRONGSWAN Installation
if [[ $STRONGSWAN = true ]]; then
info "Installing StrongSwan..."
# Install StrongSwan
apt_install "strongswan strongswan-starter libstrongswan-standard-plugins strongswan-libcharon libcharon-extra-plugins libstrongswan-extra-plugins" >> $LOG_DIR 2>&1
# remember to add ipsec renew after
grep -Eq "renew-hook.*=.*" /etc/letsencrypt/cli.ini \
|| echo "renew-hook = " | tee --append /etc/letsencrypt/cli.ini > /dev/null \
&& ( grep -Eq "renew-hook.*/usr/sbin/ipsec reload && /usr/sbin/ipsec secret" /etc/letsencrypt/cli.ini || sed -e '/^renew-hook.*/s_$_ \&\& /usr/sbin/ipsec reload \&\& /usr/sbin/ipsec secret_' -i /etc/letsencrypt/cli.ini ) \
&& (sed -e 's/=\ *&&/= /' -i /etc/letsencrypt/cli.ini)
# Set up apparmor for letsencrypt -> ipsec
grep -Fq "letsencrypt/archive/$VPN_HOSTNAME" /etc/apparmor.d/local/usr.lib.ipsec.charon || echo "/etc/letsencrypt/archive/$VPN_HOSTNAME/* r," >> /etc/apparmor.d/local/usr.lib.ipsec.charon # Make sure this line is in apparmor
aa-status --enabled && invoke-rc.d apparmor reload # Start apparmor
# Link certs
info "Linking Certificates for StrongSwan..."
ln -f -s /etc/letsencrypt/live/$VPN_HOSTNAME/cert.pem /etc/ipsec.d/certs/cert.pem
ln -f -s /etc/letsencrypt/live/$VPN_HOSTNAME/privkey.pem /etc/ipsec.d/private/privkey.pem
ln -f -s /etc/letsencrypt/live/$VPN_HOSTNAME/chain.pem /etc/ipsec.d/cacerts/chain.pem
# StrongSwan Settings: ipsec.conf
info "Prepare conf file for StrongSwan..."
echo "config setup" > /etc/ipsec.conf
echo " strictcrlpolicy=yes" >> /etc/ipsec.conf
echo " uniqueids=yes" >> /etc/ipsec.conf
echo "conn roadwarrior" >> /etc/ipsec.conf
echo " auto=add" >> /etc/ipsec.conf
echo " compress=no" >> /etc/ipsec.conf
echo " type=tunnel" >> /etc/ipsec.conf
echo " keyexchange=ikev2" >> /etc/ipsec.conf
echo " fragmentation=yes" >> /etc/ipsec.conf
echo " forceencaps=yes" >> /etc/ipsec.conf
echo " ike=$STRONGSWAN_IKE" >> /etc/ipsec.conf
echo " esp=$STRONGSWAN_ESP" >> /etc/ipsec.conf
echo " dpdaction=clear" >> /etc/ipsec.conf
echo " dpddelay=900s" >> /etc/ipsec.conf
echo " rekey=no" >> /etc/ipsec.conf
echo " left=%any" >> /etc/ipsec.conf
echo " leftid=@${VPN_HOSTNAME}" >> /etc/ipsec.conf
echo " leftcert=cert.pem" >> /etc/ipsec.conf
echo " leftsendcert=always" >> /etc/ipsec.conf
echo " leftsubnet=0.0.0.0/0" >> /etc/ipsec.conf
echo " right=%any" >> /etc/ipsec.conf
echo " rightid=%any" >> /etc/ipsec.conf
echo " rightauth=eap-mschapv2" >> /etc/ipsec.conf
echo " eap_identity=%any" >> /etc/ipsec.conf
echo " rightdns=8.8.8.8, 8.8.4.4" >> /etc/ipsec.conf
echo " rightsourceip=${STRONGSWAN_VPN_IPPOOL}" >> /etc/ipsec.conf
echo " rightsendcert=never" >> /etc/ipsec.conf
# StrongSwan Settings: ipsec.secrets
echo "${VPN_HOSTNAME} : RSA \"privkey.pem\"" > /etc/ipsec.secrets
echo "${ADMIN_EMAIL} : EAP \"${ADMIN_EMAIL}\"" >> /etc/ipsec.secrets
# Restart StrongSwan.
ipsec restart >> $LOG_DIR 2>&1
# End of StrongSwan Server Configure, Prepare for client settings
info "Generating StrongSwan Client Settings..."
mkdir -p ${SCRIPT_DIR}/StrongSwan_Clients/
info "Setting StrongSwan Script for iOS & MAC"
trim << EOF > ${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_iOS_macOS.mobileconfig
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN' 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'>
<plist version='1.0'>
<dict>
<key>PayloadContent</key>
<array>
<dict>
<key>IKEv2</key>
<dict>
<key>AuthenticationMethod</key>
<string>None</string>
<key>ChildSecurityAssociationParameters</key>
<dict>
<key>EncryptionAlgorithm</key>
<string>AES-256-GCM</string>
<key>IntegrityAlgorithm</key>
<string>SHA2-256</string>
<key>DiffieHellmanGroup</key>
<integer>21</integer>
<key>LifeTimeInMinutes</key>
<integer>1440</integer>
</dict>
<key>DeadPeerDetectionRate</key>
<string>Medium</string>
<key>DisableMOBIKE</key>
<integer>0</integer>
<key>DisableRedirect</key>
<integer>0</integer>
<key>EnableCertificateRevocationCheck</key>
<integer>0</integer>
<key>EnablePFS</key>
<true/>
<key>ExtendedAuthEnabled</key>
<true/>
<key>IKESecurityAssociationParameters</key>
<dict>
<key>EncryptionAlgorithm</key>
<string>AES-256-GCM</string>
<key>IntegrityAlgorithm</key>
<string>SHA2-256</string>
<key>DiffieHellmanGroup</key>
<integer>21</integer>
<key>LifeTimeInMinutes</key>
<integer>1440</integer>
</dict>
<key>LocalIdentifier</key>
<string>${VPN_HOSTNAME}</string>
<key>OnDemandEnabled</key>
<integer>0</integer>
<key>OnDemandRules</key>
<array>
<dict>
<key>Action</key>
<string>Connect</string>
</dict>
</array>
<key>RemoteAddress</key>
<string>${VPN_HOSTNAME}</string>
<key>RemoteIdentifier</key>
<string>${VPN_HOSTNAME}</string>
<key>UseConfigurationAttributeInternalIPSubnet</key>
<integer>0</integer>
</dict>
<key>IPv4</key>
<dict>
<key>OverridePrimary</key>
<integer>1</integer>
</dict>
<key>PayloadDescription</key>
<string>Configures VPN settings</string>
<key>PayloadDisplayName</key>
<string>VPN</string>
<key>PayloadIdentifier</key>
<string>com.apple.vpn.managed.$(uuidgen)</string>
<key>PayloadType</key>
<string>com.apple.vpn.managed</string>
<key>PayloadUUID</key>
<string>$(uuidgen)</string>
<key>PayloadVersion</key>
<integer>1</integer>
<key>Proxies</key>
<dict>
<key>HTTPEnable</key>
<integer>0</integer>
<key>HTTPSEnable</key>
<integer>0</integer>
</dict>
<key>UserDefinedName</key>
<string>${VPN_HOSTNAME}</string>
<key>VPNType</key>
<string>IKEv2</string>
</dict>
</array>
<key>PayloadDisplayName</key>
<string>IKEv2 VPN configuration (${VPN_HOSTNAME})</string>
<key>PayloadIdentifier</key>
<string>com.mackerron.vpn.$(uuidgen)</string>
<key>PayloadRemovalDisallowed</key>
<false/>
<key>PayloadType</key>
<string>Configuration</string>
<key>PayloadUUID</key>
<string>$(uuidgen)</string>
<key>PayloadVersion</key>
<integer>1</integer>
</dict>
</plist>
EOF
info "Setting StrongSwan Script for Ubuntu"
trim << EOF > ${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_Ubuntu.sh
#!/bin/bash -e
if [[ \$(id -u) -ne 0 ]]; then echo "Please run as root (e.g. sudo ./path/to/this/script)"; exit 1; fi
read -p "VPN username (same as entered on server): " VPNUSERNAME
while true; do
read -s -p "VPN password (same as entered on server): " VPNPASSWORD
echo
read -s -p "Confirm VPN password: " VPNPASSWORD2
echo
[ "\$VPNPASSWORD" = "\$VPNPASSWORD2" ] && break
echo "Passwords didn't match -- please try again"
done
apt-get install -y strongswan libstrongswan-standard-plugins libcharon-extra-plugins
apt-get install -y libcharon-standard-plugins || true # 17.04+ only
ln -f -s /etc/ssl/certs/DST_Root_CA_X3.pem /etc/ipsec.d/cacerts/
grep -Fq 'jawj/IKEv2-setup' /etc/ipsec.conf || echo "
# https://github.com/jawj/IKEv2-setup
conn ikev2vpn
ikelifetime=60m
keylife=20m
rekeymargin=3m
keyingtries=1
keyexchange=ikev2
ike=aes256gcm16-sha256-ecp521!
esp=aes256gcm16-sha256!
leftsourceip=%config
leftauth=eap-mschapv2
eap_identity=\${VPNUSERNAME}
right=${VPN_HOSTNAME}
rightauth=pubkey
rightid=@${VPN_HOSTNAME}
rightsubnet=0.0.0.0/0
auto=add # or auto=start to bring up automatically
" >> /etc/ipsec.conf
grep -Fq 'jawj/IKEv2-setup' /etc/ipsec.secrets || echo "
# https://github.com/jawj/IKEv2-setup
\${VPNUSERNAME} : EAP \"\${VPNPASSWORD}\"
" >> /etc/ipsec.secrets
ipsec restart
sleep 5 # is there a better way?
echo "Bringing up VPN ..."
ipsec up ikev2vpn
ipsec statusall
echo
echo -n "Testing IP address ... "
VPNIP=\$(dig -4 +short ${VPN_HOSTNAME})
ACTUALIP=\$(curl -s ifconfig.co)
if [[ "\$VPNIP" == "\$ACTUALIP" ]]; then echo "PASSED (IP: \${VPNIP})"; else echo "FAILED (IP: \${ACTUALIP}, VPN IP: \${VPNIP})"; fi
echo
echo "To disconnect: ipsec down ikev2vpn"
echo "To resconnect: ipsec up ikev2vpn"
echo "To connect automatically: change auto=add to auto=start in /etc/ipsec.conf"
EOF
info "Setting StrongSwan Script for Windows 10"
trim << EOF > ${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_Win10.ps1
Add-VpnConnection -Name "${VPN_HOSTNAME}" -ServerAddress "${VPN_HOSTNAME}" -TunnelType IKEv2 -EncryptionLevel Maximum -AuthenticationMethod EAP
Set-VpnConnectionIPsecConfiguration -ConnectionName "${VPN_HOSTNAME}" -AuthenticationTransformConstants GCMAES256 -CipherTransformConstants GCMAES256 -EncryptionMethod AES256 -IntegrityCheckMethod SHA256 -DHGroup ECP384 -PfsGroup ECP384 -Force
EOF
info "StrongSwan Installation...Done"
fi # End of StrongSwan Installation
# OpenConnect Installation
if [[ $OPENCONNECT = true ]]; then
info "Installing OpenConnect..."
# Install ocserv dependencies
info "Solving OpenConnect Dependencies, this will take a while..."
apt_install "openssl autogen automake gperf pkg-config make gcc m4 build-essential"
apt_install "libgmp3-dev libwrap0-dev libpam0g-dev libdbus-1-dev libnl-route-3-dev libopts25-dev libnl-nf-3-dev libreadline-dev libpcl1-dev libtalloc-dev libev-dev liboath-dev nettle-dev libseccomp-dev liblz4-dev libgeoip-dev libkrb5-dev libradcli-dev libgnutls28-dev gnutls-bin protobuf-c-compiler"
info "OpenConnect Dependencies Installed"
info "Checking and downloading source package from official website"
if [[ $OC_INSTALL_FROM_SOURCE = true ]]; then
# Download source package from official website and compile it
mkdir -p ${SCRIPT_DIR}/ocserv_install_temp
Ocserv_Install=${SCRIPT_DIR}/ocserv_install_temp
[[ $OC_VERSION = "" ]] && {
OC_VERSION=$(curl -sL "https://ocserv.gitlab.io/www/download.html" | sed -n 's/^.*The latest released version is <b>\(.*$\)/\1/p')
[[ $OC_VERSION = "" ]] && exception "Cannot get OpenConnect Latest Version Info from official website"
}
wget --quiet -c ftp://ftp.infradead.org/pub/ocserv/ocserv-$OC_VERSION.tar.xz >> $LOG_DIR 2>&1
mv -f ${SCRIPT_DIR}/ocserv-$OC_VERSION.tar.xz $Ocserv_Install
mkdir -p $Ocserv_Install/ocserv-$OC_VERSION
tar -xvf $Ocserv_Install/ocserv-$OC_VERSION.tar.xz -C $Ocserv_Install >> $LOG_DIR 2>&1
info "Configure OpenConnect from source..."
# Switch to ocserv directory to configure files
mkdir -p ${Ocserv_Install}/ocserv-${OC_VERSION}/build
cd ${Ocserv_Install}/ocserv-${OC_VERSION}/build
../configure --prefix=/usr --sysconfdir=/etc >> $LOG_DIR 2>&1
info "Install OpenConnect..."
make >> $LOG_DIR 2>&1
make install >> $LOG_DIR 2>&1
cd ${SCRIPT_DIR}
# Switch back and test installation
[[ -f /usr/sbin/ocserv ]] || exception "Ocserv install failure, check log for details" # Check install result
info "OpenConnect Installed"
else
# Install OpenConnect from apt repository, this version might not the latest one
info "Install OpenConnect"
if [[ $OC_VERSION = "" ]]; then
apt_install "ocserv"
else
info "make sure you select existing ocserv version..."
apt policy ocserv
read -p "Give me your choice: " OC_VERSION
apt -q=2 install -y ocserv=$OC_VERSION >> $LOG_DIR 2>&1
fi
info "OpenConnect Installed through apt"
#exception "Please install OpenConnect through source...This part is not tested yet"
fi
# Link certs
info "Linking Certificates for OpenConnect..."
mkdir -p /etc/ocserv/certs
ln -f -s /etc/letsencrypt/live/$VPN_HOSTNAME/cert.pem /etc/ocserv/certs/cert.pem
ln -f -s /etc/letsencrypt/live/$VPN_HOSTNAME/privkey.pem /etc/ocserv/certs/privkey.pem
ln -f -s /etc/letsencrypt/live/$VPN_HOSTNAME/fullchain.pem /etc/ocserv/certs/fullchain.pem
# Start to configure OpenConnect with PAM
info "Configuring OpenConnect..."
mkdir -p ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp
trim << EOF > ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp/ocserv
#!/bin/sh
### BEGIN INIT INFO
# Provides: ocserv
# Required-Start: \$network \$remote_fs \$syslog
# Required-Stop: \$network \$remote_fs \$syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: ocserv
# Description: OpenConnect VPN server compatible with
# Cisco AnyConnect VPN.
### END INIT INFO
# Author: liyangyijie <liyangyijie@gmail.com>
# PATH should only include /usr/ if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=ocserv
NAME=ocserv
DAEMON=/usr/sbin/ocserv
DAEMON_ARGS=""
CONFFILE="/etc/ocserv/ocserv.conf"
PIDFILE=/var/run/\$NAME/\$NAME.pid
SCRIPTNAME=/etc/init.d/\$NAME
# Exit if the package is not installed
[ -x \$DAEMON ] || exit 0
: \${USER:="root"}
: \${GROUP:="root"}
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
# Show details
VERBOSE="yes"
#
# Function that starts the daemon/service
#
do_start()
{
# Take care of pidfile permissions
mkdir /var/run/\$NAME 2>/dev/null || true
chown "\$USER:\$GROUP" /var/run/\$NAME
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
start-stop-daemon --start --quiet --pidfile \$PIDFILE --chuid \$USER:\$GROUP --exec \$DAEMON --test > /dev/null \
|| return 1
start-stop-daemon --start --quiet --pidfile \$PIDFILE --chuid \$USER:\$GROUP --exec \$DAEMON -- \
-c "\$CONFFILE" \$DAEMON_ARGS \
|| return 2
}
#
# Function that stops the daemon/service
#
do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
start-stop-daemon --stop --quiet --retry=KILL/5 --pidfile \$PIDFILE --exec \$DAEMON
RETVAL="\$?"
[ "\$RETVAL" = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=KILL/5 --exec \$DAEMON
[ "\$?" = 2 ] && return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f \$PIDFILE
return "\$RETVAL"
}
case "\$1" in
start)
[ "\$VERBOSE" != no ] && log_daemon_msg "Starting \$DESC " "\$NAME"
do_start
case "\$?" in
0|1) [ "\$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "\$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "\$VERBOSE" != no ] && log_daemon_msg "Stopping \$DESC" "\$NAME"
do_stop
case "\$?" in
0|1) [ "\$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "\$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
debug)
DAEMON_ARGS="-f -d 2"
[ "\$2" != "" ] && DAEMON_ARGS="-f -d \$2"
[ "\$VERBOSE" != no ] && log_daemon_msg "Starting \$DESC " "\$NAME"
do_start
case "\$?" in
0|1) [ "\$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "\$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
status)
status_of_proc "\$DAEMON" "\$NAME" && exit 0 || exit \$?
;;
restart|force-reload)
log_daemon_msg "Restarting \$DESC" "\$NAME"
do_stop
case "\$?" in
0|1)
do_start
case "\$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
echo "Usage: \$SCRIPTNAME {start|stop|status|restart|force-reload|debug}" >&2
exit 3
;;
esac
:
EOF
trim << EOF > ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp/ocserv.conf
auth = "plain[passwd=/etc/ocserv/ocpasswd]"
server-cert = /etc/ocserv/certs/fullchain.pem
server-key = /etc/ocserv/certs/privkey.pem
dh-params = /etc/ocserv/certs/dh.pem
default-domain = ${VPN_HOSTNAME}
tcp-port = 443
udp-port = 443
ipv4-network = 10.10.11.0
ipv4-netmask = 255.255.255.0
dns = 8.8.8.8
dns = 8.8.4.4
run-as-user = nobody
run-as-group = nogroup
socket-file = /var/run/ocserv-socket
isolate-workers = false
max-clients = 256
max-same-clients = 1
mtu = 1200
keepalive = 32400
dpd = 180
mobile-dpd = 1800
try-mtu-discovery = true
compression = true
tls-priorities = "NORMAL:%SERVER_PRECEDENCE:%COMPAT:-VERS-SSL3.0"
auth-timeout = 60
idle-timeout = 1200
mobile-idle-timeout = 1200
max-ban-score = 50
ban-reset-time = 300
cookie-timeout = 86400
deny-roaming = false
rekey-time = 172800
rekey-method = ssl
use-utmp = true
use-occtl = true
pid-file = /var/run/ocserv.pid
device = vpns
predictable-ips = true
ping-leases = false
cisco-client-compat = true
EOF
certtool --generate-dh-params --sec-param medium --outfile ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp/dh.pem >> $LOG_DIR 2>&1
# Move and apply these config files
[[ -f /etc/ocserv/ocserv.conf ]] && mv /etc/ocserv/ocserv.conf /etc/ocserv/ocserv.conf.bak >> $LOG_DIR 2>&1
cp ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp/ocserv.conf /etc/ocserv/ocserv.conf >> $LOG_DIR 2>&1
cp ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp/dh.pem /etc/ocserv/certs/dh.pem >> $LOG_DIR 2>&1
cp ${SCRIPT_DIR}/ocserv_install_temp/config_ocserv_temp/ocserv /etc/init.d/ocserv >> $LOG_DIR 2>&1
chmod 755 /etc/init.d/ocserv
systemctl daemon-reload >> $LOG_DIR 2>&1
# Bootup with system
systemctl enable ocserv >> $LOG_DIR 2>&1 || insserv ocserv >> $LOG_DIR 2>&1
# Edit Conf file based on settings.
# Disable UDP if OC_USE_UDP is set to other values
[[ ! $OC_USE_UDP = true ]] && sed -i 's|^[ \t]*\(udp-port = \)|# \1|' /etc/ocserv/ocserv.conf >> $LOG_DIR 2>&1
# Add User to server
echo "${ADMIN_EMAIL} ${ADMIN_EMAIL}"| tr " " "\n" | ocpasswd -c /etc/ocserv/ocpasswd ${ADMIN_EMAIL}
info "OpenConnect Configuration...Done"
# Set up auto restart for updated certificate
grep -Eq "renew-hook.*=.*" /etc/letsencrypt/cli.ini \
|| echo "renew-hook = " | tee --append /etc/letsencrypt/cli.ini > /dev/null \
&& ( grep -Eq "renew-hook.*/etc/init.d/ocserv restart" /etc/letsencrypt/cli.ini || sed -e '/^renew-hook.*/s_$_ \&\& /etc/init.d/ocserv restart_' -i /etc/letsencrypt/cli.ini ) \
&& (sed -e 's/=\ *&&/= /' -i /etc/letsencrypt/cli.ini)
info "Retart OpenConnect..."
/etc/init.d/ocserv stop >> $LOG_DIR 2>&1
# Force stop if ocserv is still running
Oc_pid=$(pidof ocserv)
if [[ ! -z $Oc_pid ]]; then
for Pid in $Oc_pid
do
kill -9 $Pid >> $LOG_DIR 2>&1
if [[ $? -eq 0 ]]; then
info "Killed running ocserv..."
else
warning "Cannot kill running ocserv..."
fi
done
fi
/etc/init.d/ocserv start >> $LOG_DIR 2>&1
info "OpenConnect restart...Done"
info "Clean OpenConnect Installation..."
rm -rf ${SCRIPT_DIR}/ocserv_install_temp
info "OpenConnect Installation...Done"
fi # End of OpenConnect Installation
# Shadowsocks-Python Installation
if [[ $SHADOWSOCKS = true ]]; then
# Install some necessary packages
mkdir -p /etc/shadowsocks_python >> $LOG_DIR 2>&1
apt_install "python python-dev openssl libssl-dev gcc automake autoconf make libtool"
# Install pip and setuptools if they not ready
wget --no-check-certificate -O ${SCRIPT_DIR}/get-pip.py https://bootstrap.pypa.io/get-pip.py >> $LOG_DIR 2>&1
python ${SCRIPT_DIR}/get-pip.py >> $LOG_DIR 2>&1
rm -rf ${SCRIPT_DIR}/get-pip.py
# Install libsodium
info "Installing libsodium..."
# Download libsodium first
info " Downloading libsodium..."
Libsodium_filename="$(basename ${LIBSODIUM_DOWNLOAD})"
if ! wget --no-check-certificate -O ${SCRIPT_DIR}/${Libsodium_filename} ${LIBSODIUM_DOWNLOAD} >> $LOG_DIR 2>&1; then
exception " Cannot download libsodium for shadowsocks"
fi
info " Done"
if [[ ! -f /usr/lib/libsodium.a ]]; then
info "Installing libsodium..."
decompress ${SCRIPT_DIR}/${Libsodium_filename} ${SCRIPT_DIR}/libsodium_install_temp >> $LOG_DIR 2>&1
mkdir -p ${SCRIPT_DIR}/libsodium_install_temp/build >> $LOG_DIR 2>&1
cd ${SCRIPT_DIR}/libsodium_install_temp/build
../configure --prefix=/usr >> $LOG_DIR 2>&1 && make >> $LOG_DIR 2>&1 && make install >> $LOG_DIR 2>&1
if [[ $? -ne 0 ]]; then
cd ${SCRIPT_DIR}
rm -rf ${SCRIPT_DIR}/${Libsodium_filename} ${SCRIPT_DIR}/libsodium_install_temp
exception "libsodium install failed"
fi
fi
cd ${SCRIPT_DIR}
rm -rf ${SCRIPT_DIR}/libsodium_install_temp ${SCRIPT_DIR}/${Libsodium_filename}
ldconfig >> $LOG_DIR 2>&1
info "Libsodium Installation...Done"
# Install Shadowsocks
info "Installing Shadowsocks_python..."
# Download Shadowsocks-python first
info " Downloading Shadowsocks-python..."
Ss_filename="$(basename ${SS_PYTHON_DOWNLOAD})"
if ! wget --no-check-certificate -O ${SCRIPT_DIR}/${Ss_filename} ${SS_PYTHON_DOWNLOAD} >> $LOG_DIR 2>&1; then
exception " Cannot download shadowsocks"
fi
info " Done"
decompress ${SCRIPT_DIR}/${Ss_filename} ${SCRIPT_DIR}/ss_install_temp >> $LOG_DIR 2>&1
Ss_dir=${SCRIPT_DIR}/ss_install_temp # $(find ${SCRIPT_DIR}/ss_install_temp -maxdepth 1 -mindepth 1 -type d) # There is one more layer for ss source files
cd $Ss_dir
python setup.py install --record /etc/shadowsocks_python/shadowsocks_install.log >> $LOG_DIR 2>&1
if [[ -f /usr/bin/ssserver ]] || [[ -f /usr/local/bin/ssserver ]]; then
cd ${SCRIPT_DIR}
rm -rf ${SCRIPT_DIR}/${Ss_filename} ${SCRIPT_DIR}/ss_install_temp
info "Shadowsocks-python Installation...Done"
else
cd ${SCRIPT_DIR}
rm -rf ${SCRIPT_DIR}/${Ss_filename} ${SCRIPT_DIR}/ss_install_temp
exception "Shadowsocks-python install failed"
fi
# End of Shadowsocks Installation
# Add script for auto-start
trim << EOF > /etc/init.d/shadowsocks_python
#!/bin/bash
### BEGIN INIT INFO
# Provides: Shadowsocks
# Required-Start: \$network \$local_fs \$remote_fs
# Required-Stop: \$network \$local_fs \$remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Fast tunnel proxy that helps you bypass firewalls
# Description: Start or stop the Shadowsocks server
### END INIT INFO
# Author: Teddysun <i@teddysun.com>
NAME=Shadowsocks
if [ -f /usr/bin/ssserver ]; then
DAEMON=/usr/bin/ssserver
elif [ -f /usr/local/bin/ssserver ]; then
DAEMON=/usr/local/bin/ssserver
fi
if [ -f /etc/shadowsocks_python/config.json ]; then
CONF=/etc/shadowsocks_python/config.json
elif [ -f /etc/shadowsocks_python.json ]; then
CONF=/etc/shadowsocks_python.json
fi
RETVAL=0
check_running(){
PID=\$(ps -ef | grep -v grep | grep -i "\${DAEMON}" | awk '{print \$2}')
if [ -n "\$PID" ]; then
return 0
else
return 1
fi
}
do_start(){
check_running
if [ \$? -eq 0 ]; then
echo "\$NAME (pid \$PID) is already running..."
exit 0
else
\$DAEMON -c \$CONF -d start
RETVAL=\$?
if [ \$RETVAL -eq 0 ]; then
echo "Starting \$NAME success"
else
echo "Starting \$NAME failed"
fi
fi
}
do_stop(){
check_running
if [ \$? -eq 0 ]; then
\$DAEMON -c \$CONF -d stop
RETVAL=\$?
if [ \$RETVAL -eq 0 ]; then
echo "Stopping \$NAME success"
else
echo "Stopping \$NAME failed"
fi
else
echo "\$NAME is stopped"
RETVAL=1
fi
}
do_status(){
check_running
if [ \$? -eq 0 ]; then
echo "\$NAME (pid \$PID) is running..."
else
echo "\$NAME is stopped"
RETVAL=1
fi
}
do_restart(){
do_stop
sleep 0.5
do_start
}
case "\$1" in
start|stop|restart|status)
do_\$1
;;
*)
echo "Usage: \$0 { start | stop | restart | status }"
RETVAL=1
;;
esac
exit \$RETVAL
EOF
chmod 755 /etc/init.d/shadowsocks_python
update-rc.d -f shadowsocks_python defaults >> $LOG_DIR 2>&1
# Config shadowsocks
SS_PYTHON_CONFIGFILE=/etc/shadowsocks_python/config.json
trim << EOF > $SS_PYTHON_CONFIGFILE
{
"server":"0.0.0.0",
"local_address":"127.0.0.1",
"local_port":1080,
"port_password":{
"${SS_PYTHON_PORT_START}":"${ADMIN_EMAIL}"
},
"timeout":300,
"method":"${SS_PYTHON_CIPHER}",
"fast_open":false
}
EOF
# restart shadowsocks
info "Starting Shadowsocks..."
/etc/init.d/shadowsocks_python restart >> $LOG_DIR 2>&1
fi # End of Shadowsocks Installation
# SHADOWSOCKS_R Installation
if [[ $SHADOWSOCKSR = true ]]; then
# Pre-install and install some packages
mkdir -p /etc/shadowsocks_r
apt_install "python python-dev python-setuptools openssl automake autoconf make libtool"
# Install libsodium
info "Installing libsodium..."
# Download libsodium first
info " Downloading libsodium..."
Libsodium_filename="$(basename ${LIBSODIUM_DOWNLOAD})"
if ! wget --no-check-certificate -O ${SCRIPT_DIR}/${Libsodium_filename} ${LIBSODIUM_DOWNLOAD} >> $LOG_DIR 2>&1; then
exception " Cannot download libsodium for shadowsocks"
fi
info " Done"
if [[ ! -f /usr/lib/libsodium.a ]]; then
info "Installing libsodium..."
decompress ${SCRIPT_DIR}/${Libsodium_filename} ${SCRIPT_DIR}/libsodium_install_temp >> $LOG_DIR 2>&1
mkdir -p ${SCRIPT_DIR}/libsodium_install_temp/build
cd ${SCRIPT_DIR}/libsodium_install_temp/build
../configure --prefix=/usr >> $LOG_DIR 2>&1 && make >> $LOG_DIR 2>&1 && make install >> $LOG_DIR 2>&1
if [[ $? -ne 0 ]]; then
cd ${SCRIPT_DIR}
rm -rf ${SCRIPT_DIR}/${Libsodium_filename} ${SCRIPT_DIR}/libsodium_install_temp
exception "libsodium install failed"
fi
fi
cd ${SCRIPT_DIR}
rm -rf ${SCRIPT_DIR}/libsodium_install_temp ${SCRIPT_DIR}/${Libsodium_filename}
ldconfig >> $LOG_DIR 2>&1
info "Libsodium Installation...Done"
# Install ShadowsocksR
info "Installing ShadowsocksR..."
# Download ShadowsocksR first
info " Downloading ShadowsocksR..."
Ssr_filename="$(basename ${SSR_DOWNLOAD})"
if ! wget --no-check-certificate -O ${SCRIPT_DIR}/${Ssr_filename} ${SSR_DOWNLOAD} >> $LOG_DIR 2>&1; then
exception " Cannot download shadowsocksr"
fi
info " Done"
decompress ${SCRIPT_DIR}/${Ssr_filename} ${SCRIPT_DIR}/ssr_install_temp >> $LOG_DIR 2>&1
Ssr_dir=${SCRIPT_DIR}/ssr_install_temp
mkdir -p /usr/bin/shadowsocks_r
cp -r ${Ssr_dir}/shadowsocks /usr/bin/shadowsocks_r/shadowsocks >> $LOG_DIR 2>&1 # Be careful, server.py must under directory "shadowsocks"
if [[ ! -f /usr/bin/shadowsocks_r/shadowsocks/server.py ]]; then
rm -rf ${SCRIPT_DIR}/ssr_install_temp
rm -rf ${SCRIPT_DIR}/${Ssr_filename}
exception "Shadowsocks_R Installation failed"
else
rm -rf ${SCRIPT_DIR}/ssr_install_temp
rm -rf ${SCRIPT_DIR}/${Ssr_filename}
info "Shadowsocks_R Installation...Done"
fi
# Config Auto start
trim << EOF > /etc/init.d/shadowsocks_r
#!/bin/bash
### BEGIN INIT INFO
# Provides: ShadowsocksR
# Required-Start: \$network \$local_fs \$remote_fs
# Required-Stop: \$network \$local_fs \$remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Fast tunnel proxy that helps you bypass firewalls
# Description: Start or stop the ShadowsocksR server
### END INIT INFO
# Author: Teddysun <i@teddysun.com>
NAME=ShadowsocksR
DAEMON=/usr/bin/shadowsocks_r/shadowsocks/server.py
if [ -f /etc/shadowsocks_r/config.json ]; then
CONF=/etc/shadowsocks_r/config.json
elif [ -f /etc/shadowsocks_r.json ]; then
CONF=/etc/shadowsocks_r.json
fi
RETVAL=0
check_running(){
PID=\$(ps -ef | grep -v grep | grep -i "\${DAEMON}" | awk '{print \$2}')
if [ -n "\$PID" ]; then
return 0
else
return 1
fi
}
do_start(){
check_running
if [ \$? -eq 0 ]; then
echo "\$NAME (pid \$PID) is already running..."
exit 0
else
\$DAEMON -c \$CONF -d start
RETVAL=\$?
if [ \$RETVAL -eq 0 ]; then
echo "Starting \$NAME success"
else
echo "Starting \$NAME failed"
fi
fi
}
do_stop(){
check_running
if [ \$? -eq 0 ]; then
\$DAEMON -c \$CONF -d stop
RETVAL=\$?
if [ \$RETVAL -eq 0 ]; then
echo "Stopping \$NAME success"
else
echo "Stopping \$NAME failed"
fi
else
echo "\$NAME is stopped"
RETVAL=1
fi
}
do_status(){
check_running
if [ \$? -eq 0 ]; then
echo "\$NAME (pid \$PID) is running..."
else
echo "\$NAME is stopped"
RETVAL=1
fi
}
do_restart(){
do_stop
sleep 0.5
do_start
}
case "\$1" in
start|stop|restart|status)
do_\$1
;;
*)
echo "Usage: \$0 { start | stop | restart | status }"
RETVAL=1
;;
esac
exit \$RETVAL
EOF
chmod 755 /etc/init.d/shadowsocks_r
update-rc.d -f shadowsocks_r defaults >> $LOG_DIR 2>&1
# Config shadowsocks_r
SSR_CONFIGFILE=/etc/shadowsocks_r/config.json
trim << EOF > $SSR_CONFIGFILE
{
"server":"0.0.0.0",
"server_ipv6":"[::]",
"local_address":"127.0.0.1",
"local_port":1080,
"port_password":{
"${SSR_PORT_START}":"${ADMIN_EMAIL}"
},
"timeout":120,
"method":"${SSR_CIPHER}",
"protocol":"${SSR_PROTOCOL}",
"protocol_param":"",
"obfs":"${SSR_OBFS}",
"obfs_param":"",
"redirect":"",
"dns_ipv6":false,
"fast_open":false,
"workers":1
}
EOF
/etc/init.d/shadowsocks_r restart >> $LOG_DIR 2>&1
# Clean Installation
rm -rf ${SCRIPT_DIR}/ssr_install_temp
fi # End of SHADOWSOCKS_R Installation
# Generate command for user operation
if [[ $SHADOWSOCKS = true ]]; then
trim << EOF > /usr/bin/ss_vpnuser
import sys
import json
CONFIG_FILEPATH="${SS_PYTHON_CONFIGFILE}"
PROGRAM_NAME="shadowsocks-python"
START_PORT=${SS_PYTHON_PORT_START}
END_PORT=${SS_PYTHON_PORT_END}
def main(operation, password):
def write_to_json(obj, json_filepath="./none.json"):
with open(json_filepath, "w") as f:
json.dump(obj, f, sort_keys=True, indent=4, separators=(',', ':'))
def read_from_json(json_filepath="./none.json"):
with open(json_filepath,"r") as f:
temp_data = json.load(f)
return temp_data
config_file=read_from_json(json_filepath=CONFIG_FILEPATH)
if operation in ["add", "adduser", "--adduser", "--add", "-a"]:
password_dict={pwd:prt for (prt, pwd) in config_file["port_password"].items()}
# if password already exist, output relative information and exit
if str(password) in password_dict:
print("user exist in "+str(PROGRAM_NAME))
print("user port: "+str(password_dict[str(password)]))
print("user password: "+str(password))
return
# If password don't exist, assign a unused port to it
for i in range(min(START_PORT, END_PORT), max(START_PORT, END_PORT)+1, 1):
if str(i) in config_file["port_password"]:
continue
else:
config_file["port_password"][str(i)]=password
print("user added to "+str(PROGRAM_NAME))
print("user port: "+str(i))
print("user password: "+str(password))
break
elif operation in ["del", "delete", "deluser", "--deluser", "--delete", "-d"]:
for key in config_file["port_password"]:
if config_file["port_password"][key] == password:
del config_file["port_password"][key]
print("Delete user <"+str(password)+"> from "+str(PROGRAM_NAME))
break
write_to_json(config_file, CONFIG_FILEPATH)
if __name__ == "__main__":
if len(sys.argv) > 2:
main(sys.argv[1], sys.argv[2])
else:
raise ValueError("Incorrect input arguments")
EOF
fi
if [[ $SHADOWSOCKSR = true ]]; then
trim << EOF > /usr/bin/ssr_vpnuser
import sys
import json
CONFIG_FILEPATH="${SSR_CONFIGFILE}"
PROGRAM_NAME="shadowsocks-R"
START_PORT=${SSR_PORT_START}
END_PORT=${SSR_PORT_END}
def main(operation, password):
def write_to_json(obj, json_filepath="./none.json"):
with open(json_filepath, "w") as f:
json.dump(obj, f, sort_keys=True, indent=4, separators=(',', ':'))
def read_from_json(json_filepath="./none.json"):
with open(json_filepath,"r") as f:
temp_data = json.load(f)
return temp_data
config_file=read_from_json(json_filepath=CONFIG_FILEPATH)
if operation in ["add", "adduser", "--adduser", "--add", "-a"]:
password_dict={pwd:prt for (prt, pwd) in config_file["port_password"].items()}
# if password already exist, output relative information and exit
if str(password) in password_dict:
print("user exist in "+str(PROGRAM_NAME))
print("user port: "+str(password_dict[str(password)]))
print("user password: "+str(password))
return
# If password don't exist, assign a unused port to it
for i in range(min(START_PORT, END_PORT), max(START_PORT, END_PORT)+1, 1):
if str(i) in config_file["port_password"]:
continue
else:
config_file["port_password"][str(i)]=password
print("user added to "+str(PROGRAM_NAME))
print("user port: "+str(i))
print("user password: "+str(password))
break
elif operation in ["del", "delete", "deluser", "--deluser", "--delete", "-d"]:
for key in config_file["port_password"]:
if config_file["port_password"][key] == password:
del config_file["port_password"][key]
print("Delete user <"+str(password)+"> from "+str(PROGRAM_NAME))
break
write_to_json(config_file, CONFIG_FILEPATH)
if __name__ == "__main__":
if len(sys.argv) > 2:
main(sys.argv[1], sys.argv[2])
else:
raise ValueError("Incorrect input arguments")
EOF
fi
trim << EOF > /usr/sbin/vpnuser
#!/bin/bash
STRONGSWAN=$STRONGSWAN
OPENCONNECT=$OPENCONNECT
SHADOWSOCKS=$SHADOWSOCKS
SHADOWSOCKSR=$SHADOWSOCKSR
STRONGSWAN_USER_LIST=/etc/ipsec.secrets
OPENCONNECT_USER_LIST=/etc/ocserv/ocpasswd
GENERAL_USER_LIST=/etc/vpnuser
exception(){
echo "Error: \$1"; exit 1
}
warning(){
echo "*** Warning: \$1"
}
info(){
echo "\$1"
}
trim() {
expand | awk 'NR == 1 {match(\$0, /^ */); l = RLENGTH + 1}
{print substr(\$0, l)}'
} # used to trim multiline strings based on first line
show_help(){
trim << EOF_END
Usage: \${0##*/} [-a USERNAME PASSWORD] [-d USERNAME]
Operate VPNs Users based on installation (StrongSwan, OpenConnect, Shadowsocks, ShadowsocksR), require sudo access
-a, --adduser, adduser add new user to all VPNs, require USERNAME and PASSWORD. Can be used to change password
-d, --deluser, deluser delete user from VPNs
-l, --listuser, listuser list all user on this server
-r, --restart, restart restart all VPNs on this server
EOF_END
}
[[ \$(id -u) -eq 0 ]] || ( show_help; exception "Require sudo access, rerun as sudo user." ) # Require sudo access
[[ -f \$GENERAL_USER_LIST ]] || ( warning "General user list missing, create an empty one"; touch \$GENERAL_USER_LIST; chmod 700 \$GENERAL_USER_LIST )
# main body to process request
restart_vpns() {
if [[ \$STRONGSWAN = true ]]; then
info "Restart Strongswan..."
ipsec restart
fi
if [[ \$OPENCONNECT = true ]]; then
info "Restart OpenConnect..."
/etc/init.d/ocserv restart
fi
if [[ \$SHADOWSOCKS = true ]]; then
info "Restart Shadowsocks_python..."
/etc/init.d/shadowsocks_python restart
fi
if [[ \$SHADOWSOCKSR = true ]]; then
info "Restart Shadowsocks_R..."
/etc/init.d/shadowsocks_r restart
fi
}
add_user() {
# Add user to general list
if [[ -n \$(grep -E "\$1 " \$GENERAL_USER_LIST) ]]; then
sed -i "s_^\(\$1 \).*_\1\$2_" \$GENERAL_USER_LIST
else
echo "\$1 \$2" >> \$GENERAL_USER_LIST
fi
# Add to every VPN
if [[ \$STRONGSWAN = true ]]; then
if [[ -n \$(grep -E "\$1\ :\ EAP" \$STRONGSWAN_USER_LIST) ]]; then
sed -i "s_^\(\$1 : EAP \).*_\1\"\$2\"_" \$STRONGSWAN_USER_LIST
info "Updated StrongSwan User <\$1> password to <\$2>"
else
echo "\$1 : EAP \\"\$2\\"" >> \$STRONGSWAN_USER_LIST
info "Added StrongSwan User <\$1> password <\$2>"
fi
fi
if [[ \$OPENCONNECT = true ]]; then
if [[ -n \$(grep -E "\$1:.*:.*" \$OPENCONNECT_USER_LIST) ]]; then
echo "\$2 \$2"| tr " " "\n" | /usr/bin/ocpasswd -c \$OPENCONNECT_USER_LIST \$1
info "Updated OpenConnect User <\$1> password to <\$2>"
else
echo "\$2 \$2"| tr " " "\n" | /usr/bin/ocpasswd -c \$OPENCONNECT_USER_LIST \$1
info "Added OpenConnect User <\$1> password <\$2>"
fi
fi
if [[ \$SHADOWSOCKS = true ]]; then
python /usr/bin/ss_vpnuser -a \$1
info "Added user \$1 to Shadowsocks_python..."
# Update general list
if [[ -n \$(grep -E "\$1 " \$GENERAL_USER_LIST) ]]; then
if [[ ! -n \$(grep "\$1 .* SS_PORT=" \$GENERAL_USER_LIST) ]]; then
user_port_number=\$(grep ":\"\$1\"" $SS_PYTHON_CONFIGFILE | sed "s/.*\"\(.*\)\":.*/\1/")
sed -e "/^\$1 .*/s/\$/ SS_PORT=\$user_port_number/" -i \$GENERAL_USER_LIST
fi
fi
fi
if [[ \$SHADOWSOCKSR = true ]]; then
python /usr/bin/ssr_vpnuser -a \$1
info "Added user \$1 to Shadowsocks_R..."
# Update general list
if [[ -n \$(grep -E "\$1 " \$GENERAL_USER_LIST) ]]; then
if [[ ! -n \$(grep "\$1 .* SSR_PORT=" \$GENERAL_USER_LIST) ]]; then
user_port_number=\$(grep ":\"\$1\"" $SSR_CONFIGFILE | sed "s/.*\"\(.*\)\":.*/\1/")
sed -e "/^\$1 .*/s/\$/ SSR_PORT=\$user_port_number/" -i \$GENERAL_USER_LIST
fi
fi
fi
restart_vpns
grep "\$1 " \$GENERAL_USER_LIST
}
del_user() {
# delete user from general list
if [[ -n \$(grep -E "\$1 " \$GENERAL_USER_LIST) ]]; then
sed -i "/^\$1.*/d" \$GENERAL_USER_LIST
info "Delete user from general list"
else
info "User not in general list"
fi
# delete from every VPN
if [[ \$STRONGSWAN = true ]]; then
if [[ -n \$(grep -E "\$1\ :\ EAP" \$STRONGSWAN_USER_LIST) ]]; then
sed -i "/^\$1.*/d" \$STRONGSWAN_USER_LIST
sed -i "/^\$/d" \$STRONGSWAN_USER_LIST
info "StrongSwan User <\$1> deleted"
else
info "StrongSwan User <\$1> don't exist, skip delete"
fi
fi
if [[ \$OPENCONNECT = true ]]; then
if [[ -n \$(grep -E "\$1:.*:.*" \$OPENCONNECT_USER_LIST) ]]; then
ocpasswd -c \$OPENCONNECT_USER_LIST -d \$1
info "OpenConnect User <\$1> deleted"
else
info "OpenConnect User <\$1> don't exist, skip delete"
fi
fi
if [[ \$SHADOWSOCKS = true ]]; then
python /usr/bin/ss_vpnuser -d \$1
info "Deleted user <\$1> from Shadowsocks_python..."
fi
if [[ \$SHADOWSOCKSR = true ]]; then
python /usr/bin/ssr_vpnuser -d \$1
info "Deleted user <\$1> from Shadowsocks_R..."
fi
restart_vpns
}
# Parse command
POSITIONAL=()
[[ \$# -eq 0 ]] && show_help
while [[ \$# -gt 0 ]]
do
key="\$1"
case \$key in
help|-h|--help)
show_help
exit 0
;;
adduser|-a|--adduser)
if ( [[ -n "\$2" && -n "\$3" ]] ); then
add_user \$2 \$3
else
exception "Need username and password for adding user"
fi
shift
shift
shift
;;
deluser|-d|--deluser)
if [[ -n "\$2" ]]; then
del_user \$2
else
exception "Need username for deleting user"
fi
shift
shift
;;
listuser|-l|--listuser)
echo -e "\033[0;32mUserList: \033[0m"
cat \$GENERAL_USER_LIST | awk '{print $1}'
shift
;;
restart|-r|--restart)
echo "Restart VPNs..."
restart_vpns
;;
*)
POSITIONAL+=("\$1")
shift
;;
esac
done
set -- "\${POSITIONAL[@]}"
if [[ -n \$1 ]]; then
warning "Unknown arguments: \$1"
show_help
fi
# End of Parse Command
EOF
chmod 755 /usr/sbin/vpnuser
# Create a file to store general user info
echo "${ADMIN_EMAIL} ${ADMIN_EMAIL} SS_PORT=${SS_PYTHON_PORT_START} SSR_PORT=${SSR_PORT_START}" > /etc/vpnuser
chmod 700 /etc/vpnuser
info "General user command: 'vpnuser' generated. "
# Print out generate username-password information
info ""
info_highlight "Server Hostname: " "${VPN_HOSTNAME}"
if [[ $STRONGSWAN = true ]]; then
info "******************************** StrongSwan ********************************"
info_highlight "StrongSwan default username: " "${ADMIN_EMAIL}"
info_highlight "StrongSwan default password: " "${ADMIN_EMAIL}"
fi
if [[ $OPENCONNECT = true ]]; then
info "******************************** OpenConnect ********************************"
info_highlight "OpenConnect default username: " "${ADMIN_EMAIL}"
info_highlight "OpenConnect default password: " "${ADMIN_EMAIL}"
fi
if [[ $SHADOWSOCKS = true ]]; then
info "******************************** Shadowsocks ********************************"
info_highlight "Shadowsocks default cipher: " "${SS_PYTHON_CIPHER}"
info_highlight "Shadowsocks default port: " "${SS_PYTHON_PORT_START}"
info_highlight "Shadowsocks default password: " "${ADMIN_EMAIL}"
fi
if [[ $SHADOWSOCKSR = true ]]; then
info "******************************** ShadowsocksR ********************************"
info_highlight "ShadowsocksR default cipher: " "${SSR_CIPHER}"
info_highlight "ShadowsocksR default protocol: " "${SSR_PROTOCOL}"
info_highlight "ShadowsocksR default OBFS: " "${SSR_OBFS}"
info_highlight "ShadowsocksR default port: " "${SSR_PORT_START}"
info_highlight "ShadowsocksR default password: " "${ADMIN_EMAIL}"
fi
info ""
info "You can use 'sudo vpnuser -a <username> <password>' to add user or 'sudo vpnuser -d <username>' to delete user"
# POST Processing
service ssh restart
service unattended-upgrades restart
fi # End of Installation Process
# Uninstall Process
if [[ $UNINSTALL_VPN = true ]]; then
# Remove Everything in LIFO order
# Remove user operation command and general user list
rm -rf /usr/bin/ss_vpnuser
rm -rf /usr/bin/ssr_vpnuser
rm -rf /etc/vpnuser # This is general user list
rm -rf /usr/sbin/vpnuser
# Clear Client Script
info "Clear Scripts for Client..."
if [[ -d "${SCRIPT_DIR}/StrongSwan_Clients/" ]]; then
[[ ! -f "${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_iOS_macOS.mobileconfig" ]] || rm -f "${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_iOS_macOS.mobileconfig"
[[ ! -f "${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_Ubuntu.sh" ]] || rm -f "${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_Ubuntu.sh"
[[ ! -f "${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_Win10.ps1" ]] || rm -f "${SCRIPT_DIR}/StrongSwan_Clients/StrongSwan_Client_Win10.ps1"
if [[ -n "$(find "${SCRIPT_DIR}/StrongSwan_Clients" -maxdepth 0 -type d -empty)" ]]; then
rm -rf "${SCRIPT_DIR}/StrongSwan_Clients"
fi
fi
info "Scripts Removed"
# Remove StrongSwan
info "Start to remove StrongSwan... "
ipsec stop
apt_remove "strongswan strongswan-starter libstrongswan-standard-plugins strongswan-libcharon libcharon-extra-plugins"
apt_remove "strongswan strongswan-starter libstrongswan-standard-plugins strongswan-libcharon libcharon-extra-plugins"
info "StrongSwan Removed"
# Remove OpenConnect
if [[ $OC_INSTALL_FROM_SOURCE = true ]]; then
# Force stop if ocserv is still running
Oc_pid=$(pidof ocserv)
if [[ ! -z $Oc_pid ]]; then
for Pid in $Oc_pid
do
kill -9 $Pid >> $LOG_DIR 2>&1
if [[ $? -eq 0 ]]; then
info "Killed running ocserv..."
else
warning "Cannot kill running ocserv..."
fi
done
fi
rm -rf /etc/ocserv
rm -rf /usr/sbin/ocserv
rm -rf /etc/init.d/ocserv
rm -rf /usr/bin/occtl
rm -rf /usr/bin/ocpasswd
info "OpenConnect Removed"
else
# Uninstall OpenConnect through apt
apt_remove "ocserv"
info "OpenConnect Removed through apt"
#exception "Please install OpenConnect through source...This part is not tested yet"
fi
apt_remove "libgmp3-dev libwrap0-dev libpam0g-dev libdbus-1-dev libnl-route-3-dev libopts25-dev libnl-nf-3-dev libreadline-dev libpcl1-dev libtalloc-dev libev-dev liboath-dev nettle-dev libseccomp-dev liblz4-dev libgeoip-dev libkrb5-dev libradcli-dev libgnutls28-dev gnutls-bin protobuf-c-compiler"
# Remove Shadowsocks_python
/etc/init.d/shadowsocks_python stop
update-rc.d -f shadowsocks_python remove
if [[ -f /etc/shadowsocks_python/shadowsocks_install.log ]]; then
cat /etc/shadowsocks_python/shadowsocks_install.log | xargs rm -rf
fi
rm -rf /etc/shadowsocks_python
rm -rf /etc/init.d/shadowsocks_python
rm -rf /var/run/shadowsocks.pid
rm -rf /var/log/shadowsocks.log
info "Shadowsocks_python Removed"
# Remove Shadowsocks_r
/etc/init.d/shadowsocks_r stop
update-rc.d -f shadowsocks_r remove
rm -rf /etc/shadowsocks_r
rm -rf /usr/bin/shadowsocks_r
rm -rf /etc/init.d/shadowsocks_r
info "Shadowsocks_R Removed"
# Remove Let's Encrypt Certificate
info "Remove Let's Encrypt Certificate. If you don't want to remove certificate left it blank. Be careful..."
read -p "Enter you hostname: " VPN_HOSTNAME
certbot revoke --cert-path /etc/letsencrypt/live/$VPN_HOSTNAME/cert.pem --delete-after-revoke >> $LOG_DIR 2>&1
sed -e 's/* * * * 7 root certbot -q renew//' -i.original /etc/crontab
info "Certificate Removed"
# Clear Firewall Settings
info "Start to Clear Firewall Settings..."
iptables -D INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT >> $LOG_DIR 2>&1 # accept anything already accepted
iptables -D INPUT -i lo -j ACCEPT >> $LOG_DIR 2>&1 # accept anything on loopback interface
iptables -D INPUT -m state --state INVALID -j DROP >> $LOG_DIR 2>&1 # Drop invalid packets
iptables -D INPUT -i $INTERFACE -m state --state NEW -m recent --update --seconds 60 --hitcount 30 -j DROP >> $LOG_DIR 2>&1
iptables -D INPUT -i $INTERFACE -m state --state NEW -m recent --set >> $LOG_DIR 2>&1 # Set limit for repeated request from same IP
# StrongSwan Firewall Rules
iptables -D INPUT -p udp -m udp --dport 500 -j ACCEPT >> $LOG_DIR 2>&1 # Accept IPSec/NAT-T for StrongSwan VPN
iptables -D INPUT -p udp -m udp --dport 4500 -j ACCEPT >> $LOG_DIR 2>&1
iptables -D FORWARD --match policy --pol ipsec --dir in --proto esp -s $STRONGSWAN_VPN_IPPOOL -j ACCEPT >> $LOG_DIR 2>&1 # Forward VPN traffic anywhere
iptables -D FORWARD --match policy --pol ipsec --dir out --proto esp -d $STRONGSWAN_VPN_IPPOOL -j ACCEPT >> $LOG_DIR 2>&1
iptables -t mangle -D FORWARD --match policy --pol ipsec --dir in -s $STRONGSWAN_VPN_IPPOOL -o $INTERFACE -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360 >> $LOG_DIR 2>&1 # Reduce MTU/MSS values for dumb VPN clients
iptables -t nat -D POSTROUTING -s $STRONGSWAN_VPN_IPPOOL -o $INTERFACE -m policy --pol ipsec --dir out -j ACCEPT >> $LOG_DIR 2>&1 # Exempt IPsec traffic from Masquerade
iptables -t nat -D POSTROUTING -s $STRONGSWAN_VPN_IPPOOL -o $INTERFACE -j MASQUERADE >> $LOG_DIR 2>&1 # Masquerade VPN traffic over interface
# OpenConnect Firewal Rules
iptables -D INPUT -p udp -m udp --dport $OC_PORT -m comment --comment "ocserv-udp" -j ACCEPT >> $LOG_DIR 2>&1
iptables -D INPUT -p tcp -m tcp --dport $OC_PORT -m comment --comment "ocserv-tcp" -j ACCEPT >> $LOG_DIR 2>&1
iptables -D FORWARD -s $OC_VPN_IPPOOL -m comment --comment "ocserv-forward-in" -j ACCEPT
iptables -D FORWARD -d $OC_VPN_IPPOOL -m comment --comment "ocesrv-forward-out" -j ACCEPT
iptables -t mangle -D FORWARD -s $OC_VPN_IPPOOL -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "ocserv-mangle" -j TCPMSS --clamp-mss-to-pmtu # MSS fix
iptables -t nat -D POSTROUTING -s $OC_VPN_IPPOOL ! -d $OC_VPN_IPPOOL -m comment --comment "ocserv-postrouting" -j MASQUERADE
# Shadowsocks Firewall Rules
iptables -A INPUT -p tcp -m multiport --dports $SS_PYTHON_PORT_START:$SS_PYTHON_PORT_END -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports $SS_PYTHON_PORT_START:$SS_PYTHON_PORT_END -j ACCEPT
# Shadowoskcs-R firewall Rules
iptables -A INPUT -p tcp -m multiport --dports $SSR_PORT_START:$SSR_PORT_END -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports $SSR_PORT_START:$SSR_PORT_END -j ACCEPT
if [[ ! $SSH_ACCEPT_IP = "" ]]; then
echo $SSH_ACCEPT_IP |tr ' ' '\n' | while read IP_RANGE ; do iptables -D INPUT -s $IP_RANGE -p tcp -m tcp --dport $SSH_PORT -j ACCEPT >> $LOG_DIR 2>&1 ; done # Only accept ssh from certain IP rangse
fi
iptables -D INPUT -p tcp -m tcp --dport $SSH_PORT -j DROP >> $LOG_DIR 2>&1 # Close SSH port to void ssh attack
iptables -D INPUT -d $INTERFACE_IP/32 -p icmp -m icmp --icmp-type 8 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT >> $LOG_DIR 2>&1
iptables -D OUTPUT -s $INTERFACE_IP/32 -p icmp -m icmp --icmp-type 8 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT >> $LOG_DIR 2>&1
iptables -D INPUT -j DROP >> $LOG_DIR 2>&1 # Deny all other requests
iptables -D FORWARD -j DROP >> $LOG_DIR 2>&1
info "Firewall rules cleared"
iptables-save > /etc/iptables/rules.v4
iptables-save > /etc/iptables/rules.v6
info "Firewall persistent updated"
# Purge apt, will keep packages from official repository
info "Removing certbot apt repository..."
apt_install ppa-purge
add-apt-repository -y ppa:certbot/certbot >> $LOG_DIR 2>&1
ppa-purge -y ppa:certbot/certbot >> $LOG_DIR 2>&1
add-apt-repository --remove ppa:certbot/certbot -y >> $LOG_DIR 2>&1
apt_remove ppa-purge
fi
|
Swift | UTF-8 | 5,662 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// Writes trial sensor data to a CSV file.
class TrialDataWriter {
private let csvWriter: CSVWriter
private var currentRow: Row?
private let sensorIDs: [String]
private let trialID: String
private let isRelativeTime: Bool
private let trialRange: ChartAxis<Int64>
private var firstTimeStampWritten: Int64?
private let sensorDataManager: SensorDataManager
/// The file URL of the CSV file.
var fileURL: URL {
return csvWriter.fileURL
}
/// Designated initializer. Returns nil if there is a problem creating a valid file.
///
/// - Parameters:
/// - trialID: A trial ID.
/// - filename: A filename for the CSV file.
/// - isRelativeTime: True if output timestamps should be relative to the trial start,
/// otherwise false.
/// - sensorIDs: The IDs of the sensors to include.
/// - range: The range of timestamps to export.
/// - sensorDataManager: The sensor data manager.
init?(trialID: String,
filename: String,
isRelativeTime: Bool,
sensorIDs: [String],
range: ChartAxis<Int64>,
sensorDataManager: SensorDataManager) {
self.trialID = trialID
self.isRelativeTime = isRelativeTime
self.sensorIDs = sensorIDs
self.trialRange = range
self.sensorDataManager = sensorDataManager
let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
let fileURL = tempDirectory.appendingPathComponent(filename)
var titles = sensorIDs
titles.insert(isRelativeTime ? "relative_time" : "timestamp", at: 0)
if let writer = CSVWriter(fileURL: fileURL, columnTitles: titles) {
csvWriter = writer
} else {
return nil
}
}
/// Begins the writing to disk. Calls completion when writing is complete.
///
/// - Parameters:
/// - progress: A block called with a progress value between 0 and 1. Called on the main queue.
/// - completion: Called when writing is complete with a Bool parameter indicating
/// success or failure. Called on the main queue.
func write(progress: @escaping (Double) -> Void, completion: @escaping (Bool) -> Void) {
sensorDataManager.fetchSensorData(forTrialID: trialID,
startTimestamp: trialRange.min,
endTimestamp: trialRange.max,
completion: { (sensorData) in
if let sensorData = sensorData {
for data in sensorData {
self.addSensorData(data)
DispatchQueue.main.async {
progress(Double(data.timestamp - self.trialRange.min) /
Double(self.trialRange.length))
}
}
self.finish()
DispatchQueue.main.async { completion(true) }
} else {
DispatchQueue.main.async { completion(false) }
}
})
}
// MARK: - Private
/// Adds sensor data to the output file.
///
/// - Parameter sensorData: A sensor data reading.
private func addSensorData(_ sensorData: SensorData) {
// Ignore sensor data that is not for one of the exported sensor IDs.
guard sensorIDs.contains(sensorData.sensor) else {
return
}
var timestamp: Int64
if isRelativeTime {
// If the timestamps are relative,
if let firstTimeStampWritten = firstTimeStampWritten {
timestamp = sensorData.timestamp - firstTimeStampWritten
} else {
timestamp = 0
self.firstTimeStampWritten = sensorData.timestamp
}
} else {
timestamp = sensorData.timestamp
}
if timestamp != currentRow?.timestamp {
writeRow()
}
// If timestamp matches current row, add to it, otherwise create a new row.
var row: Row
if let currentRow = currentRow {
row = currentRow
} else {
row = Row(timestamp: timestamp)
}
row.addValue(sensorData.value, for: sensorData.sensor)
currentRow = row
}
/// Writes any pending rows to the CSV file. Must be called to ensure all data is exported.
private func finish() {
writeRow()
csvWriter.finish()
}
/// Writes the current row to the CSV file.
private func writeRow() {
guard let currentRow = currentRow else { return }
// First column is timestamp.
var values = [String(currentRow.timestamp)]
// Then append sensor columns.
values.append(contentsOf: sensorIDs.map { (sensorID) in
if let value = currentRow.values[sensorID] {
return String(value)
} else {
return ""
}
})
csvWriter.addValues(values)
// Clear current row once it has been written.
self.currentRow = nil
}
// MARK: - Sub types
/// Represents one row of trial sensor data.
struct Row {
var timestamp: Int64
var values: [String: Double]
init(timestamp: Int64) {
self.timestamp = timestamp
self.values = [:]
}
mutating func addValue(_ value: Double, for sensorID: String) {
values[sensorID] = value
}
}
}
|
Python | UTF-8 | 754 | 2.796875 | 3 | [] | no_license | from pymongo import MongoClient
import pymongo
import datetime
"""
一个文件作为一个database输入
"""
client = MongoClient()
def database(data, name, error_number):
"""建立输入数据库"""
keys = list(data.keys())
db = client[name]
for key in keys:
collection(data[key], key, db, error_number)
def collection(data, name, db, error_number):
"""建立collection"""
collections = db[name]
for doc in data:
document(doc, collections, error_number)
def document(data, coll, error_number):
data['errornumber'] = error_number
post_id = coll.insert_one(data).inserted_id
def input(data, name, error_number):
'''输入数据,从这里开始'''
database(data, name, error_number)
|
PHP | UTF-8 | 1,814 | 2.84375 | 3 | [] | no_license | <?php
class PageData {
private $logInOut;
private $admin;
private $path;
public function __construct() { }
//these getter functions return the private property values to the
//calling object.
public function getAdminScript(){
return $this->adminScript;
}
public function getLogout(){
return $this->logout;
}
public function getLogInOut(){
return $this->logInOut;
}
public function getAdmin(){
return $this->admin;
}
//This loads the scripts needed based upon whether we are in admin or non-admin mode.
public function pageSetup() {
session_start();
/*By default I call the mainobj.init of the main script
this only contains methods for the pages when they are
in non admin mode
*/
$this->logout="";
//If in admin mode the extra scripts load and the page is editable
if (isset($_SESSION['admin'])){
if ($_SESSION['admin']==='authorized'){
/*set the $admin flag to true so the application knows it is
in admin mode*/
$this->admin=true;
}
}
//since a sesssion was created using the session start but not needed because
//we are in non-admin mode then remove session and cookie.
else {
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
$this->admin=false;
session_destroy();
}
}
}
|
C | UTF-8 | 10,874 | 2.578125 | 3 | [] | no_license | // customViewTest.c ... test the ADTs more extensively
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "GameView.h"
int main()
{
GameView gv;
int i;
int size, seen[NUM_MAP_LOCATIONS], *edges;
printf("\t\tTest From PastPlays in Bugfixes\n");
printf("\n\tGame #0 samples, Start of Round 1\n");
PlayerMessage messages1[] = {"Hello", "There", "This", "Should", "Be Good"};
gv = newGameView("GMN.... SPL.... HAM.... MPA.... DC?.V..", messages1);
printf("Turn/Score Tests\n");
assert(getCurrentPlayer(gv) == PLAYER_LORD_GODALMING);
assert(getRound(gv) == 1);
assert(getScore(gv) == GAME_START_SCORE -1);
printf("Passed Score Tests\n");
printf("Location Tests\n");
assert(getLocation(gv,PLAYER_LORD_GODALMING) == MANCHESTER);
assert(getLocation(gv,PLAYER_DR_SEWARD) == PLYMOUTH);
assert(getLocation(gv,PLAYER_VAN_HELSING) == AMSTERDAM);
assert(getLocation(gv,PLAYER_MINA_HARKER) == PARIS);
assert(getLocation(gv,PLAYER_DRACULA) == CITY_UNKNOWN);
printf("Passed Location Tests\n");
disposeGameView(gv);
printf("\n\tGame #0 samples, End of Round 1\n");
PlayerMessage messages2[] = {"Hello", "There", "This", "Should", "Be Good",
"Yas", "I'm Getting", "A", "Bit", "Excited"};
gv = newGameView("GMN.... SPL.... HAM.... MPA.... DC?.V.. "
"GLV.... SLO.... HNS.... MST.... DC?T...", messages2);
printf("Location History Tests\n");
LocationID history[TRAIL_SIZE];
getHistory(gv, 0, history);
assert(history[0] == LIVERPOOL);
assert(history[1] == MANCHESTER);
assert(history[2] == UNKNOWN_LOCATION);
getHistory(gv,1,history);
assert(history[0] == LONDON);
assert(history[1] == PLYMOUTH);
assert(history[2] == UNKNOWN_LOCATION);
getHistory(gv,2,history);
assert(history[0] == NORTH_SEA);
assert(history[1] == AMSTERDAM);
assert(history[2] == UNKNOWN_LOCATION);
getHistory(gv,3,history);
assert(history[0] == STRASBOURG);
assert(history[1] == PARIS);
assert(history[2] == UNKNOWN_LOCATION);
getHistory(gv,4,history);
assert(history[0] == CITY_UNKNOWN);
assert(history[1] == CITY_UNKNOWN);
assert(history[2] == UNKNOWN_LOCATION);
printf("Passed Location History Tests\n");
disposeGameView(gv);
printf("\n\tGame #1, Mina's Turn, 5 complete Rounds\n");
PlayerMessage messages3[]={""};
gv = newGameView("GMN.... SPL.... HAM.... MPA.... DC?.V.. "
"GLV.... SLO.... HNS.... MST.... DC?T... "
"GIR.... SPL.... HAO.... MZU.... DCDT... "
"GSW.... SLO.... HNS.... MFR.... DC?T... "
"GLV.... SPL.... HAO.... MZU.... DC?T... "
"GSW.... SLO.... HNS....", messages3);
printf("Score And Round Number tests\n");
assert(getRound(gv) == 5);
assert(getScore(gv) == GAME_START_SCORE - 5);
assert(getCurrentPlayer(gv) == PLAYER_MINA_HARKER);
assert(getHealth(gv, 4) == GAME_START_BLOOD_POINTS + LIFE_GAIN_CASTLE_DRACULA);
printf("Passed Score/Round tests\n");
printf("Location History Tests\n");
getHistory(gv,0,history);
assert(history[0] == SWANSEA);
assert(history[1] == LIVERPOOL);
assert(history[2] == SWANSEA);
assert(history[3] == IRISH_SEA);
assert(history[4] == LIVERPOOL);
assert(history[5] == MANCHESTER);
getHistory(gv,1,history);
assert(history[0] == LONDON);
assert(history[1] == PLYMOUTH);
assert(history[2] == LONDON);
assert(history[3] == PLYMOUTH);
assert(history[4] == LONDON);
assert(history[5] == PLYMOUTH);
getHistory(gv,2,history);
assert(history[0] == NORTH_SEA);
assert(history[1] == ATLANTIC_OCEAN);
assert(history[2] == NORTH_SEA);
assert(history[3] == ATLANTIC_OCEAN);
assert(history[4] == NORTH_SEA);
assert(history[5] == AMSTERDAM);
getHistory(gv,3,history);
assert(history[0] == ZURICH);
assert(history[1] == FRANKFURT);
assert(history[2] == ZURICH);
assert(history[3] == STRASBOURG);
assert(history[4] == PARIS);
getHistory(gv,4,history);
assert(history[0] == CITY_UNKNOWN);
assert(history[1] == CITY_UNKNOWN);
assert(history[2] == CASTLE_DRACULA);
assert(history[3] == CITY_UNKNOWN);
assert(history[4] == CITY_UNKNOWN);
disposeGameView(gv);
printf("Passed Location History Tests\n");
printf("\n\tChecking Empty Game Rail Connections for Paris\n");
gv = newGameView("", messages1);
printf("Checking Paris rail connections for Godalming Rd 0 (up to 0 steps)\n");
edges = connectedLocations(gv, &size, PARIS, PLAYER_LORD_GODALMING, 0,0,1,0);
memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));
for (i=0; i < size; i++) seen[edges[i]] = 1;
assert(size = 1);
assert(seen[PARIS]);
free(edges);
printf("passed\n");
printf("Checking Paris rail connections for Seward Rd 0 (up to 1 steps)\n");
edges = connectedLocations(gv, &size, PARIS, PLAYER_DR_SEWARD, 0,0,1,0);
memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));
for (i=0; i < size; i++) seen[edges[i]] = 1;
assert(size = 5); assert(seen[BORDEAUX]); assert(seen[MARSEILLES]);
assert(seen[LE_HAVRE]); assert(seen[BRUSSELS]); assert(seen[PARIS]);
free(edges);
printf("passed\n");
printf("Checking Paris rail connections for Helsing Rd 0 (up to 2 steps)\n");
edges = connectedLocations(gv, &size, PARIS, PLAYER_VAN_HELSING, 0,0,1,0);
memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));
for (i=0; i < size; i++) seen[edges[i]] = 1;
assert(size = 7); assert(seen[BORDEAUX]); assert(seen[MARSEILLES]);
assert(seen[LE_HAVRE]); assert(seen[BRUSSELS]); assert(seen[PARIS]);
assert(seen[COLOGNE]); assert(seen[SARAGOSSA]);
free(edges);
printf("passed\n");
printf("Checking Paris rail connections for Mina Rd 0 (up to 3 steps)\n");
edges = connectedLocations(gv, &size, PARIS, PLAYER_MINA_HARKER, 0,0,1,0);
memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));
for (i=0; i < size; i++) seen[edges[i]] = 1;
assert(size = 10); assert(seen[BORDEAUX]); assert(seen[MARSEILLES]);
assert(seen[LE_HAVRE]); assert(seen[BRUSSELS]); assert(seen[PARIS]);
assert(seen[COLOGNE]); assert(seen[SARAGOSSA]);
assert(seen[BARCELONA]); assert(seen[MADRID]); assert(seen[FRANKFURT]);
free(edges);
printf("passed\n");
disposeGameView(gv);
printf("\n\tGame #2, Godalmings Turn, 7 rounds\n");
PlayerMessage messages4[] = {""};
gv = newGameView("GED.... SGE.... HZU.... MCA.... DCF.V.. "
"GMN.... SCFVD.. HGE.... MLS.... DBOT... "
"GLO.... SMR.... HCF.... MMA.... DC?T... "
"GPL.... SMS.... HMR.... MGR.... DBAT... "
"GLO.... SBATD.. HMS.... MMA.... DC?T... "
"GPL.... SSJ.... HBA.... MGR.... DC?T... "
"GPL.... SSJ.... HBA.... MGR.... DC?T...", messages4);
printf("Score And Round Tests\n");
assert(getRound(gv) == 7);
assert(getCurrentPlayer(gv) == 0);
assert(getScore(gv) == (GAME_START_SCORE - 7 - 6));
printf("passed\n");
printf("Health Tests\n");
assert(getHealth(gv, 0) == 9);
assert(getHealth(gv, 1) == 9);
assert(getHealth(gv, 2) == 9);
assert(getHealth(gv, 3) == 9);
assert(getHealth(gv, 4) == 20);
disposeGameView(gv);
printf("passed\n");
printf("\n\tGame #3, Godalmings Turn, 1 round\n");
gv=newGameView("GEDT... SGET... HZUT... MCAT... DCF.V..", messages4);
printf("Score And Round Tests\n");
assert(getRound(gv) == 1); //unsure if this is right
assert(getCurrentPlayer(gv) == 0);
assert(getScore(gv) == (GAME_START_SCORE-1));
printf("Health Tests\n");
assert(getHealth(gv, 0) == 7);
assert(getHealth(gv, 1) == 7);
assert(getHealth(gv, 2) == 7);
assert(getHealth(gv, 3) == 7);
assert(getHealth(gv, 4) == 40);
disposeGameView(gv);
printf ("passed\n");
printf("\n\tGame #4, Godalmings Turn, 2 rounds\n");
gv=newGameView("GEDT... SGET... HZUT... MCAT... DCF.V.. "
"GED.... SGE.... HZU.... MCA.... DAS..V.", messages4);
printf("Score And Round Tests\n");
assert(getRound(gv) == 2);
assert(getCurrentPlayer(gv) == 0);
assert(getScore(gv) == (GAME_START_SCORE-15)); //2 for round 13 for matured
printf("Health Tests\n");
assert(getHealth(gv, 0) == 9); //should be healed from resting
assert(getHealth(gv, 1) == 9); //test to ensure does not exceed
assert(getHealth(gv, 2) == 9);
assert(getHealth(gv, 3) == 9);
assert(getHealth(gv, 4) == 38); // lost two due to ending in sea
disposeGameView(gv);
printf("passed\n");
printf("\n\tGame #5, Godalmings Turn, 3 rounds\n");
gv=newGameView("GEDT... SGET... HZUT... MCAT... DCF.V.. "
"GMNT... SPLT... HNST... MPAT... DAS..V. "
"GMN.... SPL.... HNS.... MPA.... DC?....", messages4);
printf("Score And Round Tests\n");
assert(getRound(gv) == 3);
assert(getCurrentPlayer(gv) == 0);
assert(getScore(gv) == (GAME_START_SCORE-16)); //3 for round 13 for matured
printf("Health Tests\n");
assert(getHealth(gv, 0) == 8); //loose 4 to two traps
assert(getHealth(gv, 1) == 8); //Gain 3 from one rest
assert(getHealth(gv, 2) == 8);
assert(getHealth(gv, 3) == 8);
assert(getHealth(gv, 4) == 38); // lost two due to ending in sea
disposeGameView(gv);
printf("passed\n");
printf("\n\tGame #6, Godalmings Turn, 7 rounds\n");
gv=newGameView("GEDT... SGET... HZUT... MCAT... DCF.V.. "
"GMNT... SPLT... HNST... MPAT... DAS..V. "
"GMN.... SPL.... HNS.... MPA.... DC?.... " //health at 8
"GEDT... SGET... HZUT... MCAT... DC?.... " //6
"GMNT... SPLT... HNST... MPAT... DC?.... "//4
"GEDT... SGET... HZUT... MCAT... DC?.... "//2
"GMNT... SPLT... HNST... MPAT... DC?....", messages4);
printf("Score And Round Tests\n");
assert(getRound(gv) == 7);
assert(getCurrentPlayer(gv) == 0);
assert(getScore(gv) == (GAME_START_SCORE-44)); //7 for round 13 for matured 6*4 for hunter deaths
printf("Health Tests\n");
assert(getHealth(gv, 0) == 9); //should now be reset to 9
assert(getHealth(gv, 1) == 9);
assert(getHealth(gv, 2) == 9);
assert(getHealth(gv, 3) == 9);
assert(getHealth(gv, 4) == 38); // lost two due to ending in sea
printf("Location Tests\n"); //locations should be reset
assert(getLocation(gv,0)==ST_JOSEPH_AND_ST_MARYS);
assert(getLocation(gv,1)==ST_JOSEPH_AND_ST_MARYS);
assert(getLocation(gv,2)==ST_JOSEPH_AND_ST_MARYS);
assert(getLocation(gv,3)==ST_JOSEPH_AND_ST_MARYS);
disposeGameView(gv);
printf("passed\n");
return 0;
}
|
Java | UTF-8 | 6,391 | 1.851563 | 2 | [] | no_license | package com.github.vincentrussell.restdocs.maven.plugin;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import static org.apache.commons.lang3.Validate.isTrue;
@Mojo( name = "build-api-docs-html", defaultPhase = LifecyclePhase.PACKAGE, threadSafe = true, requiresDependencyResolution = ResolutionScope.RUNTIME )
public class BuildApiDocsMojo extends AbstractMojo {
@Parameter(defaultValue = "${project.build.directory}/html-api-docs/api-docs.html", property = "destinationFile", required = true)
protected String destinationFile;
@Parameter(property = "xmlConfigs", required = false)
protected String[] xmlConfigs = new String[0];
@Parameter(property = "annotatedClassConfigs", required = false)
protected String[] annotatedClassConfigs = new String[0];
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject mavenProject;
@Parameter(property = "basePath", required = false)
private String basePath = "/";
@Parameter(property = "host", required = false)
private String host = "";
@Parameter(property = "title", required = false)
private String title = "Api Documentation";
@Parameter(property = "description", required = false)
private String description = "Api Documentation";
@Parameter(property = "version", defaultValue = "${project.version}", required = false)
private String version = "1.0";
@Parameter(property = "termsOfServiceUrl", required = false)
private String termsOfServiceUrl = "";
@Parameter(property = "contactName", required = false)
private String contactName = "";
@Parameter(property = "contactUrl", required = false)
private String contactUrl = "";
@Parameter(property = "contactEmail", required = false)
private String contactEmail = "";
@Parameter(property = "license", required = false)
private String license = "Apache 2.0";
@Parameter(property = "licenseUrl", required = false)
private String licenseUrl = "http://www.apache.org/licenses/LICENSE-2.0";
@Parameter(property = "schemes", required = false)
private String[] schemes = new String[0];
@Parameter(property = "pathIncludeRegexes", required = false)
private String[] pathIncludeRegexes = new String[0];
@Parameter(property = "pathExcludeRegexes", required = false)
private String[] pathExcludeRegexes = new String[0];
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
isTrue((xmlConfigs!=null && xmlConfigs.length > 0)
|| (annotatedClassConfigs!=null && annotatedClassConfigs.length > 0), "xmlConfigs or annotatedClassConfigs must be provided");
setProjectRuntimeDependenciesOnPluginClasspath();
final File destFile = new File(destinationFile);
if (destFile.getParentFile() != null) {
destFile.getParentFile().mkdirs();
}
try {
try (SwaggerJsonToMarkupConverter swaggerJsonToMarkupConverter =
isXmlMode() ? new SwaggerJsonToMarkupConverter(xmlConfigs) :
new SwaggerJsonToMarkupConverter(Lists.transform(Lists.newArrayList(annotatedClassConfigs), new Function<String, Class>() {
@Override
public Class apply(String input) {
try {
return Class.forName(input);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}).toArray(new Class[annotatedClassConfigs.length]))) {
swaggerJsonToMarkupConverter.setBasePath(basePath)
.setHost(host)
.setApiInfoTitle(title)
.setApiInfoDescription(description)
.setApiInfoVersion(version)
.setApiInfoTermsOfServiceUrl(termsOfServiceUrl)
.setApiInfoContactInfoName(contactName)
.setApiInfoContactInfoUrl(contactUrl)
.setApiInfoContactInfoEmail(contactEmail)
.setApiInfoLicense(license)
.setApiInfoLicenseUrl(licenseUrl);
swaggerJsonToMarkupConverter.writeToHtmlFile(destFile);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void setProjectRuntimeDependenciesOnPluginClasspath() throws MojoExecutionException {
try {
List<String> runtimeClasspathElements = runtimeClasspathElements = mavenProject.getRuntimeClasspathElements();
URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
for (int i = 0; i < runtimeClasspathElements.size(); i++) {
String element = runtimeClasspathElements.get(i);
runtimeUrls[i] = new File(element).toURI().toURL();
}
URLClassLoader newLoader = new URLClassLoader(runtimeUrls,
Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(newLoader);
getLog().info("Plugin classpath augmented with project compile and runtime dependencies: " + runtimeClasspathElements);
} catch (DependencyResolutionRequiredException | MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private boolean isXmlMode() {
return (xmlConfigs!=null && xmlConfigs.length > 0);
}
}
|
SQL | UTF-8 | 628 | 3.984375 | 4 | [] | no_license | Table: Project
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
+-------------+---------+
Table: Employee
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| experience_years | int |
+------------------+---------+
Question: Write an SQL query that reports all the projects that have the most employees.
select
project_id
from
(select
project_id,
count(*) as emp_count
from Project
group by 1) t
order by emp_count desc
limit 1 |
JavaScript | UTF-8 | 1,873 | 2.515625 | 3 | [
"MIT"
] | permissive | 'use sctrict';
var http = require('http');
function HttpTransport() {}
HttpTransport.prototype.listen = function(opts, callback) {
callback = callback || function() {};
var self = this;
var server = http.createServer(handleRequest.bind(this));
server.listen(opts.port || 3000, opts.hostname || "0.0.0.0", function() {
callback(null, server.address());
});
};
function handleRequest(req, res) {
var self = this;
var data = '';
// if request is type POST and on /exec url then parse the data and handle it
if (req.url.indexOf('/exec') !== -1 && req.method.toLowerCase() === 'post' ) {
req.on('data', function(chunk) {
chunk = chunk.toString();
data += chunk;
});
return req.on('end', function() {
var args = JSON.parse(data);
self.exec(args, function(err, out) {
if (err) {
// ignore error for now...
}
// empty 200 OK response for now
res.writeHead(200, "OK", {'Content-Type': 'application/json'});
res.end(JSON.stringify(out));
});
});
}
// default action for the rest of requests
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({ message: 'To call an action use /do' }));
}
HttpTransport.prototype.send = function(opts, args, callback) {
args = args || {};
var data = '';
var reqOpts = _.clone(opts, true);
reqOpts = _.extend(self._defaults.transport, reqOpts);
var req = http.request(reqOpts, function(res) {
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
callback(null, JSON.parse(data));
});
res.on('error', function(err) {
callback(err);
});
});
req.on('error', function(err) {
console.log('request error', err);
});
req.write(JSON.stringify(args));
req.end();
};
module.exports = HttpTransport;
|
Java | UTF-8 | 435 | 1.859375 | 2 | [
"MIT"
] | permissive | package cn.genlei.ydms.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author nid
*/
@Data
@ApiModel(description = "登录传参")
public class LoginDTO {
@ApiModelProperty(required = true, value = "用户名",example = "admin")
String username;
@ApiModelProperty(required = true, value = "密码",example = "xxxxxx")
String password;
}
|
PHP | UTF-8 | 931 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Event\SomethingHappened;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ConsoleLogger implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
SomethingHappened::class => [
['writeOnConsole', 1],
['sendSms', 10],
]
];
}
public function writeOnConsole(SomethingHappened $event)
{
echo "EventSubscriber: ConsoleLogger\n";
echo sprintf(" %s %s\n", $event->getDateTime()->format('Y-m-d H:i:s'), $event->getDescription());
echo PHP_EOL;
}
public function sendSms(SomethingHappened $event)
{
echo "EventSubscriber: SendSms\n";
echo sprintf(" %s %s\n", $event->getDateTime()->format('Y-m-d H:i:s'), $event->getDescription());
echo PHP_EOL;
}
}
|
Java | UTF-8 | 3,681 | 3.390625 | 3 | [] | no_license | package com.isharpever.game.pursuit;
import com.alibaba.fastjson.JSON;
import lombok.Data;
/**
* 棋盘
*/
@Data
public class Board {
private static volatile Board instance;
/** 棋盘行数 */
public static final int ROW_NUM = 6;
/** 棋盘列数 */
public static final int COL_NUM = 6;
/**
* 行数
*/
private int rowNum;
/**
* 列数
*/
private int colNum;
/**
* 棋盘格
*/
private Cell[] cells;
private Board() {
init();
}
private void init() {
this.rowNum = ROW_NUM;
this.colNum = COL_NUM;
int cellNum = ROW_NUM * COL_NUM;
this.cells = new Cell[cellNum];
for (int i = 0; i < cellNum; i++) {
this.cells[i] = new Cell(i, getX(i), getY(i));
}
}
public static Board getInstance() {
if (instance == null) {
synchronized (Board.class) {
if (instance == null) {
instance = new Board();
}
}
}
return instance;
}
/**
* 返回指定序号位置的棋盘格
* @param cellOrder
* @return
*/
public Cell getCell(int cellOrder) {
return this.cells[cellOrder];
}
/**
* 返回指定坐标位置的棋盘格
* @param x
* @param y
* @return
*/
public Cell getCell(int x, int y) {
int cellOrder = (y - 1) * this.colNum + x;
return this.cells[cellOrder];
}
/**
* 指定序号位置的棋盘格设置棋子
* @param cellOrder
* @param chessPiece
*/
public void setChessPiece(int cellOrder, ChessPiece chessPiece) {
this.cells[cellOrder].setChessPiece(chessPiece);
}
/**
* 指定序号位置的棋盘格设置警车
* @param cellOrder
*/
public void setPoliceCar(int cellOrder) {
this.cells[cellOrder].setPoliceCar(true);
}
/**
* 返回指定序号位置的棋盘格里是否有棋子
* @param cellOrder
* @return
*/
public boolean isNotEmpty(int cellOrder) {
return !getCell(cellOrder).isEmpty();
}
/**
* 返回指定序号位置的棋盘格里是否有警车
* @param cellOrder
* @return
*/
public boolean isPoliceCar(int cellOrder) {
return this.cells[cellOrder].isPoliceCar();
}
/**
* 返回指定序号位置的棋盘格里是否有警车
* @param cellOrder
* @return
*/
public boolean isBuilding(int cellOrder) {
return this.cells[cellOrder].isBuilding();
}
/**
* 释放所有棋盘格
*/
public void release() {
for (int i = 0; i < this.cells.length; i++) {
this.cells[i].release();
}
}
/**
* 打印
*/
public void print() {
System.out.println(JSON.toJSONString(this.cells));
}
/**
* 返回指定序号的棋盘格是否在棋盘边界以外(含边界)
* @param cellOrder
* @return
*/
public static boolean isOnOrOutOfBorder(int cellOrder) {
if (cellOrder < 0 || cellOrder >= COL_NUM * ROW_NUM) {
return true;
}
int y = getY(cellOrder);
if (y == 0 || y == ROW_NUM - 1) {
return true;
}
int x = getX(cellOrder);
if (x == 0 || x == COL_NUM - 1) {
return true;
}
return false;
}
public static int getX(int cellOrder) {
int y = getY(cellOrder);
return cellOrder - y * COL_NUM;
}
public static int getY(int cellOrder) {
return cellOrder / COL_NUM;
}
}
|
C++ | UTF-8 | 11,537 | 2.5625 | 3 | [] | no_license | /*
To do -
webc_ElementPushPrivateData();
webc_ElementPopPrivateData();
webc_ElementPushTagEventHandler();
webc_ElementPopTagEventHandler();
Fix up DragDrop interface.
Dynamically create control sprite.
Scope start and garbage collect
webc_QueueGc();
webc_Gc();
*/
#include "../include/NewApi.h"
#include "rtpmem.h"
#include "dflow.hpp"
#include "helement.hpp"
#include "htmlbrow.hpp"
#include <assert.h>
#if (0)
char *webc_Strmalloc(char *str)
{
char *rstr = 0 ;
if (str)
{
rstr = (char *)rtp_malloc(rtp_strlen(str)+1);
rtp_strcpy(rstr, str);
}
return rstr;
}
#endif
/* Get display element. (not used.)
** Currently must be an HtmlElement, doesn't work for FlowDisplay. Can we tell if it's an Element or flow display ? So we can do both ?.*/
DELEMENT_HANDLE webc_GetDisplayElement(HELEMENT_HANDLE hElem)
{
DisplayElement *pDisplay=0;
if (hElem)
pDisplay = ((HTMLElement *)hElem)->GetDisplayElement();
return (DELEMENT_HANDLE) pDisplay;
}
/* Attaching listener callbacks to the object so we get HTML_EVENT_RENDER
** Currently must be a FlowDisplay. Can we tell if it's an Element or flow display ? So we can do both ?.*/
void webc_ElementEnableDisplayEvents(HELEMENT_HANDLE hElem)
{
HTMLFlowDisplay *D = (HTMLFlowDisplay *)((HTMLElementContainer *) hElem)->GetDisplayElement();
if (D)
D->SetListener(HELEMENT_OBJ(hElem));
}
int webc_SetControlSpritePosition(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc, int X, int Y)
{
HELEMENT_HANDLE ControlSprite;
char ascii_buff[80];
ControlSprite = webc_GetControlSprite(hbrowser, hdoc);
if (!ControlSprite)
return -1;
rtp_sprintf(ascii_buff, "position:absolute;left:%dpx;top:%dpx;", X, Y);
webc_ElementSetStyleASCII(ControlSprite, ascii_buff,WEBC_TRUE);
return 0;
}
int webc_ElementSetXYPosition(HELEMENT_HANDLE element, int X, int Y)
{
char ascii_buff[80];
if (!element)
return -1;
rtp_sprintf(ascii_buff, "position:absolute;left:%dpx;top:%dpx;", X, Y);
webc_ElementSetStyleASCII(element, ascii_buff,WEBC_TRUE);
HDOC_HANDLE hdoc = webc_ElementGetDocument(element);
return webc_SetControlSpritePosition(webc_DocGetBrowser(hdoc),hdoc,X,Y);/* Move the control sprite so the element actually moves */
}
int webc_ElementSetXYWHPosition(HELEMENT_HANDLE element, int X, int Y,int W, int H)
{
char ascii_buff[80];
if (!element)
return -1;
rtp_sprintf(ascii_buff, "position:absolute;left:%dpx;top:%dpx;width:%dpx;height:%dpx;", X, Y, W, H);
webc_ElementSetStyleASCII(element, ascii_buff,WEBC_TRUE);
HDOC_HANDLE hdoc = webc_ElementGetDocument(element);
return webc_SetControlSpritePosition(webc_DocGetBrowser(hdoc),hdoc,X,Y);/* Move the control sprite so the element actually moves */
}
int webc_ElementGetXYWHPosition(HELEMENT_HANDLE element, int *X, int *Y, int *W, int *H)
{
long y,x;
if (!element)
return -1;
x=y=0;
webc_ElementGetXYPosition(element, &x, &y);
*Y=y;*X=x;
*W = webc_ElementGetWidth(element);
*H = webc_ElementGetHeight(element);
return 0;
}
int webc_ElementHide(HELEMENT_HANDLE helem, WEBC_BOOL doHide)
{
if (doHide)
return webc_ElementSetStyleASCII(helem, "visibility:hidden;",WEBC_TRUE);
else
return webc_ElementSetStyleASCII(helem, "visibility:visible;",WEBC_TRUE);
}
int webc_ElementSetZindex(HELEMENT_HANDLE helem, int z)
{
char ascii_buff[80];
rtp_sprintf(ascii_buff, "z-index:%d;", z);
return webc_ElementSetStyleASCII(helem, ascii_buff,WEBC_TRUE);
}
/* Stop dragging and reset. */
static void _webc_DragReset(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc, struct _webcDraghandle *dragObject)
{
HELEMENT_HANDLE ControlSprite;
webc_ElementSetXYPosition(dragObject->DraggingElement, dragObject->DraggingElementStartX, dragObject->DraggingElementStartY);
ControlSprite = webc_GetControlSprite(hbrowser, hdoc);
if (ControlSprite)
{
webc_ElementSetPrivateData(ControlSprite,0);
rtp_free(dragObject);
webc_ElementHide(ControlSprite, WEBC_TRUE);
webc_ElementReleasePointer(ControlSprite);
}
}
static int clipYDrag(struct _webcDraghandle *dragObject,int Y)
{
int inY = Y;
if ((dragObject->DraggingFlags & HASYMIN) && Y < dragObject->DraggingElementminY)
Y = dragObject->DraggingElementminY;
if ((dragObject->DraggingFlags & HASYMAX) && Y > dragObject->DraggingElementmaxY)
Y = dragObject->DraggingElementmaxY;
return Y;
}
static int clipXDrag(struct _webcDraghandle *dragObject, int X)
{
if ((dragObject->DraggingFlags & HASXMIN) && X < dragObject->DraggingElementminX)
X = dragObject->DraggingElementminX;
if ((dragObject->DraggingFlags & HASXMAX) && X > dragObject->DraggingElementmaxX)
X = dragObject->DraggingElementmaxX;
return X;
}
static HTMLEventStatus ControlSpriteEventHandler(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc, HELEMENT_HANDLE ControlSprite, HTMLEvent* event,char * param)
{
struct _webcDraghandle *dragObject;
switch (event->type)
{
case HTML_EVENT_MOUSEMOVE:
{
int moveX, moveY;
dragObject = (struct _webcDraghandle *) webc_ElementGetPrivateData(ControlSprite);
if (!dragObject)
break;
moveX = event->data.position.x - dragObject->DraggingPointerStartX;
moveY = event->data.position.y - dragObject->DraggingPointerStartY;
dragObject->DraggingElementCurrentX = clipXDrag(dragObject,dragObject->DraggingElementStartX+moveX);
dragObject->DraggingElementCurrentY = clipYDrag(dragObject,dragObject->DraggingElementStartY+moveY);
webc_ElementSetXYPosition(dragObject->DraggingElement, dragObject->DraggingElementCurrentX, dragObject->DraggingElementCurrentY);
if (dragObject->cb)
{
DraggingCallbackResponse r = dragObject->cb(hbrowser, hdoc, DRAGGING, dragObject);
switch (r) {
case RESETDRAGGING:
_webc_DragReset(hbrowser,hdoc, dragObject);
return (HTML_EVENT_STATUS_HALT);
case STOPDRAGGING:
break; /* Fall through to up handler */
case KEEPDRAGGING:
default:
return (HTML_EVENT_STATUS_HALT);
}
}
else
break;
}
case HTML_EVENT_MOUSEUP:
{
dragObject = (struct _webcDraghandle *) webc_ElementGetPrivateData(ControlSprite);
if (dragObject && dragObject->Signature == DRAGOBJECTMAGICNUMBER)
{
if (dragObject->cb)
{
DraggingCallbackResponse r = dragObject->cb(hbrowser, hdoc, DONEDRAGGING, dragObject);
switch (r) {
case RESETDRAGGING:
_webc_DragReset(hbrowser,hdoc, dragObject);
return (HTML_EVENT_STATUS_HALT);
case STOPDRAGGING:
case KEEPDRAGGING:
default:
break; /* Fall through to up handler */
}
}
webc_ElementSetPrivateData(ControlSprite,0);
rtp_free(dragObject);
webc_ElementHide(ControlSprite, WEBC_TRUE);
webc_ElementReleasePointer(ControlSprite);
return (HTML_EVENT_STATUS_HALT);
}
}
case HTML_EVENT_KEYDOWN:
printf("Keydown in sprite");
default:
break;
}
return (HTML_EVENT_STATUS_CONTINUE);
}
HELEMENT_HANDLE CreateControlSprite(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc)
{
printf("No control sprite. Fix this \n");
return 0;
}
HELEMENT_HANDLE webc_GetControlSprite(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc)
{
HELEMENT_HANDLE h;
h = webc_DocFindElement(hdoc, "ControlSprite", 0, HTML_ELEMENT_ANY, 0);
if (!h)
h = CreateControlSprite(hbrowser, hdoc);
if (h)
webc_ElementSetTagEventHandler (h, ControlSpriteEventHandler);
return h;
}
/* Start dragging helem. */
struct _webcDraghandle * webc_DragStart(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc, HELEMENT_HANDLE helem, int elemStartX, int elemStartY, DraggingCallbackFunction cb, int x, int y)
{
HELEMENT_HANDLE ControlSprite;
struct _webcDraghandle *dragObject;
ControlSprite = webc_GetControlSprite(hbrowser, hdoc);
if (!ControlSprite)
{
assert(0);
return 0;
}
dragObject = (struct _webcDraghandle *) rtp_malloc(sizeof(* dragObject));
if (!dragObject)
return 0;
rtp_memset(dragObject,0,sizeof(*dragObject));
dragObject->DraggingElement = helem;
dragObject->Signature = DRAGOBJECTMAGICNUMBER;
dragObject->DraggingElementCurrentX = dragObject->DraggingElementStartX = elemStartX; /* Need to validate a way to get position info */
dragObject->DraggingElementCurrentY = dragObject->DraggingElementStartY = elemStartY;
dragObject->DraggingPointerStartX = x;
dragObject->DraggingPointerStartY = y;
dragObject->cb = cb;
webc_ElementSetPrivateData (ControlSprite, (void *) dragObject);
/* Unhide the sprite and move it to the drag position */
webc_ElementHide(ControlSprite, WEBC_FALSE);
webc_SetControlSpritePosition(hbrowser, hdoc,elemStartX, elemStartY);
webc_ElementClaimPointer(ControlSprite);
return dragObject;
}
/*****************************************************************************/
/**
@memo Set an HTML element's inner html
void webc_ElementSetInnerHtmlASCII ( HELEMENT_HANDLE element, char * newhtml)
@doc
Returns the last elemnt in the container, for single object inserts will be
the the last element.
*/
/*****************************************************************************/
HELEMENT_HANDLE webc_ElementAppendInnerHtmlASCII(HELEMENT_HANDLE element, char * newhtml)
{
int OriginalLength = 0;
char *newstring;
char *Original = webc_ElementGetInnerHtmlASCII (element);
if (Original)
{
OriginalLength = rtp_strlen(Original);
}
int NewLength = OriginalLength+rtp_strlen(newhtml);
newstring = (char *) rtp_malloc(NewLength+1);
*newstring = 0;
if (Original)
{
rtp_strcpy(newstring,Original);
webc_FreeASCIIString(Original);
}
rtp_strcat(newstring,newhtml);
webc_ElementSetInnerHtmlASCII (element,newstring);
rtp_free(newstring);
return webc_ElementFixedGetLastChild(element);
}
/* Stop dragging and reset. */
void webc_DragReset(HBROWSER_HANDLE hbrowser, HDOC_HANDLE hdoc, struct _webcDraghandle *dragObject)
{
HELEMENT_HANDLE ControlSprite;
webc_ElementSetXYPosition(dragObject->DraggingElement, dragObject->DraggingElementStartX, dragObject->DraggingElementStartY);
ControlSprite = webc_GetControlSprite(hbrowser, hdoc);
if (ControlSprite)
{
webc_ElementSetPrivateData(ControlSprite,0);
rtp_free(dragObject);
webc_ElementReleasePointer(ControlSprite);
}
}
void webc_ElementRedraw(HELEMENT_HANDLE element)
{
HTMLFlowDisplay *D = (HTMLFlowDisplay *)((HTMLElementContainer *) element)->GetDisplayElement();
if (D)
{
D->Invalidate();
// webc_BrowserInvalidate(hbrowser);
webc_BrowserDraw (webc_DocGetBrowser(webc_ElementGetDocument(element)));
}
}
HELEMENT_HANDLE webc_GetRootContainer(HDOC_HANDLE hdoc)
{
HELEMENT_HANDLE ElResult;
ElResult = webc_DocFindElement(hdoc, "root", 0, HTML_ELEMENT_ANY, 0);
return ElResult;
}
HELEMENT_HANDLE webc_ElementFixedGetLastChild(HELEMENT_HANDLE element)
{
HELEMENT_HANDLE Elem, prevElem, result;
result = Elem = prevElem = 0;
Elem = (HELEMENT_HANDLE) (HELEMENT_OBJ(element)->FirstChild());
while (Elem)
{
result = Elem;
(HELEMENT_HANDLE) (HELEMENT_OBJ(Elem)->mpPrev);
Elem = (HELEMENT_HANDLE) (HELEMENT_OBJ(Elem)->mpPrev);
}
return result;
}
/* New function was put in API, may need to document */
//void webc_ElementCancelTimers(HBROWSER_HANDLE hbrowser, HELEMENT_HANDLE el)
//{
// HBROWSER_OBJ(hbrowser)->TimeoutManager()->CancelTimeout(_matchElement, &el, WEBC_TRUE);
//}
|
Python | UTF-8 | 8,037 | 3.96875 | 4 | [] | no_license | #%% TensorFlow 变量是用于表示程序处理的共享持久状态的推荐方法。本指南介绍在 TensorFlow 中如何创建、更新和管理 tf.Variable 的实例。
#变量通过 tf.Variable 类进行创建和跟踪。tf.Variable 表示张量,对它执行运算可以改变其值。
# 利用特定运算可以读取和修改此张量的值。更高级的库(如 tf.keras)使用 tf.Variable 来存储模型参数。
#%% 1 设置
# 本笔记本讨论变量布局。如果要查看变量位于哪一个设备上,请取消注释这一行代码。
import tensorflow as tf
# Uncomment to see where your variables get placed (see below)
# tf.debugging.set_log_device_placement(True)
#%% 2 创建变量
# 要创建变量,请提供一个初始值。tf.Variable 与初始值的 dtype 相同。
my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
my_variable = tf.Variable(my_tensor)
# Variables can be all kinds of types, just like tensors
bool_variable = tf.Variable([False, False, False, True])
complex_variable = tf.Variable([5 + 4j, 6 + 1j])
# 变量与张量的定义方式和操作行为都十分相似,实际上,它们都是 tf.Tensor 支持的一种数据结构。与张量类似,变量也有 dtype 和形状,并且可以导出至 NumPy。
# 大部分张量运算在变量上也可以按预期运行,不过变量无法重构形状。
print("A variable:",my_variable)
print("\nViewed as a tensor:", tf.convert_to_tensor(my_variable))
print("\nIndex of highest value:", tf.argmax(my_variable))
# This creates a new tensor; it does not reshape the variable.
print("\nCopying and reshaping: ", tf.reshape(my_variable, ([1,4])))
# 如上所述,变量由张量提供支持。您可以使用 tf.Variable.assign 重新分配张量。调用 assign(通常)不会分配新张量,而会重用现有张量的内存。
a = tf.Variable([2.0, 3.0])
# This will keep the same dtype, float32
a.assign([1, 2])
# Not allowed as it resizes the variable:
try:
a.assign([1.0, 2.0, 3.0])
except Exception as e:
print(f"{type(e).__name__}: {e}")
# 如果在运算中像使用张量一样使用变量,那么通常会对支持张量执行运算。
# 从现有变量创建新变量会复制支持张量。两个变量不能共享同一内存空间。
a = tf.Variable([2.0, 3.0])
# Create b based on the value of a
b = tf.Variable(a)
a.assign([5, 6])
# a and b are different
print(a.numpy())
print(b.numpy())
# There are other versions of assign
print(a.assign_add([2,3]).numpy()) # [7. 9.]
print(a.assign_sub([7,9]).numpy()) # [0. 0.]
#%% 3 生命周期、命名和监视
# 在基于 Python 的 TensorFlow 中,tf.Variable 实例与其他 Python 对象的生命周期相同。如果没有对变量的引用,则会自动将其解除分配。
# 为了便于跟踪和调试,您还可以为变量命名。两个变量可以使用相同的名称。
# Create a and b; they have the same value but are backed by different tensors.
a = tf.Variable(my_tensor, name="Mark")
# A new variable with the same name, but different value
# Note that the scalar add is broadcast
b = tf.Variable(my_tensor + 1, name="Mark")
print(a == b)
# 保存和加载模型时会保留变量名。默认情况下,模型中的变量会自动获得唯一变量名,所以除非您希望自行命名,否则不必多此一举。
# 虽然变量对微分很重要,但某些变量不需要进行微分。在创建时,通过将 trainable 设置为 False 可以关闭梯度。例如,训练计步器就是一个不需要梯度的变量。
step_counter = tf.Variable(1, name='Steps', trainable=False)
#%% 4 放置变量和张量
# 为了提高性能,TensorFlow 会尝试将张量和变量放在与其 dtype 兼容的最快设备上。这意味着如果有 GPU,那么大部分变量都会放置在 GPU 上。
# 不过,我们可以重写变量的位置。在以下代码段中,即使存在可用的 GPU,我们也可以将一个浮点张量和一个变量放置在 CPU 上。
# 通过打开设备分配日志记录(参阅设置),可以查看变量的所在位置。
# 注:虽然可以手动放置变量,但使用分布策略是一种可优化计算的更便捷且可扩展的方式。
with tf.device('CPU:0'):
# Create some tensors
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
# 您可以将变量或张量的位置设置在一个设备上,然后在另一个设备上执行计算。但这样会产生延迟,因为需要在两个设备之间复制数据。
# 不过,如果您有多个 GPU 工作进程,但希望变量只有一个副本,则可以这样做。
with tf.device('CPU:0'):
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.Variable([[1.0, 2.0, 3.0]])
with tf.device('GPU:0'):
# Element-wise multiply
k = a * b
print(k)
# 注:由于 tf.config.set_soft_device_placement 默认处于打开状态,所以,即使在没有 GPU 的设备上运行此代码,它也会运行,只不过乘法步骤在 CPU 上执行。
#%% Part 2 自动微分和梯度带 - 梯度带
# 在上一个教程中,我们介绍了 "张量"(Tensor)及其操作。本教程涉及自动微分(automatic differentitation),它是优化机器学习模型的关键技巧之一。
# TensorFlow 为自动微分提供了 tf.GradientTape API ,根据某个函数的输入变量来计算它的导数。
# Tensorflow 会把 'tf.GradientTape' 上下文中执行的所有操作都记录在一个磁带上 ("tape")。 然后基于这个磁带和每次操作产生的导数,
# 用反向微分法("reverse mode differentiation")来计算这些被“记录在案”的函数的导数。
x = tf.ones((2, 2))
with tf.GradientTape() as t:
t.watch(x)
y = tf.reduce_sum(x)
z = tf.multiply(y, y)
# Derivative of z with respect to the original input tensor x
dz_dx = t.gradient(z, x)
for i in [0, 1]:
for j in [0, 1]:
assert dz_dx[i][j].numpy() == 8.0
# 你也可以使用 tf.GradientTape 上下文计算过程产生的中间结果来求取导数。
x = tf.ones((2, 2))
with tf.GradientTape() as t:
t.watch(x)
y = tf.reduce_sum(x)
z = tf.multiply(y, y)
# Use the tape to compute the derivative of z with respect to the
# intermediate value y.
dz_dy = t.gradient(z, y)
assert dz_dy.numpy() == 8.0
#%% 默认情况下,调用 GradientTape.gradient() 方法时, GradientTape 占用的资源会立即得到释放。通过创建一个持久的梯度带,可以计算同个函数的多个导数。
# 这样在磁带对象被垃圾回收时,就可以多次调用 'gradient()' 方法。例如:
x = tf.constant(3.0)
with tf.GradientTape(persistent=True) as t:
t.watch(x)
y = x * x
z = y * y
dz_dx = t.gradient(z, x) # 108.0 (4*x^3 at x = 3)
dy_dx = t.gradient(y, x) # 6.0
del t # Drop the reference to the tape
#%% 2 记录控制流
# 由于磁带会记录所有执行的操作,Python 控制流(如使用 if 和 while 的代码段)自然得到了处理。
def f(x, y):
output = 1.0
for i in range(y):
if i > 1 and i < 5:
output = tf.multiply(output, x)
return output
def grad(x, y):
with tf.GradientTape() as t:
t.watch(x)
out = f(x, y)
return t.gradient(out, x)
x = tf.convert_to_tensor(2.0)
assert grad(x, 6).numpy() == 12.0
assert grad(x, 5).numpy() == 12.0
assert grad(x, 4).numpy() == 4.0
#%% 3 高阶导数
# 在 'GradientTape' 上下文管理器中记录的操作会用于自动微分。如果导数是在上下文中计算的,导数的函数也会被记录下来。
# 因此,同个 API 可以用于高阶导数。例如:
x = tf.Variable(1.0) # Create a Tensorflow variable initialized to 1.0
with tf.GradientTape() as t:
with tf.GradientTape() as t2:
y = x * x * x
# Compute the gradient inside the 't' context manager
# which means the gradient computation is differentiable as well.
dy_dx = t2.gradient(y, x)
d2y_dx2 = t.gradient(dy_dx, x)
assert dy_dx.numpy() == 3.0
assert d2y_dx2.numpy() == 6.0
|
Python | UTF-8 | 608 | 3.140625 | 3 | [] | no_license | import math
import os
import random
import re
import sys
import collections
#
# Complete the 'sherlockAndAnagrams' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def sherlockAndAnagrams(s):
anagrams = collections.Counter()
count = 0
for i in range(len(s)):
for j in range(i, len(s)):
cnt = frozenset(collections.Counter(s[i:j+1]).items())
anagrams[cnt] += 1
for key in anagrams:
count += anagrams[key] * (anagrams[key] - 1)// 2
return count
print(sherlockAndAnagrams('cdcd'))
|
JavaScript | UTF-8 | 820 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive |
var jsontext = '[{"id":1,"domainId":"altran","name":"altranName","description":""},{"id":2,"domainId":"osl","name":"OsloAirport","description":""},{"id":3,"domainId":"paal","name":"Paal","description":""},{"id":4,"domainId":"bli","name":"BardLind","description":""},{"id":5,"domainId":"demo.synxbios.com","name":"SynxDemo","description":""}]';
var domains = [];
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element.domainId);
domains.push(element.domainId);
}
var ls = JSON.parse(jsontext);
ls.forEach(logArrayElements);
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
var hasDomain = contains(domains,'altraN');
console.log("domains has domain:" + domains);
|
Python | UTF-8 | 609 | 3.203125 | 3 | [] | no_license | #!/usr/bin/python3
""" modules for method """
def island_perimeter(grid):
""" Method to caclc the perimeter """
perimeter = 0
for y, r in enumerate(grid):
for x, c in enumerate(r):
if c == 1:
if y == 0 or grid[y - 1][x] == 0:
perimeter += 1
if x == 0 or grid[y][x - 1] == 0:
perimeter += 1
if y == len(grid) - 1 or grid[y + 1][x] == 0:
perimeter += 1
if x == len(r) - 1 or grid[y][x + 1] == 0:
perimeter += 1
return perimeter
|
Java | UTF-8 | 1,356 | 2.078125 | 2 | [] | no_license | package com.android.sensorsapp.ui.fragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import com.android.sensorsapp.ui.activity.TabBarActivity;
import butterknife.ButterKnife;
public class BaseFragment extends Fragment {
protected String title;
protected boolean hasParent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
((TabBarActivity) getActivity()).closeScreenIfNeeded();
return true;
default:
break;
}
return false;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean hasParent() { return hasParent; }
public void setHasParent(boolean hasParent) { this.hasParent = hasParent; }
}
|
Java | UTF-8 | 715 | 2.90625 | 3 | [] | no_license | public class Sprinkles extends SugarCookie{
private int sprinkles;
public Sprinkles(int oT, int s){
super(oT);
sprinkles = s;
}
@Override
public String getIngrediants(){
return super.getIngrediants() + "sprinkles: " + sprinkles;
}
@Override
public String getRecipe(){
return super.getRecipe() + "add "+ sprinkles + " sprinkles too";
}
@Override
public String[] getImage(){
String[] s = {"__________",
"| . . |" ,
"| . |" ,
"| . .|" ,
"__________" };
return s;
}
public int getSprinkles(){
return sprinkles;
}
} |
Java | UTF-8 | 5,632 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.ui.wizard;
import com.android.ide.common.repository.GradleVersion;
import com.android.tools.adtui.validation.Validator;
import com.android.tools.idea.gradle.plugin.AndroidPluginInfo;
import com.android.tools.idea.wizard.template.Category;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.RecentProjectsManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PathUtil;
import com.intellij.util.SystemProperties;
import org.jetbrains.android.util.AndroidBundle;
import org.jetbrains.android.util.AndroidUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Static utility methods useful across wizards
*/
public final class WizardUtils {
// TODO: parentej needs to be updated to 4.0.0 when released
public static final String COMPOSE_MIN_AGP_VERSION = "4.0.0-alpha02";
/**
* The package is used to create a directory (eg: MyApplication/app/src/main/java/src/my/package/name)
* A windows directory path cannot be longer than 250 chars
* On unix/mac a directory name cannot be longer than 250 chars
* On all platforms, aapt fails with really cryptic errors if the package name is longer that ~200 chars
* Having a sane length for the package also seems a good thing
*/
private static final int PACKAGE_LENGTH_LIMIT = 100;
/**
* Returns the parent directory which the last project was created into or a reasonable default
* if this will be the first project a user has created. Either way, the {@link File} returned
* should be a strong candidate for a home for the next project.
*/
@NotNull
public static File getProjectLocationParent() {
String parent = RecentProjectsManager.getInstance().getLastProjectCreationLocation();
if (parent != null) {
return new File(PathUtil.toSystemDependentName(parent));
}
String defaultProjectLocation = GeneralSettings.getInstance().getDefaultProjectDirectory();
if (defaultProjectLocation != null && !defaultProjectLocation.isEmpty()) {
return new File(defaultProjectLocation);
}
String child = ApplicationNamesInfo.getInstance().getFullProductName().replace(" ", "") + "Projects";
return new File(SystemProperties.getUserHome(), child);
}
@Nullable
public static String validatePackageName(@Nullable String packageName) {
packageName = (packageName == null) ? "" : packageName;
if (packageName.length() >= PACKAGE_LENGTH_LIMIT) {
return AndroidBundle.message("android.wizard.module.package.too.long");
}
return AndroidUtils.validateAndroidPackageName(packageName);
}
/**
* Wrap a target string with {@code <html></html>} if it's not already so wrapped, and replaces NewLines with html breaks. This is useful
* as various Swing components (particularly labels) act slightly differently with html input.
*/
@NotNull
public static String toHtmlString(@NotNull String text) {
if (!StringUtil.isEmpty(text) && !text.startsWith("<html>")) {
text = text.trim().replaceAll("\n", "<br>");
return String.format("<html>%1$s</html>", text);
}
return text;
}
/**
* Utility method used to create a URL from its String representation without throwing a {@link MalformedURLException}.
* Callers should use this if they're absolutely certain their URL is well formatted.
*/
@NotNull
public static URL toUrl(@NotNull String urlAsString) {
URL url;
try {
url = new URL(urlAsString);
}
catch (MalformedURLException e) {
// Caller should guarantee this will never happen!
throw new RuntimeException(e);
}
return url;
}
/**
* Utility method that returns a unique name using an initial seed and a {@link Validator}
* @return The supplied initialValue if its valid (as per the return of {@link Validator}, or the initialValue contatenated with an
* {@link Integer} value that will be valid.
*/
public static String getUniqueName(String initialValue, Validator<? super String> validator) {
int i = 2;
String uniqueName = initialValue;
while (i <= 100 && validator.validate(uniqueName).getSeverity() == Validator.Severity.ERROR) {
uniqueName = initialValue + i;
i++;
}
return uniqueName;
}
public static boolean hasComposeMinAgpVersion(@Nullable Project project, Category category) {
if (project == null || !Category.Compose.equals(category)) {
return true;
}
AndroidPluginInfo androidPluginInfo = AndroidPluginInfo.findFromModel(project);
if (androidPluginInfo == null) {
return true;
}
GradleVersion agpVersion = androidPluginInfo.getPluginVersion();
if (agpVersion == null) {
return true;
}
return agpVersion.compareTo(COMPOSE_MIN_AGP_VERSION) >= 0;
}
}
|
Java | UTF-8 | 3,249 | 3.078125 | 3 | [] | no_license | package annees.annee2019.jour24;
public class Grille extends Case {
private Case[][] map;
private Grille parent;
private Grille enfant;
private int position;
public Grille() {
super(2, 2);
map = new Case[5][5];
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 5; i++) {
Case c = new Case(i, j);
map[j][i] = c;
if (i > 0) {
c.setOuest(map[j][i - 1]);
}
if (j > 0) {
c.setNord(map[j - 1][i]);
}
}
}
}
public Grille ajouterGrille() {
boolean insecte = false;
a: for (int i = 0; i < getMap().length; i++) {
for (int j = 0; j < getMap()[i].length; j++) {
if (!map[i][j].isGrille() && map[i][j].isInsecte()) {
insecte = true;
break a;
}
}
}
if (insecte) {
if (parent == null) {
return ajouterGrilleExterieur();
}
if (enfant == null) {
return ajouterGrilleCentrale();
}
}
return null;
}
public Grille ajouterGrilleCentrale() {
Grille grille = new Grille();
map[2][2] = grille;
grille.parent = this;
enfant = grille;
grille.position = position - 1;
for (int i = 0; i < map.length; i++) {
grille.map[i][0].getCasesAdjacentes().add(map[2][1]);
map[2][1].getCasesAdjacentes().add(grille.map[i][0]);
}
for (int i = 0; i < map.length; i++) {
grille.map[i][4].getCasesAdjacentes().add(map[2][3]);
map[2][3].getCasesAdjacentes().add(grille.map[i][4]);
}
for (int i = 0; i < map[0].length; i++) {
grille.map[0][i].getCasesAdjacentes().add(map[1][2]);
map[1][2].getCasesAdjacentes().add(grille.map[0][i]);
}
for (int i = 0; i < map[0].length; i++) {
grille.map[4][i].getCasesAdjacentes().add(map[3][2]);
map[3][2].getCasesAdjacentes().add(grille.map[4][i]);
}
return grille;
}
public Grille ajouterGrilleExterieur() {
Grille grille = new Grille();
parent = grille;
grille.enfant = this;
grille.map[2][2] = this;
grille.position = position + 1;
for (int i = 0; i < map.length; i++) {
map[i][0].getCasesAdjacentes().add(grille.map[2][1]);
grille.map[2][1].getCasesAdjacentes().add(map[i][0]);
}
for (int i = 0; i < map.length; i++) {
map[i][4].getCasesAdjacentes().add(grille.map[2][3]);
grille.map[2][3].getCasesAdjacentes().add(map[i][4]);
}
for (int i = 0; i < map[0].length; i++) {
map[0][i].getCasesAdjacentes().add(grille.map[1][2]);
grille.map[1][2].getCasesAdjacentes().add(map[0][i]);
}
for (int i = 0; i < map[0].length; i++) {
map[4][i].getCasesAdjacentes().add(grille.map[3][2]);
grille.map[3][2].getCasesAdjacentes().add(map[4][i]);
}
return grille;
}
public boolean isGrille() {
return true;
}
public Case[][] getMap() {
return map;
}
public void setMap(Case[][] map) {
this.map = map;
}
public void visualiserMap() {
System.out.println(position);
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
Case case1 = map[i][j];
if (case1.isInsecte()) {
System.out.print("#");
} else {
System.out.print(".");
}
}
System.out.println();
}
System.out.println();
System.out.println();
}
@Override
public int compareTo(Case o) {
if (o instanceof Grille) {
return -Integer.compare(position, ((Grille) o).position);
}
return -1;
}
}
|
Markdown | UTF-8 | 5,929 | 3.953125 | 4 | [] | no_license | ---
layout: topic
title: Строки
permalink: topics/string/
---
**Строка** в C++ представляет собой особый класс. Класс, в терминах программирования, это элемент, описывающий абстрактный тип данных. Это означает, что для строки определены особые функции - методы.
Чтобы пользоваться строками, необходимо подключить заголовочный файл <string>:
{% highlight cpp %}
#include <string>
{% endhighlight %}
Объявление строк схоже с объявлением переменной.
{% highlight cpp %}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
s = "Hello!";
cout << s << endl;
return 0;
}
{% endhighlight %}
Строка также представляет собой массив символов. Значит, чтобы получить конкретный символ, можно использовать следующее:
{% highlight cpp %}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
s = "Hello!";
cout << s[2] << endl;
return 0;
}
{% endhighlight %}
Этот код выведет третий символ строки s.
## Методы string
Для начала следует сказать, что для строки определены итераторы **begin()** и **end()**. Указывающие соответственно на первый и на последний символы.
* **s.size() / s.lenght()**
Возвращает длину строки s. В следующем коде мы циклом идем по строке и выводим каждый символ.
{% highlight cpp %}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
for (int i = 0; i < s.size(); i++)
{
cout << s[i];
}
return 0;
}
{% endhighlight %}
* **s.append(s1)**
Данная функция добавляет строку s1 в конец строки s.
{% highlight cpp %}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "a";
string s1 = "b";
s.append(s1); // идентично s += s1
cout << s << endl;
cout << s + s1 << endl;
return 0;
}
{% endhighlight %}
* **s.erase()**
Данная функция имеет несколько перегрузок:
| s.erase(pos,n)| удаляет n символов начиная с позиции pos |
| s.erase(iterator) | iterator - это итератор, указывающий на символ. В результате применения функции этот символ будет удален|
| s.erase(it begin, it end) | it begin, it end - итераторы, указывающие на начало и конец удаляемой последовательности |
{% highlight cpp %}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdef";
s.erase(1,2); // adef
string str = "abcdef";
str.erase(str.begin()); // bcdef
string sp = "abcdef";
sp.erase(sp.begin() + 1, sp.end()); // a
}
{% endhighlight %}
В данном коде показаны преобразования строки, сделанные erase().
* **s.find(ch)**
Возвращает позицию, с которой ch входит в s. В свою очередь ch может быть отдельным символом или строкой. Если ch не найдено, возвращает string::npos.
* **s.substr(pos,n)**
Возвращает подстроку из n символов начиная с позиции pos.
* **Перевод строки в число и наоборот**
Когда возникает потребность перевести число в строку, может пригодиться функция stoi:
{% highlight cpp %}
string s;
cin >> s;
int n = stoi(s);
cout << n;
{% endhighlight %}
Если же нам нужно перевести число в строку, воспульзуемся функцией to_string:
{% highlight cpp %}
int n;
cin >> n;
string s = to_string(n);
cout << s;
{% endhighlight %}
## Символьные функции
Иногда нам нужно отвечать на вопрос: а является ли символ буквой, цифрой, знаком пунктуации etc? Тогда нам могут помочь символьные функции. Они принимают на вход символ и возвращают логическое значение.
| isalpha(char) | true, если буква |
| ispunct(char) | true, если знак пунктуации |
| isdigit(char) | true, если десятичная цифра |
| isspace(char) | true, если пробел |
| islower(char) | true, если символ нижнего регистра |
| isupper(char) | true, если символ вернего регистра |
| tolower(char) | возвращает char в нижнем регистре |
| toupper(char) | возвращает char в верхнем регистре |
## Решение задачи : проверка на палиндромность
Создадим логическую функцию, с помощью которой будем определять, является ли строка палиндромом. Напомним, что палиндром - строка, которая читается одинаково с начала и с конца. Например, abba - палиндром.
{% highlight cpp %}
bool palindrome(string s)
{
for (int i = 0; i < s.size() / 2; i++)
if (s[i] != s[s.size() - 1 - i])
return false;
return true;
}
{% endhighlight %}
|
Python | UTF-8 | 184 | 2.890625 | 3 | [] | no_license | def shape_area(n):
a = 1
b = 0
i = 0
if n == 1:
return 1
while n - 1 >= a:
i = n + a
a = a + 1
b = n * i + 1
b = b - n
return b
|
Python | UTF-8 | 1,045 | 2.84375 | 3 | [
"MIT"
] | permissive | # import math
import random
import numpy
# from effectlayer import *
# from effects.color_palette_library import *
# import random
class ColorPaletteLibrary:
def __init__(self):
self.palettes = [
[0x4CFF00, 0x009BC2, 0x85E7FF, 0x00CCFF, 0xB300FF],
[0x33AA99, 0x66EE88, 0x00DDFF, 0x22FFFF, 0xFFEE55],
[0x4C2A14, 0xEC5A00, 0xFFA200, 0xFFFF00, 0xFFFFC3],
[0x62A9F0, 0x517506, 0x68C51C, 0xBEB940, 0xEDFA25],
[0x8AC97B, 0xE8AFBA, 0xE8C1AF, 0xDDAFE8, 0x6BB1D1],
[0x45B29D, 0xE27A3F, 0xDF4949, 0xE8B37D, 0xEFC94C]
]
def getPalette(self):
randomPalette = random.choice(self.palettes)
return self.generatePalette(randomPalette)
def generatePalette(self, hexValues):
def convertColor(val):
r = (val & 0xff0000) >> 16
g = (val & 0x00ff00) >> 8
b = (val & 0x0000ff)
return numpy.array([r/255., g/255., b/255.])
return [ convertColor(val) for val in hexValues ]
|
Swift | UTF-8 | 2,210 | 2.828125 | 3 | [] | no_license | //
// ContentView.swift
// TravelApp
//
// Created by Shreyak Godala on 04/05/21.
//
import SwiftUI
import Kingfisher
struct NavigationLazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}
struct DiscoverView: View {
init() {
UINavigationBar.appearance().largeTitleTextAttributes = [
.foregroundColor : UIColor.white
]
}
@Environment(\.colorScheme) var colorScheme
var body: some View {
NavigationView {
ZStack {
LinearGradient(gradient: Gradient(colors: [Color.orange, Color.red]), startPoint: .top, endPoint: .center)
.ignoresSafeArea()
Color.defaultBackground.offset(y: 400)
ScrollView {
HStack() {
Image(systemName: "magnifyingglass")
Text("Where do you want to go?")
Spacer()
}.font(.system(size: 14, weight: .semibold))
.foregroundColor(.white)
.padding()
.background(Color(white: 1, opacity: 0.3))
.cornerRadius(12)
.padding()
DiscoveryCategoryView()
VStack {
PopularDestinationsView()
PopularRestaurantsView()
TrendingCreatorsView()
}
// .background(Color(white: 0.95, opacity: 1))
.background(Color.defaultBackground)
.cornerRadius(16)
.padding(.top, 32)
}
}
.navigationTitle("Discovery")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
DiscoverView()
}
}
|
Python | UTF-8 | 822 | 3.328125 | 3 | [] | no_license | # coding:utf-8
'''
@Copyright:LintCode
@Author: CodeWTKH
@Problem: http://www.lintcode.com/problem/compare-strings
@Language: Python
@Datetime: 17-05-30 20:10
'''
class Solution:
"""
@param A : A string includes Upper Case letters
@param B : A string includes Upper Case letters
@return : if string A contains all of the characters in B return True else return False
"""
def compareStrings(self, A, B):
# write your code here
if not A and B:
return False
a = []
for c in A:
a.append(c)
for c in B:
for i in range(len(a)):
if a[i] == c:
a[i] = '.'
break
if i == len(a) - 1:
return False
return True |
Python | UTF-8 | 598 | 3.546875 | 4 | [] | no_license | # Evaluate RPN EX
def evalRPN(tokens):
ops = {"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: int(float(a) / b)}
stack = []
for i in tokens:
if i in ops:
a = stack.pop()
b = stack.pop()
stack.append(ops[i](b, a))
else:
stack.append(int(i))
print stack, i
print stack
return stack[0]
if __name__ == '__main__':
test_case = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
print evalRPN(test_case) |
Python | UTF-8 | 1,102 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python3
from argparse import ArgumentParser
from datetime import datetime
from subprocess import call
def main(arguments):
chore = arguments.chore.replace("'", "\'")
due_date = arguments.due_date
sql = f"CALL change_due_date('{chore}', '{due_date}', @c)"
command = ["chore-database", sql]
if arguments.preview:
command.append("--preview")
if arguments.verbose:
command.append("--verbose")
call(command)
def parse_arguments():
parser = ArgumentParser(description="Change the due date of a chore.")
parser.add_argument("chore", help="The chore whose due date to change.")
date = lambda s: datetime.strptime(s, "%Y-%m-%d")
parser.add_argument("due_date", type=date, help="The new due date.")
parser.add_argument("--preview", action="store_true", help="Show the SQL command but do not execute it.")
parser.add_argument("-v", "--verbose", action="store_true", help="Show SQL commands as they are executed.")
return parser.parse_args()
if __name__ == "__main__":
arguments = parse_arguments()
main(arguments)
|
C++ | UTF-8 | 1,295 | 2.875 | 3 | [] | no_license |
/*
* AssistorLog.h
*
* Created on: Mar 11, 2015
* Author: root
*/
#ifndef ASSISTORLOG_H_
#define ASSISTORLOG_H_
#include "log/log.h"
#include <sstream>
using namespace std;
class AssistorLog{
public:
enum LogType{
FILE = 0,
FILE_TS = 1,
CERR = 2
};
static void init_log_system(LogType ltype,
Log::MessageType clevel,
const char *filename = NULL,
ios_base::openmode mode = ios_base::trunc){
switch(ltype){
case FILE:
AssistorLog::logger = new FileLog(filename, clevel, mode);
break;
case FILE_TS:
AssistorLog::logger = new FileLogTS(filename, clevel, mode);
break;
default:
AssistorLog::logger = new CerrLog(clevel);
break;
}
}
static void finalize_log_system(){
delete logger;
}
static void log(const char *module,
const Log::MessageType type,
const char *message){
logger->log(module, type, message);
}
static void log(const char *module,
const Log::MessageType type,
const ostringstream &message){
logger->log(module, type, message.str().c_str());
}
static void log(const char *module,
const Log::MessageType type,
const string &message){
logger->log(module, type, message.c_str());
}
private:
AssistorLog(){}
~AssistorLog(){}
static Log *logger;
};
#endif /* INC_LOG_ASSISTORLOG_H_ */
|
JavaScript | UTF-8 | 427 | 4.4375 | 4 | [] | no_license | // define arrow function
let sum = (a, b) => a + b;
console.log( sum(1,2) );
/*
shorter version of
let sum = function(a, b) {
return a + b;
}
*/
// parentheses optional if 1 argument
let dbl = a => a * 2;
console.log( dbl(1) );
// multiline arrow function
// return statement needed
let sum2 = (a, b) => {
let result = a + b;
return result;
}
console.log( sum2(3,4) );
// arrow functions don't have a 'this' |
SQL | UTF-8 | 4,114 | 3.578125 | 4 | [] | no_license | -- Houston Real Estate SQL
-- Drop tables if they exist
DROP TABLE IF EXISTS "property_school";
DROP TABLE IF EXISTS "appraisal";
DROP TABLE IF EXISTS "properties";
DROP TABLE IF EXISTS "crime";
DROP TABLE IF EXISTS "school";
DROP TABLE IF EXISTS "neighborhoods";
DROP TABLE IF EXISTS "school_district";
DROP TABLE IF EXISTS "flood_zone";
DROP TABLE IF EXISTS "zip_code";
-- Create tables
CREATE TABLE "zip_code" (
"zip_code" INT NOT NULL,
CONSTRAINT "pk_zip_code" PRIMARY KEY (
"zip_code"
)
);
CREATE TABLE "flood_zone" (
"Flood_Description" TEXT NOT NULL,
"Flood_Zone" VARCHAR(2) NOT NULL,
CONSTRAINT "pk_flood_zone" PRIMARY KEY (
"Flood_Description"
)
);
CREATE TABLE "school_district" (
"district_id" INT NOT NULL,
"district_name" TEXT NOT NULL,
CONSTRAINT "pk_school_district" PRIMARY KEY (
"district_id"
)
);
CREATE TABLE "neighborhoods" (
"neighborhood_code" NUMERIC NOT NULL,
"neighborhood" VARCHAR(300) NOT NULL,
CONSTRAINT "pk_neighborhoods" PRIMARY KEY (
"neighborhood_code"
)
);
CREATE TABLE "school" (
"school_id" INT NOT NULL,
"school_type" TEXT NOT NULL,
"name" TEXT NOT NULL,
"address" TEXT NOT NULL,
"city" TEXT NOT NULL,
"zip_code" VARCHAR(5) NOT NULL,
"district_id" INT NOT NULL,
"latitude" NUMERIC NOT NULL,
"longitude" NUMERIC NOT NULL,
"school_rating" INT NOT NULL,
CONSTRAINT "pk_school" PRIMARY KEY (
"school_id","school_type"
)
);
CREATE TABLE "crime" (
"id" SERIAL NOT NULL,
"Incident" INT,
"Date" DATE,
"Hour" INT,
"NIBRS_Class" VARCHAR(100),
"NIBRS_Description" VARCHAR(100),
"Offense_Count" INT,
"Premise" VARCHAR(100),
"Block_Range" VARCHAR(20),
"Street_Name" VARCHAR(50),
"Street_Type" VARCHAR(10),
"City" VARCHAR(50),
"Zip_Code" INT NOT NULL,
CONSTRAINT "pk_crime" PRIMARY KEY (
"id"
)
);
CREATE TABLE "properties" (
"account" BIGINT NOT NULL,
"latitude" NUMERIC NOT NULL,
"longitude" NUMERIC NOT NULL,
"address" VARCHAR(300) NOT NULL,
"zip_code" INT NOT NULL,
"neighborhood_code" NUMERIC NOT NULL,
"acreage" NUMERIC NOT NULL,
"new_owner_date" DATE NOT NULL,
"sq_ft" NUMERIC,
"flood_description" TEXT,
CONSTRAINT "pk_properties" PRIMARY KEY (
"account"
)
);
CREATE TABLE "appraisal" (
"id" SERIAL NOT NULL,
"account" BIGINT NOT NULL,
"land_value" NUMERIC NOT NULL,
"total_appraised_value" NUMERIC NOT NULL,
"total_market_value" NUMERIC NOT NULL,
"tax_year" INT NOT NULL,
CONSTRAINT "pk_appraisal" PRIMARY KEY (
"id"
)
);
CREATE TABLE "property_school" (
"account" BIGINT NOT NULL,
"school_id" INT NOT NULL,
"school_type" TEXT NOT NULL,
CONSTRAINT "pk_property_school" PRIMARY KEY (
"account","school_id","school_type"
)
);
ALTER TABLE "school" ADD CONSTRAINT "fk_school_district_id" FOREIGN KEY("district_id")
REFERENCES "school_district" ("district_id");
ALTER TABLE "properties" ADD CONSTRAINT "fk_properties_zip_code" FOREIGN KEY("zip_code")
REFERENCES "zip_code" ("zip_code");
ALTER TABLE "properties" ADD CONSTRAINT "fk_properties_neighborhood_code" FOREIGN KEY("neighborhood_code")
REFERENCES "neighborhoods" ("neighborhood_code");
ALTER TABLE "properties" ADD CONSTRAINT "fk_properties_flood_description" FOREIGN KEY("flood_description")
REFERENCES "flood_zone" ("Flood_Description");
ALTER TABLE "appraisal" ADD CONSTRAINT "fk_appraisal_account" FOREIGN KEY("account")
REFERENCES "properties" ("account");
ALTER TABLE "crime" ADD CONSTRAINT "fk_crime_Zip_Code" FOREIGN KEY("Zip_Code")
REFERENCES "zip_code" ("zip_code");
ALTER TABLE "property_school" ADD CONSTRAINT "fk_property_school_account" FOREIGN KEY("account")
REFERENCES "properties" ("account");
ALTER TABLE "property_school" ADD CONSTRAINT "fk_property_school_school_id_school_type" FOREIGN KEY("school_id", "school_type")
REFERENCES "school" ("school_id", "school_type");
|
Java | UTF-8 | 380 | 1.625 | 2 | [] | no_license | package com.basic;
import java.util.Scanner;
public class savingaccount {
public static void main(String[] args) {
}
}
class amount{
private SavingBalance
private void CalculateMonthlyInterest()
{
0
.
}
} |
Java | UTF-8 | 348 | 1.84375 | 2 | [] | no_license | package course.spring.webfluxdemo.dao;
import course.spring.webfluxdemo.model.Article;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import reactor.core.publisher.Flux;
public interface ArticlesReactiveRepository extends ReactiveMongoRepository<Article, String> {
Flux<Article> findAllByAuthor(String author);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.