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 |
|---|---|---|---|---|---|---|---|
Markdown | UTF-8 | 2,274 | 3.0625 | 3 | [
"MIT"
] | permissive | # [Cook — A Modern Build System](https://getcook.org/)
:snowflake: **Development is paused for now but may be resumed in the future.**
:zap: **This software is currently in alpha and not ready for production use.**
:heart: **Contributions to this project are very welcome!**
## Overview
Cook is an extensible, dynamic, parallel and cross-platform
build system. It is based on the concept that writing build definitions should
be as powerful and easy as possible, which is why everything in Python. While
many other systems may be slightly faster in benchmarks, we believe that, at
least for most projects, these differences do not outweigh the advantages you
get by using a more powerful system.
## Example
Using the built-in rules is straightforward. You just import the corresponding
module and call the supplied rule. This is all you need to get a working build
going. The following example will automatically work on any supported platform.
```python
from cook import cpp
cpp.executable(
sources=['main.cpp'],
destination='main'
)
```
Executing this script will build an executable using the correct
platform-specific details. For example, the output is either named `main` or
`main.exe` depending on the operating system.
```
$ ls
BUILD.py main.cpp main.h
$ cook
[ 0%] Compile main.cpp
[ 50%] Link build/main
[100%] Done.
$ ls build/
main
```
You can also easily create your own rules. Upon calling, they are executed
until the required information is passed back to the system using
`yield core.publish(...)`. Everything after that is executed shortly after if
the system decides it is necessary to do so.
```python
from cook import core
@core.rule
def replace(source, destination, mapping):
source = core.resolve(source)
destination = core.build(destination)
yield core.publish(
inputs=[source],
message='Generating {}'.format(destination),
outputs=[destination],
check=mapping
)
with open(source) as file:
content = file.read()
for key, value in mapping.items():
content = content.replace(key, value)
with open(destination, 'w') as file:
file.write(content)
```
Please look at [the documentation](https://getcook.org/docs/) if you want to
know more.
|
Ruby | UTF-8 | 1,534 | 3.203125 | 3 | [
"MIT"
] | permissive | #
# IRCUtil is a module that contains utility functions for use with the
# rest of Ruby-IRC. There is nothing required of the user to know or
# even use these functions, but they are useful for certain tasks
# regarding IRC connections.
#
module IRCUtil
#
# Matches hostmasks against hosts. Returns t/f on success/fail.
#
# A hostmask consists of a simple wildcard that describes a
# host or class of hosts.
#
# f.e., where the host is 'bar.example.com', a host mask
# of '*.example.com' would assert.
#
def assert_hostmask(host, hostmask)
return !!host.match(quote_regexp_for_mask(hostmask))
end
module_function :assert_hostmask
#
# A utility function used by assert_hostmask() to turn hostmasks
# into regular expressions.
#
# Rarely, if ever, should be used by outside code. It's public
# exposure is merely for those who are interested in it's
# functionality.
#
def quote_regexp_for_mask(hostmask)
# Big thanks to Jesse Williamson for his consultation while writing this.
#
# escape all other regexp specials except for . and *.
# properly escape . and place an unescaped . before *.
# confine the regexp to scan the whole line.
# return the edited hostmask as a string.
hostmask.gsub(/([\[\]\(\)\?\^\$])\\/, '\\1').
gsub(/\./, '\.').
gsub(/\*/, '.*').
sub(/^/, '^').
sub(/$/, '$')
end
module_function :quote_regexp_for_mask
end
|
Markdown | UTF-8 | 1,559 | 2.75 | 3 | [
"Apache-2.0"
] | permissive |
-----------
# APIResource unversioned
Group | Version | Kind
------------ | ---------- | -----------
Core | unversioned | APIResource
APIResource specifies the name of a resource and whether it is namespaced.
<aside class="notice">
Appears In <a href="#apiresourcelist-unversioned">APIResourceList</a> </aside>
Field | Description
------------ | -----------
kind <br /> *string* | kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')
name <br /> *string* | name is the name of the resource.
namespaced <br /> *boolean* | namespaced indicates if a resource is namespaced or not.
### APIResourceList unversioned
Field | Description
------------ | -----------
apiVersion <br /> *string* | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
groupVersion <br /> *string* | groupVersion is the group and version this APIResourceList is for.
kind <br /> *string* | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
resources <br /> *[APIResource](#apiresource-unversioned) array* | resources contains the name of the resources and if they are namespaced.
|
Java | UTF-8 | 5,398 | 1.921875 | 2 | [
"Apache-2.0"
] | permissive | package org.mingy.jmud.ui;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.mingy.jmud.Activator;
import org.mingy.jmud.client.ConnectionEvent;
import org.mingy.jmud.client.ConnectionStates;
import org.mingy.jmud.client.IConnectionStateListener;
import org.mingy.jmud.client.MudClient;
import org.mingy.jmud.model.Configuration;
import org.mingy.jmud.model.Session;
public class SessionEditor extends EditorPart {
public static final String ID = "org.mingy.jmud.ui.SessionEditor"; //$NON-NLS-1$
private static final Log logger = LogFactory.getLog(EditorPart.class);
private StyledText styledText;
private Text text;
private SessionEditorInput input;
public SessionEditor() {
}
/**
* Create contents of the editor part.
*
* @param parent
*/
@Override
public void createPartControl(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new FormLayout());
text = new Text(container, SWT.BORDER);
FormData fd_text = new FormData();
fd_text.left = new FormAttachment(0);
fd_text.right = new FormAttachment(100);
fd_text.bottom = new FormAttachment(100);
text.setLayoutData(fd_text);
styledText = new StyledText(container, SWT.BORDER | SWT.V_SCROLL);
FormData fd_styledText = new FormData();
fd_styledText.left = new FormAttachment(0);
fd_styledText.right = new FormAttachment(100);
fd_styledText.top = new FormAttachment(0);
fd_styledText.bottom = new FormAttachment(text, 0);
styledText.setLayoutData(fd_styledText);
Session session = input.getSession();
if (session.getFont() != null)
styledText.setFont(session.getFont());
final Image onlineImage = Activator.getImageDescriptor(
"/icons/online_16.gif").createImage();
final Image offlineImage = Activator.getImageDescriptor(
"/icons/offline_16.gif").createImage();
final MudClient mc = new MudClient(session, styledText, text);
input.setClient(mc);
input.setContext(mc.getContext());
mc.addConnectionStateListener(new IConnectionStateListener() {
@Override
public void onStateChanged(ConnectionEvent event) {
if (isActive()) {
final boolean offline = event.getNewState() == ConnectionStates.DISCONNECTED;
input.getDisconnectAction().setEnabled(!offline);
getSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
setTitleImage(offline ? offlineImage : onlineImage);
}
});
}
}
});
mc.connect();
IPartService service = (IPartService) getSite().getService(
IPartService.class);
service.addPartListener(new PartAdapter() {
@Override
public void partOpened(IWorkbenchPart part) {
if (part == SessionEditor.this) {
Configuration configuration = input.getSession()
.getConfiguration();
if (configuration != null
&& configuration.getCharacterViewId() != null) {
try {
CharacterView view = (CharacterView) getSite()
.getPage().showView(
configuration.getCharacterViewId(),
null, IWorkbenchPage.VIEW_VISIBLE);
input.setCharacterView(view);
view.init(input);
} catch (PartInitException e) {
if (logger.isErrorEnabled()) {
logger.error("error on open character view", e);
}
}
}
}
}
@Override
public void partClosed(IWorkbenchPart part) {
if (part == SessionEditor.this) {
mc.close();
if (input.getCharacterView() != null) {
getSite().getPage().hideView(input.getCharacterView());
input.setCharacterView(null);
}
} else if (part == input.getCharacterView()) {
input.setCharacterView(null);
}
}
@Override
public void partActivated(IWorkbenchPart part) {
if (part == SessionEditor.this) {
if (input.getCharacterView() != null) {
getSite().getPage()
.bringToTop(input.getCharacterView());
}
}
}
});
}
private boolean isActive() {
IWorkbenchPage page = getSite().getPage();
return page != null && page.getActiveEditor() == this;
}
@Override
public void setFocus() {
text.setFocus();
}
@Override
public void doSave(IProgressMonitor monitor) {
// Do the Save operation
}
@Override
public void doSaveAs() {
// Do the Save As operation
}
@Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
setSite(site);
if (!(input instanceof SessionEditorInput))
throw new PartInitException("unsupported type: " + input.getClass());
this.input = (SessionEditorInput) input;
setInput(input);
setPartName(input.getName());
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
}
|
JavaScript | UTF-8 | 1,497 | 3.25 | 3 | [
"MIT"
] | permissive | function Solve(input) {
var matrixSize = input[0].split(' ');
var startPositionRandC = input[1].split(' ');
var rows = parseInt(matrixSize[0]);
var cols = parseInt(matrixSize[1]);
var currentRow = parseInt(startPositionRandC[0]);
var currentCol = parseInt(startPositionRandC[1]);
var matrix = [];
var counter = 1;
var sumOfNumbers = 0;
var numberOfCells = 0;
for (var i = 0; i < rows; i++) {
matrix[i] = [];
for (var j = 0; j < cols; j++) {
matrix[i][j] = counter;
counter++;
}
}
while (true) {
if (currentCol >= cols || currentRow >= rows || currentCol < 0 || currentRow < 0) {
return 'out ' + sumOfNumbers;
}
if (matrix[currentRow][currentCol] == 'V') {
return 'lost ' + numberOfCells;
}
sumOfNumbers += matrix[currentRow][currentCol];
matrix[currentRow][currentCol] = 'V';
numberOfCells++;
switch (input[currentRow + 2][currentCol]) {
case 'l': currentCol--; break;
case 'r': currentCol++; break;
case 'u': currentRow--; break;
case 'd': currentRow++; break;
}
}
}
args1 = [
"3 4",
"1 3",
"lrrd",
"dlll",
"rddd"];
args2 = [
"5 8",
"0 0",
"rrrrrrrd",
"rludulrd",
"durlddud",
"urrrldud",
"ulllllll"];
args3 = [
"5 8",
"0 0",
"rrrrrrrd",
"rludulrd",
"lurlddud",
"urrrldud",
"ulllllll"];
console.log(Solve(args2));
|
C# | UTF-8 | 2,253 | 2.78125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;
namespace ParcialComputoII.Clases
{
class Account
{
Connection Connection = new Connection();
Crud crud = new Crud();
public int _codUser { get; set; }
public string _firstname { get; set; }
public string _lastname { get; set; }
public string _email { get; set; }
public string _registerdate { get; set; }
public string _username {get; set;}
public string _password {get; set;}
public MySqlDataReader getAll()
{
string query = "SELECT * from accoun WHERE codUser<>1";
return crud.select(query);
}
public Boolean registerAccount()
{
string query = "INSERT INTO accoun(firstname, lastname, email, registerDate, username, password)" +
"VALUE ('" + _firstname + "','" + _lastname + "','" + _email + "','" + _registerdate + "','" + _username + "','" + _password + "')";
crud.executeQuery(query);
return true;
}
public Boolean Login()
{
string query = "SELECT * FROM accoun WHERE username = '"+_username+ "'AND password= '"+_password+"'";
if (crud.select(query).HasRows)
{
return true;
}
return false;
}
public void insertLog()
{
string insertLog = "INSERT INTO userlog(username, timeLoggedin) VALUES('" + _username + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
crud.executeQuery(insertLog);
}
public MySqlDataReader getLog()
{
string query = "SELECT * from userlog";
return crud.select(query);
}
public MySqlDataReader getAllLogs()
{
string query = "SELECT codLog, username, timeLoggedin FROM userlog";
return crud.select(query);
}
public MySqlDataReader getAllUsers()
{
string query = "SELECT * FROM accoun";
return crud.select(query);
}
}
}
|
Java | UTF-8 | 1,134 | 1.929688 | 2 | [] | no_license | package com.example.masodikp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText nev=findViewById(R.id.nev);
EditText szuletesi=findViewById(R.id.szuletesi);
EditText jelszo=findViewById(R.id.jelszo);
Button regisztral=findViewById(R.id.regisztracio);
regisztral.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this, MainActivity2.class);
i.putExtra("nev",nev.getText().toString());
i.putExtra("szuldat",szuletesi.getText().toString());
i.putExtra("jelszo", jelszo.getText().toString());
startActivity(i);
}
});
}
} |
JavaScript | UTF-8 | 3,027 | 2.796875 | 3 | [] | no_license | //Import the required modules.
const Course = require('../models/Course');
var fs = require('fs');
//Load instructor page with the courses.
exports.instructor = async (req, res) => {
const courses = await Course.find().sort({ title: 'asc' });
res.render('instructor', {
title: 'Instructor',
courses,
user: req.user,
});
};
//Create and save a course.
exports.createCourse = (req, res) => {
try{
filePath = '../instructorsTODO/public/uploads/java.txt'
const course = new Course(req.body);
course.file.data = fs.readFileSync(filePath);
course.file.contentType = 'string/txt';
course.save();
res.redirect('/instructor');
} catch (err) {
console.log(err);
}
};
// Return the courses page with the title and the message to the course.ejs view.
exports.getCourses = (req, res) => {
Course.find((err, courses) => {
if (err) {
res.render('error');
} else {
//var imageblob = courses.file;
//var image = document.createElement('image');
// image.src = 'data:image/png;base64,' + imageblob;
// document.appendChild(image);
res.render('instructor', {
title: 'Instructors - Courses',
message: 'Here is the list of all the courses: ',
courses,
user: req.user,
});
}
});
};
//Take the user to add course page only if he's authenticated.
exports.addCourse = (req, res) => {
res.render('addCourse', {
title: 'Add Course',
user: req.user,
});
};
//method to allow user to delete the courses.
exports.deleteCourse = (req, res) => {
Course.remove(
{ _id: req.params.id },
async (err) => {
if (err) {
console.log(err);
} else {
res.redirect('/instructor');
}
},
);
};
//This method allows the user to edit the courses.
exports.editCourse = (req, res) => {
Course.findById({ _id: req.params.id }, (err, course) => {
if (err){
console.log(err)}
else{
res.render('editCourse', {
title: 'Edit',
course,
user: req.user,
});
}
});
};
//This method redirects the user to the appropriate page once they've edited the course.
exports.updateCourse = (req, res) => {
Course.update({_id: req.params.id}, req.body, (err) => {
if (err){
console.log(err);
}
else {
res.redirect('/instructor');
}
});
};
//This method allows the user to upload/add a text file (.txt).
exports.fileUpload = function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv('../public/uploads/filename.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
res.redirect('/instructor');
});
}; |
TypeScript | UTF-8 | 3,780 | 2.53125 | 3 | [] | no_license | const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
export const firestore = admin.firestore();
const sendPushNotification = function(token:string,title:string,body:string,badge:string) {
const payload = {
notification: {
title: title,
body: body,
badge: badge,
sound:"default"
}
};
const option = {
priority: "high"
};
admin.messaging().sendToDevice(token,payload,option);
}
// 新規依頼作時
export const createRequest = functions.firestore.document('/request/{request}')
.onCreate( async (snapshot, context) => {
const request = snapshot.data()
const requestStatus = request['status']
if (requestStatus === "未対応") {
const senderUid = request["adviserId"]
const adviserRef = firestore.collection("adviser").doc(senderUid)
adviserRef.get().then(function(doc){
if (doc.exists === true) {
const adviser = doc.data()
const fcmToken = adviser["fcmToken"]
const studentName = request["studentName"]
const requestType = request["type"]
const title = '新規依頼'
const body = `${studentName}から新規の依頼(${requestType})がきました`
sendPushNotification(fcmToken,title,body,"1");
console.log("newRequest")
} else {
console.log("notExists")
}
})
} else {
console.log("statusNotFound")
}
})
// 依頼更新時
export const updateRequest = functions.firestore.document('/request/{request}')
.onUpdate( async (change, context) => {
const request = change.after.data()
const requestStatus = request['status']
if (requestStatus === "対応中") {
const senderUid = request["studentId"]
const adviserRef = firestore.collection("student").doc(senderUid)
adviserRef.get().then(function(doc){
if (doc.exists === true) {
const student = doc.data()
const fcmToken = student["fcmToken"]
const adviserName = request["adviserName"]
const requestType = request["type"]
const title = '依頼対応中'
const body = `${adviserName}がの依頼(${requestType})の期限を返答しました`
sendPushNotification(fcmToken,title,body,"1");
console.log("updateRequest")
} else {
console.log("notExists")
}
})
} else if (requestStatus === "対応済み") {
const senderUid = request["studentId"]
const adviserRef = firestore.collection("student").doc(senderUid)
adviserRef.get().then(function(doc){
if (doc.exists === true) {
const student = doc.data()
const fcmToken = student["fcmToken"]
const adviserName = request["adviserName"]
const requestType = request["type"]
const title = '依頼完了'
const body = `${adviserName}がの依頼(${requestType})の対応が完了しました`
sendPushNotification(fcmToken,title,body,"1");
console.log("updateRequest")
} else {
console.log("notExists")
}
})
} else {
console.log("statusNotFound")
}
})
|
JavaScript | UTF-8 | 4,827 | 2.53125 | 3 | [] | no_license | /*
* Model.js
*/
'use strict';
const mysql = require('mysql');
const fs = require('fs');
const crypto = require('crypto');
const DBuser = require('./ConnectionInfo')
const connection = mysql.createConnection(DBuser.user);
connection.connect();
// Query sentences definition
// 1. Users
var allUser = 'SELECT * FROM users';
var selectUser = 'SELECT * FROM users WHERE username = ?';
var insertUser = 'INSERT INTO users(username, password, userImageUrl, phone, email) VALUES(?,?,?,?,?)';
var updateUser = 'UPDATE users SET phone = ?, email = ? WHERE username = ?';
var updateUser2 = 'UPDATE users SET phone = ?, email = ?, userImageUrl = ? WHERE username = ?';
// 5. Friends
var insertFriendShip = 'INSERT INTO friends(userOne, userTwo) VALUES(?,?)';
var selectFriends = 'SELECT * FROM friends WHERE userOne = ? AND userTwo = ?';
var myFriends = 'SELECT * FROM friends WHERE userOne = ? OR userTwo = ?';
exports.InsertUser = function(username, pass, userImageUrl, phone, email){
/*
* -3 for username already exists, -2 for rePass not equal to pass,
* -1 for phone already exists, 0 for email alreadt exists,
* 1 for success
*/
var userParam = [username, pass, userImageUrl, phone, email];
connection.query(insertUser, userParam, function(err, result){
if(err) throw err;
});
}
exports.AllUser = async function(){
return new Promise((resolve, reject)=>{
connection.query(allUser, function(err, result){
if(err){
reject(err);
}else {
resolve(result);
}
});
});
}
exports.TestLogIn = async function(username, testPass){
return new Promise((resolve, reject)=>{
connection.query(allUser, function(err, result){
var code = -1; // No such user
if(err){
reject(err);
}else {
result.forEach(function(user) {
if(user.username === username){
if(testPass == GetDecode_SHA256(user.password)){
code = 1; // Success
}else code = 0; // Password error
}
});
resolve(code);
}
});
});
}
exports.GetUserInfo = async function(username){
return new Promise((resolve, reject)=>{
var selectParam = [username];
var res = {};
connection.query(selectUser, selectParam, function(err, result){
if(err){
reject(err);
}
if(result.length > 0){
res['phone'] = result[0].phone;
res['email'] = result[0].email;
res['image'] = result[0].userImageUrl;
}
resolve(res);
});
});
}
exports.StoreUserImg = function(userImage, imageUrl){
var buff = new Buffer(userImage, 'ascii');
var trueImageUrl = 'static/img/' + imageUrl;
fs.writeFileSync(trueImageUrl, userImage);
}
exports.SelectFriendsByName = function(username){
return new Promise((resolve, reject) => {
var res = [];
connection.query(myFriends, [username, username], function(err, result){
if(err){
reject(err);
}
result.forEach(function(item){
if(item.userOne == username)
res.push(item.userTwo);
else
res.push(item.userOne);
});
resolve(res);
});
});
}
exports.AreFriends = async function(user1, user2){
return new Promise((resolve, reject) => {
var res = {
'code': 0
};
connection.query(selectFriends, [user1, user2], function(err, result){
if(err) reject(err);
if(Object.keys(result).length > 0){
res.code = 1;
resolve(res);
}else {
connection.query(selectFriends, [user2, user1], function(err, result){
if(err) reject(err);
if(Object.keys(result).length > 0){
res.code = 1;
}
resolve(res);
});
}
});
});
}
exports.GetEncode_SHA256 = function(str){
var secret = 'HoShiNoGen', key = secret.toString('hex');
var cipher = crypto.createCipher('aes192', key);
var encode_result = cipher.update(str, 'utf-8', 'hex');
encode_result += cipher.final('hex');
return encode_result;
}
var GetDecode_SHA256 = function(str){
var secret = 'HoShiNoGen', key = secret.toString('hex');
var decipher = crypto.createDecipher('aes192', key);
var decode_result = decipher.update(str, 'hex', 'utf-8');
decode_result += decipher.final('utf-8');
return decode_result;
} |
JavaScript | UTF-8 | 995 | 2.75 | 3 | [] | no_license | import game from './_game';
import Cloud from './_Cloud';
class Sky {
constructor() {
this.mesh = new THREE.Object3D();
this.nClouds = 20;
this.clouds = [];
const stepAngle = (Math.PI * 2) / this.nClouds;
for (let i = 0; i < this.nClouds; i++) {
const cloud = new Cloud();
const angle = stepAngle * i;
const height = game.v.seaRadius + 150 + Math.random() * 200;
const size = 1 + Math.random() * 2;
cloud.mesh.position.y = Math.sin(angle) * height;
cloud.mesh.position.x = Math.cos(angle) * height;
cloud.mesh.position.z = -300 - Math.random() * 500;
cloud.mesh.rotation.z = angle + Math.PI / 2;
cloud.mesh.scale.set(size, size, size);
this.mesh.add(cloud.mesh);
this.clouds.push(cloud);
}
}
moveClouds() {
for (let i = 0; i < this.nClouds; i++) {
const c = this.clouds[i];
c.rotate();
}
this.mesh.rotation.z += game.v.speed * game.deltaTime;
}
}
export default Sky;
|
Python | UTF-8 | 2,615 | 2.953125 | 3 | [] | no_license | # Iman Rezaei
# UniqueProbsTotalCfas.py
# 4/22/16
# Create a CSV file with unique step names and their total CFAs
import numpy as np
import pandas as pd
import csv
# **************************************************************************
# import data file
dataFile = pd.read_csv("traindataFilteredByView20.csv", header=0)
problemHierarchy = dataFile["Problem Hierarchy"]
stepName = dataFile["Step Name"]
problemName = dataFile["Problem Name"]
problemView = dataFile["Problem View"]
cfa = dataFile["Correct First Attempt"]
rowNum = dataFile["Row"]
uniqueProblemStepName = []
totalProblemViews = [0]
totalCfas = [0]
# **************************************************************************
# Check to see if there is a CFA
# Then check if the current step name is existed in our uniqueStepNameArray
# if yes add it to the total CFA of the existed step name.
# If the step name is new add it to uniqueStepNameArray
# and its CFA to totalCfas for that unique step name
# Remember in Python array[-1] is the last element!
for i in range(len(stepName)):
print(i)
if cfa[i]:
if problemHierarchy[i] + ";" + problemName[i] + ";" + stepName[i] in uniqueProblemStepName:
uniqueProblemStepNameList = uniqueProblemStepName.tolist()
j = uniqueProblemStepNameList.index(problemHierarchy[i]
+ ";" + problemName[i] + ";" + stepName[i])
totalCfas[j] = totalCfas[j] + cfa[i]
else:
uniqueProblemStepName = np.append(uniqueProblemStepName,
problemHierarchy[i] + ";" + problemName[i]
+ ";" + stepName[i])
totalCfas = np.append(totalCfas, cfa[i])
# print("New unique step name & prob view in row {:d} added".format(i))
# **************************************************************************
with open('UniqueProbsTotalCfas.csv', 'w') as csvfile:
fieldnames = ['Row', 'Problem Hierarchy', 'Problem Name', 'Step Name', 'Total Correct First Attempts']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for x in range(len(uniqueProblemStepName)):
writer.writerow(
{'Row': rowNum[x], 'Problem Hierarchy': uniqueProblemStepName[x].split(";")[0],
'Problem Name': uniqueProblemStepName[x].split(";")[1],
'Step Name': uniqueProblemStepName[x].split(";")[2],
'Total Correct First Attempts': totalCfas[x]})
# ************************************************************************** |
Python | UTF-8 | 301 | 4.0625 | 4 | [] | no_license | #Exercício 4
cat_op = 0.5
cat_adj = 5
tan_theta = (cat_op)/(cat_adj)
print ('A tangente do ângulo zenital vale' , tan_theta , '. Para ângulos pequenos, a tangente pode ser aproximada para o próprio ângulo. Portanto, o ângulo zenital é aproximadamente ' , tan_theta, 'radianos.')
|
Markdown | UTF-8 | 818 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | # DbMan command hierarchy
The command hierarchy is:
- config (manages dbman's configuration)
- show (shows the current configuration)
- delete (deletes a configuration set)
- list (list configuration sets)
- set (set a configuration value in the current configuration)
- use (use a specified configuration)
- release (release information)
- plan (shows the release plan)
- info (shows a specific release information)
- db (database maintenance)
- version (shows the database version)
- deploy (deploy the latest or a specific release)
- upgrade (upgrades to a specific release)
- backup (backups the database)
- restore (restores the database)
- check (check that tools and connections are working for the current config set)
- serve (starts dbman as an http service)
|
C | UTF-8 | 428 | 2.84375 | 3 | [] | no_license | #include "allergies.h"
#ifdef USE_ALLERGIC_TO_FUNCTION
bool is_allergic_to(const allergen_t all, const uint32_t val)
{
return !!(val & (1 << all));
}
#endif
allergen_list_t get_allergens(uint32_t val)
{
allergen_list_t list = { .count = 0 };
allergen_t i;
for (i=0; i<ALLERGEN_COUNT; ++i) {
list.allergens[i] = is_allergic_to(i, val);
list.count += list.allergens[i];
}
return list;
}
|
Java | UTF-8 | 213 | 1.882813 | 2 | [] | no_license | package hw20171227;
public class abc1 {
int age;
String name;
char sex;
public abc1(){
}
public abc1(int asd){
}
public abc1(String dsa){
}
}
|
Ruby | UTF-8 | 709 | 2.6875 | 3 | [] | no_license | class Story < ApplicationRecord
STORY_LENGTH = 5
belongs_to :user
has_many :characters
has_many :story_paragraphs
has_many :paragraphs, through: :story_paragraphs
has_many :plots, through: :paragraphs
has_many :genres, through: :plots
def create_content(genre, characters)
paragraphs = (1..STORY_LENGTH).to_a.map do |num|
Paragraph.where({order: [num]}).order("RANDOM()").first
end #end loop
self.paragraphs << paragraphs
self.content = self.story_content #calling story_content below
end #end createContent
def story_content
full_story = self.paragraphs.map do |p|
p.text
end
full_story.join("-----")
end #end story_content
end #end of class
|
Java | UTF-8 | 13,641 | 3.015625 | 3 | [] | no_license | package hospital;
import shared.Human;
import java.io.Reader;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Hospital {
CarPark carPark;
Stack<Floor> floors;
private String name;
private int countHospitalGuest = 0;
private String encryptionKeyforCases= "vRMbp7kiSXAVA59X";
private String encryptedKey;
ArrayList<Case> allCases = new ArrayList<>();
public Hospital(String name, Stack<Floor> floors, CarPark carPark) {
this.name = name;
this.floors = floors;
this.carPark = carPark;
//later have access to the vehicles
((BSEmergencyDepartment) floors.get(0).getDepartments(0)).setCarPark(carPark);
((EmergencyDepartment) floors.get(0).getDepartments(1)).setCarPark(carPark);
((BSEmergencyDepartment) floors.get(0).getDepartments(0)).setHospital(this);
((EmergencyDepartment) floors.get(0).getDepartments(1)).setHospital(this);
LinkedList<HospitalBed> oneFreeBed = new LinkedList<>();
oneFreeBed.add(getFreeBed());
((BSEmergencyDepartment) getFloor(0).getDepartments(0)).setEmptyHospitalBedList(oneFreeBed);
AESAlgorithm aesAlgorithm = new AESAlgorithm();
encryptedKey = aesAlgorithm.encrypt("HospitalPass1234", encryptionKeyforCases);
}
//general IDs for new patients
public int getNewHospitalPatientID() {
countHospitalGuest++;
return countHospitalGuest;
}
//get the floors, departments etc..
public Floor getFloor(int floorID) {
return floors.get(floorID);
}
//get a RANDOM bed form (1) the first department(floor=1) or (2) the second department(floor=2)
public HospitalBed getFreeBed() {
Random r = new Random();
ArrayList<HospitalBed> availableBeds;
ArrayList<int[]> bedInfo;
//two possible floors for beds
for (int i = 1; i <= 2; i++) {
availableBeds = new ArrayList<>();
bedInfo = new ArrayList<>();
//-->interate over the rooms, departments
for (int j = 0; j < floors.get(i).getDepartments(0).getNumberOfStations(); j++) {
for (int k = 0; k < floors.get(i).getDepartments(0).getStation(j).getNumberOfRooms(); k++) {
for (int l = 0; l < floors.get(i).getDepartments(0).getStation(j).getRoom(k).getNumberOfBeds(); l++) {
if (floors.get(i).getDepartments(0).stations.get(j).rooms.get(k).getHospitalBed(l) != null &&
floors.get(i).getDepartments(0).stations.get(j).rooms.get(k).getHospitalBed(l).isEmpty()) {
/* System.out.println("Hospital: Found free bed in Department " + Floor.getNameDepartmentFloor(i) +
" / Station " + floors.get(i).getDepartments(0).getStation(j).getName()+
" / Room " + k + 1 +
" /Bed " + l+1);*/
HospitalBed freeBed = floors.get(i).getDepartments(0).stations.get(j).rooms.get(k).getHospitalBed(l);
availableBeds.add(freeBed);
bedInfo.add(new int[]{i, j, k, l});
}
}
}
}
//if a collection of free beds >0 --> select random --> print
if (availableBeds.size() != 0) {
int randomNumber = r.nextInt(availableBeds.size());
int[] bedInfoChosenBed = bedInfo.get(randomNumber);
HospitalBed chosenBed = availableBeds.get(randomNumber);
floors.get(i).getDepartments(0).stations.get(bedInfoChosenBed[1]).rooms.get(bedInfoChosenBed[2]).setHospitalBed(bedInfoChosenBed[3], null);
System.out.println("Hospital: Found free bed in Department " + floors.get(i).getDepartments(0).getName() +
" / Station " + floors.get(i).getDepartments(0).getStation(bedInfoChosenBed[1]).getName() +
" / Room " + bedInfoChosenBed[2] + 1 +
" /Bed " + bedInfoChosenBed[3] + 1);
return chosenBed;
}
}
return null;
}
//get a RANDOM bed in the station where the last bed was moved
public HospitalBed getBedByStation(String name, String station) {
//same code as method above
int floorID = 1;
int stationID = Station.getStationNumberFromNameID(station);
if (name.equals(DepartmentsName.Pulmonology)) {
floorID = 2;
}
Random r = new Random();
ArrayList<HospitalBed> availableBeds = new ArrayList<>();
ArrayList<int[]> bedInfo = new ArrayList<>();
for (int k = 0; k < floors.get(floorID).getDepartments(0).getStation(stationID).getNumberOfRooms(); k++) {
for (int l = 0; l < floors.get(floorID).getDepartments(0).getStation(stationID).getRoom(k).getNumberOfBeds(); l++) {
if (floors.get(floorID).getDepartments(0).stations.get(stationID).rooms.get(k).getHospitalBed(l) != null &&
floors.get(floorID).getDepartments(0).stations.get(stationID).rooms.get(k).getHospitalBed(l).isEmpty()) {
/* System.out.println("Hospital: Found free bed in Department " + Floor.getNameDepartmentFloor(stationID) +
" / Station " + floors.get(floorID).getDepartments(0).getStation(stationID).getName()+
" / Room " + k + 1 +
" /Bed " + l+1);*/
HospitalBed freeBed = floors.get(floorID).getDepartments(0).stations.get(stationID).rooms.get(k).getHospitalBed(l);
availableBeds.add(freeBed);
bedInfo.add(new int[]{floorID, stationID, k, l});
}
}
}
//if a collection of free beds >0 --> select random --> print
if (availableBeds.size() != 0) {
int randomNumber = r.nextInt(availableBeds.size());
int[] bedInfoChosenBed = bedInfo.get(randomNumber);
HospitalBed chosenBed = availableBeds.get(randomNumber);
floors.get(floorID).getDepartments(0).stations.get(bedInfoChosenBed[1]).rooms.get(bedInfoChosenBed[2]).setHospitalBed(bedInfoChosenBed[3], null);
System.out.println("Hospital: Found free bed in Department " + floors.get(floorID).getDepartments(0).getName() +
" / Station " + floors.get(floorID).getDepartments(0).getStation(bedInfoChosenBed[1]).getName() +
" / Room " + (bedInfoChosenBed[2] + 1) +
" /Bed " + (bedInfoChosenBed[3] + 1) +
"--> will be moved to BSEmergencyDepartment");
return chosenBed;
}
//nothing free in station --> go somewhere else
//return getFreeBed();
return getFreeBed();
}
//get a RANDOM free space where bed can be placed
public String[] getFreeSpace() {
Random r = new Random();
ArrayList<String[]> freeSpace;
//two possible floors
for (int i = 1; i <= 2; i++) {
freeSpace = new ArrayList<>();
for (int j = 0; j < floors.get(i).getDepartments(0).getNumberOfStations(); j++) {
for (int k = 0; k < floors.get(i).getDepartments(0).getStation(j).getNumberOfRooms(); k++) {
for (int l = 0; l < floors.get(i).getDepartments(0).getStation(j).getRoom(k).getNumberOfBeds(); l++) {
if (floors.get(i).getDepartments(0).stations.get(j).rooms.get(k).getHospitalBed(l) == null) {
/* System.out.println("Hospital: Found free bed in Department " + Floor.getNameDepartmentFloor(i) +
" / Station " + floors.get(i).getDepartments(0).getStation(j).getName()+
" / Room " + k + 1 +
" /Bed " + l+1);*/
freeSpace.add(new String[]{
Integer.toString(i), //Floor
Floor.getNameDepartmentFloor(i).toString(), //departmentName
floors.get(i).getDepartments(0).getStation(j).getName(), //stationName
Integer.toString(k + 1), //RoomID
Integer.toString(l + 1)}); //BedID
}
}
}
}
if (freeSpace.size() != 0) {
int randomNumber = r.nextInt(freeSpace.size());
String[] freeSpaceInfo = freeSpace.get(randomNumber);
System.out.println("Hospital: Found free space where bed will be moved in Department " + freeSpaceInfo[1] +
" / Station " + freeSpaceInfo[2] +
" / Room " + freeSpaceInfo[3] +
" /Bed " + freeSpaceInfo[4]);
return freeSpaceInfo;
}
}
System.out.println("Nothing found");
return null;
}
public void addCaseInDP(Case newCase) {
allCases.add(newCase);
}
//Builder
public static class Builder {
Stack<Floor> floors;
CarPark carPark;
private String name;
public Hospital.Builder setName(String name) {
this.name = name;
return this;
}
public Hospital.Builder setFloors(Stack<Floor> floors) {
this.floors = floors;
return this;
}
public Hospital.Builder setCarPark(CarPark carPark) {
this.carPark = carPark;
return this;
}
public Hospital build() {
return new Hospital(name, floors, carPark);
}
}
//getting Data --> security mechanismus
public Case getMyCase(Human human){
for (Case casePatient: allCases) {
if(casePatient.getFirstName().equals(human.getFirstName()) && casePatient.getLastName().equals(human.getLastName()) && casePatient.getBirthDate().equals(human.getFirstName())){
return casePatient;
};
}
return null;
}
//verify the password
private boolean verify(String masterKeyforCases) {
AESAlgorithm aesAlgorithm = new AESAlgorithm();
if (encryptedKey.equals(aesAlgorithm.encrypt(masterKeyforCases, encryptionKeyforCases))) {
return true;
} else return false;
}
//get case from a specific patient id --> verify with a password
public Case getCaseFromPatient(String password, int id){
if(verify(password)){
for (Case casePatient :allCases) {
if(casePatient.getID() == id){
return casePatient;
}
}
}
System.out.println("Wrong password or id unknown");
return null;
}
//
public void getAnalytics(String password){
if (verify(password)){
System.out.println("Hospital:");
Map<String, Character> mapNametoStation = new HashMap<>();
//1)
getFloor(1).getDepartments(0).getStations().forEach(station -> {
station.getRooms().forEach(room -> {
for(int i=0;i<room.getNumberOfBeds();i++){
if(room.getHospitalBed(i)!=null && room.getHospitalBed(i).getHuman()!=null){
mapNametoStation.put(room.getHospitalBed(i).getHuman().getLastName(),station.getName().charAt(0));
}
}
});
});
System.out.println("List of patients in stations sorted");
mapNametoStation.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.sorted(Map.Entry.comparingByKey())
.forEach(stringStringEntry -> System.out.println("On Station " + stringStringEntry.getValue()+ " is Patient " + stringStringEntry.getKey()));
System.out.println();
//2)
AtomicInteger counterPatients = new AtomicInteger();
getFloor(1).getDepartments(0).getStations().forEach(station -> {
station.getRooms().forEach(room -> {
for(int i=0;i<room.getNumberOfBeds();i++){
if(room.getHospitalBed(i)!=null && room.getHospitalBed(i).getHuman()!=null){
counterPatients.getAndIncrement();
}
}
});
});
System.out.println("Total patients in hospital: " + counterPatients);
System.out.println();
//3)
HashMap<Character, Integer> counterStation = new HashMap<>();
getFloor(1).getDepartments(0).getStations().forEach(station -> {
AtomicInteger counterPatientsStation = new AtomicInteger();
station.getRooms().forEach(room -> {
for(int i=0;i<room.getNumberOfBeds();i++){
if(room.getHospitalBed(i)!=null && room.getHospitalBed(i).getHuman()!=null){
counterPatientsStation.getAndIncrement();
}
}
counterStation.put(station.getName().charAt(0),counterPatientsStation.intValue());
});
});
counterStation.entrySet().stream().forEach(entry -> System.out.println("On Station " + entry.getKey() + " are " + entry.getValue() + " patients."));
System.out.println();
}
else{
System.out.println("Wrong password");
}
}
} |
Ruby | UTF-8 | 622 | 3.6875 | 4 | [] | no_license | def bubble_sort(array)
flag=false
while !flag
flag=true
for i in 0...((array.length) -1)
if array[i]>array[i+1]
array[i],array[i+1]=array[i+1],array[i]
flag=false
end
end
end
return array
end
print bubble_sort([4,3,78,2,0,2])
def bubble_sort_by(array)
flag=false
while !flag
flag=true
for i in 0...((array.length) -1)
if yield(array[i], array[i+1]) >0
array[i],array[i+1]=array[i+1],array[i]
flag=false
end
end
end
return array
end
print bubble_sort_by(["hi","hello","hey"]){
|left, right|
left.length - right.length
}
|
Java | UTF-8 | 2,986 | 1.898438 | 2 | [] | no_license | package hdsec.web.project.secactivity.action;
import hdsec.web.project.activiti.model.ApproveProcess;
import hdsec.web.project.activiti.model.ProcessJob;
import hdsec.web.project.activiti.model.ProcessRecord;
import hdsec.web.project.burn.model.BurnFile;
import hdsec.web.project.common.CCLCMConstants;
import hdsec.web.project.common.bm.BMPropertyUtil;
import hdsec.web.project.secactivity.model.SecOutExchangeEvent;
import hdsec.web.project.secplace.model.EntityVisitor;
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.StringUtils;
/**
* 查看涉外交流作业详情
*
* @author gj
*/
public class ViewSecOutExchangeDetailAction extends SecuActiBaseAction {
private static final long serialVersionUID = 1L;
private String event_code = "";
private SecOutExchangeEvent event = null;
private ApproveProcess process = null;
private ProcessJob job = null;
private List<ProcessRecord> recordList = null;
private List<BurnFile> burnFileList = null;
private List<EntityVisitor> visitorList = null;
public List<EntityVisitor> getVisitorList() {
return visitorList;
}
public void setVisitorList(List<EntityVisitor> visitorList) {
this.visitorList = visitorList;
}
public String getEvent_code() {
return event_code;
}
public void setEvent_code(String event_code) {
this.event_code = event_code;
}
public SecOutExchangeEvent getEvent() {
return event;
}
public List<ProcessRecord> getRecordList() {
return recordList;
}
public ProcessJob getJob() {
return job;
}
public ApproveProcess getProcess() {
return process;
}
public List<BurnFile> getBurnFileList() {
return burnFileList;
}
@Override
public String executeFunction() throws Exception {
event = secactivityservice.getSecOutExchangeByEventCode(event_code);
if (event == null) {
throw new Exception("查询的作业已经被删除");
} else {
String[] filelist = event.getFile_list().split(CCLCMConstants.DEVIDE_SYMBOL);
if (filelist.length > 0 && StringUtils.hasLength(filelist[0])) {
String storePath = BMPropertyUtil.getSecActivityStrorePath();
burnFileList = new ArrayList<BurnFile>();
String file_path = "";
for (int i = 0; i < filelist.length; i++) {
file_path = storePath + "/" + event_code + "/" + filelist[i];
burnFileList.add(new BurnFile(filelist[i], file_path));
}
}
visitorList = secplaceService.getVisitorListByEventCode(event_code);
String job_code = secactivityservice.getOutExchangeJobCodeByEventCode(event_code);
if (StringUtils.hasLength(job_code)) {
job = basicService.getProcessJobByCode(job_code);
process = basicPrcManage.getApproveProcessByInstanceId(job.getInstance_id());
ProcessRecord record = new ProcessRecord();
record.setJob_code(job_code);
recordList = activitiService.getProcessRecordList(record);
}
return SUCCESS;
}
}
}
|
Java | UTF-8 | 922 | 2.71875 | 3 | [] | no_license | import org.junit.Assert;
import org.junit.Test;
public class SolutionTest {
@Test
public void testExample1() {
Solution sol = new Solution();
Assert.assertEquals(2, sol.strStr("hello", "ll"));
}
@Test
public void testExample2() {
Solution sol = new Solution();
Assert.assertEquals(-1, sol.strStr("aaaaa", "bba"));
}
@Test
public void testExample3() {
Solution sol = new Solution();
Assert.assertEquals(-1, sol.strStr("aaa", "aaaa"));
}
@Test
public void testExample4() {
Solution sol = new Solution();
Assert.assertEquals(4, sol.strStr("mississippi", "issip"));
}
@Test
public void testEmpty() {
Solution sol = new Solution();
String haystack = "anyone";
Assert.assertEquals(0, sol.strStr(haystack, ""));
Assert.assertEquals(0, sol.strStr(haystack, null));
}
}
|
Python | UTF-8 | 216 | 4.03125 | 4 | [] | no_license |
my_dict = {'1': 1, '2': 2, '3': 2, '4': 2, '5': 5}
for value in my_dict.values():
print(value)
print("-" * 70)
# use a "set" to de-dupe dictionary values
for value in set(my_dict.values()):
print(value)
|
C# | UTF-8 | 1,703 | 3.4375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SearchAlgorithmsLib;
namespace Server
{
/// <summary>
/// Holds a solution and the number of nodes evaluated in it's search.
/// </summary>
/// <typeparam name="T">Type of state the solution will hold.</typeparam>
public class SolutionWithNodesEvaluated<T>
{
/// <summary>
/// The solution.
/// </summary>
private List<State<T>> solution;
/// <summary>
/// The number of nodes evaluated.
/// </summary>
private int nodesEvaluated;
/// <summary>
/// Initializes a new instance of the <see cref="SolutionWithNodesEvaluated{T}"/> class.
/// </summary>
/// <param name="sol">The solution.</param>
/// <param name="nodes">The number of nodes evaulated.</param>
public SolutionWithNodesEvaluated(Solution<T> sol, int nodes)
{
solution = new List<State<T>>();
State<T> head = sol.Pop();
while (head != null)
{
solution.Add(head);
head = sol.Pop();
}
nodesEvaluated = nodes;
}
/// <summary>
/// Gets the solution.
/// </summary>
/// <value>
/// The solution.
/// </value>
public List<State<T>> Solution { get => solution;}
/// <summary>
/// Gets the number of nodes evaluated.
/// </summary>
/// <value>
/// The number of nodes evaluated.
/// </value>
public int NodesEvaluated { get => nodesEvaluated;}
}
}
|
C | UTF-8 | 1,397 | 3.140625 | 3 | [
"MIT"
] | permissive | typedef Process Data;
typedef struct PriorityQueue
{
int capacity;
int size;
Data* arr;
}PriorityQueue;
typedef PriorityQueue* PQueue;
int isFull(PQueue Q)
{
return Q -> size == Q -> capacity;
}
int isEmpty(PQueue Q)
{
return Q -> size == 0;
}
PQueue createPQueue(const int maxsize)
{
PQueue tmp = (PQueue)malloc(sizeof(PriorityQueue));
tmp -> capacity = maxsize;
tmp -> size = 0;
tmp -> arr = (Data*)malloc(sizeof(Data) * maxsize);
tmp -> arr[0].rem_t = -1;
return tmp;
}
void enqueue(PQueue q,const Data d)
{
if(isFull(q))
{
return;
}
int i = ++q -> size;
for(; q -> arr[i/2].rem_t > d.rem_t; i /= 2)
{
q -> arr[i] = q -> arr[i/2];
}
q -> arr[i] = d;
}
Data dequeue(PQueue q)
{
if(isEmpty(q))
{
return q -> arr[0];
}
int i;
int child;
Data min,last;
min = q -> arr[1];
last = q -> arr[q -> size--];
for(i = 1; i * 2 <= q -> size ; i = child)
{
child = i * 2;
if(child != q -> size && q -> arr[child + 1].rem_t < q -> arr[child].rem_t)
{
child ++;
}
if(last.rem_t >= q -> arr[child].rem_t)
{
q -> arr[i] = q -> arr[child];
}
else
{
break;
}
}
q -> arr[i] = last;
return min;
}
void display(PQueue Q)
{
for(int i = 1 ; i <= Q -> size ; i++)
{
printf("PID : %d rem_t: %4.2f\n",Q -> arr[i].pid,Q -> arr[i].rem_t);
}
}
|
Swift | UTF-8 | 2,544 | 2.671875 | 3 | [
"MIT"
] | permissive | //
// LoginTextField.swift
// ProofOfConcept
//
// Created by Stephen Vickers on 2/8/17.
// Copyright © 2017 Stephen Vickers. All rights reserved.
//
import UIKit
@IBDesignable
class UILoginTextField: UITextField {
@IBInspectable var leftImage : UIImage? {
didSet{
self.updateView()
}
}
@IBInspectable var leftImagePadding : CGFloat = 5.0{
didSet{
self.updateView()
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var shadowColor: UIColor = UIColor.clear {
didSet {
self.updateShadow()
}
}
@IBInspectable var shadowOpacity: Float = 1.0 {
didSet {
self.updateShadow()
}
}
@IBInspectable var shadowRadius: CGFloat = 0.0 {
didSet {
self.updateShadow()
}
}
@IBInspectable var shadowOffset: CGSize = CGSize(width: 0.0, height: 0.0) {
didSet{
self.updateShadow()
}
}
private func updateView(){
if let image = leftImage{
leftViewMode = .always
let imageView = UIImageView(frame: CGRect(x: self.leftImagePadding, y: 0, width: 20, height: 20))
imageView.image = leftImage
var width = self.leftImagePadding + 20
if borderStyle == UITextBorderStyle.none || borderStyle == UITextBorderStyle.line{
width += 5
}
let view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
view.addSubview(imageView)
leftView = view
}
else{
if borderStyle == UITextBorderStyle.none || borderStyle == UITextBorderStyle.line {
leftViewMode = .always
let view = UIView(frame: CGRect(x: 5, y: 0, width: 5, height: 0))
leftView = view
}
}
}
private func updateShadow(){
self.layer.shadowOffset = shadowOffset
self.layer.shadowRadius = shadowRadius
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowColor = shadowColor.cgColor
self.layer.masksToBounds = false
}
}
|
JavaScript | UTF-8 | 493 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* This is not a Array Library,
* (this is just a tribute)
*
* This is just a set of helpers, to make code easier to maintain.
*
* D. Rimron <darran@xalior.com>
*/
if (djsex) {
if (djsex.math) {
djsex.array = {
randomIndex: function(arr) {
return djsex.math.randomint(0, arr.length-1);
}
};
} else {
djsex.log('djsex.array requires djsex.math');
}
} else {
console.log('DJSEX ERROR: could not find djsex.core!');
}
|
Java | UTF-8 | 1,259 | 3.765625 | 4 | [] | no_license | package com.company.multithreading.exp1;
/*
19. public void interrupt()
This method of a thread is used to interrupt the currently executing thread. This method can only be called when
the thread is in sleeping or waiting state.
But if the thread is not in the sleeping or waiting state, then the interrupt() method will not interrupt the
thread but will set the interrupt flag to true.
*/
public class _19_InterruptExp1 extends Thread {
public void run() {
try {
Thread.sleep(1000);
System.out.println("javatpoint");
} catch (InterruptedException e) {
throw new RuntimeException("Thread interrupted..." + e);
}
}
public static void main(String args[]) {
_19_InterruptExp1 thread1 = new _19_InterruptExp1();
thread1.start();
try {
thread1.interrupt();
} catch (Exception e) {
System.out.println("Exception handled " + e);
}
}
/*
Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted...java.lang.InterruptedException: sleep interrupted
at com.company.multithreading.exp1._19_InterruptExp1.run(_19_InterruptExp1.java:19)
*/
}
|
Java | UTF-8 | 2,860 | 2.28125 | 2 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | /*******************************************************************************
* Copyright (c) 2004, 2010 IBM Corporation.
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.a11y.utils.accprobe.accservice.core;
import java.util.Map;
import org.a11y.utils.accprobe.core.model.InvalidComponentException;
/**
* extended interface for exposing more semantically rich properties and relations that might be provided by
* some accessibility APIs. The Java Accessibility API is one such API.
*
*<p>In most cases, implementations of this interface will be primarily native and platform-dependent.
*
* @author Mike Smith
* @see javax.accessibility.AccessibleContext
*/
public interface IAccessibleElement2 extends IAccessibleElement
{
/**
* get the accessible table element for this object
*
* @return table or <code>null</code> if no table is available
* @throws InvalidComponentException
*/
public IAccessibleTableElement getAccessibleTable ()
throws InvalidComponentException;
/**
* get the accessible text element for this object
*
* @return text object or <code>null</code> if no text is available
* @throws InvalidComponentException
*/
public IAccessibleTextElement getAccessibleText ()
throws InvalidComponentException;
/**
* get the accessible image elements for this object
*
* @return array of image objects or empty array if no images are available
* @throws InvalidComponentException
*/
public IAccessibleImageElement[] getAccessibleImage ()
throws InvalidComponentException;
/**
* get the relations for this accessible element. Such objects express this element's
* relation to other accessible elements (e.g. the element is a "member of" or
* "labeled by" some other element). The map
* should have the relation type as key and relation target(s) as value. The value will be an array of
* <code>IAccessibleElement</code> objects.
*
* <p><b>Note</b>: All attempts will be made to use keys
* that match one of the pre-defined relation constants in <code>AccessibleConstants</code>. Should the relation type be
* unknown or not match one of the pre-defined constants, the original
* relationship type from the underlying accessibility model will be returned.
* @return accessible relations held by this element to other accessible elements
* @throws InvalidComponentException
*/
public Map getAccessibleRelations () throws InvalidComponentException;
/**
* get the accessible Editable Text for this object
*
* @return EditbleText object or <code>null</code> if no EditableText is available
* @throws InvalidComponentException
*/
public IAccessibleEditableTextElement getAccessibleEditableText ()
throws InvalidComponentException;
} |
C# | UTF-8 | 976 | 2.5625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace SecurityProj2.Models
{
public class PasswordKey
{
[Key]
public Guid PasswordId { get; set; }
public string UserName { get; set; }
[Display(Name = "Accounts")]
public string HandleName { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
public bool includeUpper { get; set; }
public bool includeNumbers { get; set; }
public bool includeSpecial { get; set; }
[Range(5, 100, ErrorMessage = "Value must be between 5 and 100")]
[Display(Name = "Length")]
public int passwordLength { get; set; }
}
public class PasswordKeyDBContext : DbContext
{
public DbSet<PasswordKey> Keys { get; set; }
}
} |
Markdown | UTF-8 | 14,587 | 3.546875 | 4 | [
"Apache-2.0"
] | permissive | # The SDP Development Process
In SDP, you will use a **GitHub repository** as your navigation panel for the semester: issues, project board, and code.
The repository will allow you to track your progress and to communicate with your team and with the SDP staff.
This document will teach you how to manage your team's GitHub repository according to SDP's variant of the [Scrum development process](https://www.scrumguides.org/).
Scrum is all about minimalism in processes, since it was inspired by the [Agile manifesto](https://agilemanifesto.org/).
Getting familiar with the basics explained here will help you deliver better software faster.
## 0. Reminders
SDP is 4 credits, and each credit corresponds to 25-30h of work during the semester, thus 4 credits divided by 14 weeks is around 8 hours of work per person per week.
See the [EPFL FAQs](https://www.epfl.ch/education/bachelor/study-programs-structure/faqs/) for more information.
In SDP, your team is what Scrum calls the "Development Team", and you share the role of "Product Owner" with your coaches since you both can decide what to include in the app.
While this is not always realistic, it means that this semester you make sure to work on something you care about rather than merely implementing features you are told to.
Scrum also has the concept of "Scrum Master", one person who is in charge of helping the team work smoothly.
In SDP, you will rotate this role among team members.
## 1. Issues
Issues are a way to track work.
Each issue has a name, a description, and other features such as labels.
Anyone can comment on the issue, which is a convenient way to thread discussions.
### Assignment
You can assign an issue to one or more people, indicating that these people are responsible for the issue.
We will use this extensively in SDP, to mark who has to do what work.
### Labels
Labels are a way to annotate issues with predefined categories.
When you create a repository, GitHub automatically creates a bunch of labels for you.
For simplicity, we suggest you use the following labels for issue types:
- "New feature" for issues related to adding new functionality to the application
- "Enhancement" for issues related to improving the user experience of existing features
- "Bug" for issues related to fixing defects in the application
In a real project, some other labels might be necessary, such as "good first issue" to help orient newcomers, or "won't fix" for issues that are valid but out of scope.
However, you won't need these in SDP, since your team will be the only one working on your project.
Another use of labels is to track the time you expect to spend on an issue, as well as the time you actually did spend on it.
This allows you to improve your estimations over time. We suggest you create the following labels:
- "estimated: 1h", "estimated: 2h", "estimated: 3h", "estimated: 5h", "estimated: 8h"
- "actual: 1h", "actual: 2h", "actual: 3h", "actual: 5h", "actual: 8h", "actual: 13h", "actual: 21h"
These numbers follow the Fibonacci sequence, which is convenient for dividing work among people since you can add up issues to ensure everybody has the same amount of work.
When creating an issue, you will assign someone to it, add a label for the issue type, and add a label for the estimated time.
When closing an issue, add a label for the actual time it took.
### Milestones
Another useful feature of issues is milestones: you can group issues together and assign some date at which they should be completed.
However, we will not use milestones in SDP, but instead a more powerful tool: projects.
## 2. Projects
Projects are a visual way to organize issues in groups. You will use one project in SDP to represent all work on your team's application.
GitHub Projects are a list of columns, each of which contains two kinds of items: notes and issues.
To keep it simple, we will only use issues in SDP, so when adding something to the project, always finish by clicking on the three dots and then on "Convert to issue".
Note that GitHub Projects include automation tools, which can automatically trigger actions based on events such as code being merged.
We will not use them in SDP, but we encourage you to check them out.
Create one project called "Scrum Board" and create the following columns:
- "Product Backlog"
- "Sprint backlog"
- "Sprint tasks"
- "Done in Sprint 1"
During the semester, you will create a "Done in sprint N" for every new week.
### Product Backlog
The Product Backlog contains **User Stories**.
User Stories are descriptions of a software feature from the point of view of an user.
In SDP, the format for a User Story is _"As a [role], I want to [action], so that [reason]"_.
For instance, "As a TA, I want to write tutorials, so that I can help my teams".
All three parts are important: the role indicates who the user is and what you can assume about their background, the action is a user-centric view of the feature, and the reason provides context.
If you cannot find a role or reason for a User Story, or if you have to use very generic ones such as "As a user", the feature you're thinking of may not be something users actually care about.
The Product Backlog contains _all_ User Stories that the customers can come up with, ordered by priority.
Since the Product Backlog should be always sorted, having too many User Stories is never a problem, as the team will only implement the highest-priority ones. Some User Stories may permanently stay at the bottom of the Product Backlog, because new high-priority User Stories keep taking their place at the top.
You should add as many User Stories as you can think of, and continue doing so when you have new ideas as the product evolves.
Before the weekly SDP meeting, your team should move User Stories in the Product Backlog to match the priorities your team has.
During the meeting, the coaches may have you move items around if your app does not meet the [app requirements], to ensure you work on them before anything else.
There is another kind of item in the Product Backlog: Bugs. When you encounter a Bug, you should create an issue for it, placing it in the Product Backlog according to the priority you believe it has.
Note that Bugs are not always high-priority, since they may be minor annoyances that are not worth the time to fix compared to implementing a useful feature.
### Sprint Backlog
The Sprint Backlog contains User Stories for the current "Sprint", i.e. one week's worth of work.
At or before the weekly SDP meeting, you and your teammates pick from the top of the Product Backlog as many User Stories as you think you can implement in a Sprint.
Because the Product Backlog is ordered, the team always picks from the top, skipping items only if they have a hard requirement on a higher-priority item that hasn't been completed yet.
Once the Sprint backlog is defined, you cannot remove items from it or add more during the week: it represents a commitment from the team.
### Sprint tasks
The Sprint tasks contains the **Developer Tasks** corresponding to the Sprint backlog's User Stories.
User Stories can correspond to one or more tasks depending on how complex they are.
Each User Story issue should contain in its description a list of the corresponding task issues.
The art of translating User Stories to developer tasks requires time to master, so you will have to practice it as much as possible.
Let's take an example story: "as an administrator, I can log into the system, so that I can use the admin interface".
This User Story tells us nothing about how it will be implemented, or how much time it will take.
As a team, you need to decide how you will implement this story.
You are the experts on how to produce software, so your opinion is what matters here, given that there is no other constraint.
You can choose to use an authentication service (e.g., Google, Facebook, EPFL).
Then you need to show something to the user: a login screen.
And the last part is that you want to keep some settings associated with each user's account in your database.
These steps of achieving the login functionality are not the only way to implement what is necessary for the User Story to be considered done but they are one possible way.
Whatever the steps for delivering the functionality described in a User Story, you need to describe these steps as tasks, estimate how much time each task is going to take, assign a team member to work on each, and do it.
After breaking up a User Story into smaller pieces, you estimate the time necessary to deliver each task.
You then create an issue corresponding to each task, and go on to split up the next User Story if some team members are still available for more work.
Using this workflow, at the end of each Sprint the repository's "master" branch will contain a working application where all tasks have been implemented.
Note that testing is not a separate developer task from implementation: all tasks should include both code and tests.
## 3. Code
Follow the [SDP Bootcamp](https://github.com/sweng-epfl/public/blob/master/bootcamp/SDPBootcamp.md) to set up a basic codebase, including branch protection rules, and to learn about pull requests.
Pull requests are the only way your code will get into the team's master branch, to ensure that nobody can accidentally commit code that does not meet quality standards.
In SDP, we ask that each pull request be reviewed by at least two teammates.
You can speed up this process by assigning teammates as reviewers after you have opened a pull request, using the "Reviewers" list in the pull request page.
To get good feedback on a pull request, make sure the code you push is clean and readable; for instance, do not leave commented out lines of code you used for debugging, and use Android Studio's code formatting tools to make everything consistent.
Otherwise, your teammates will have to give you feedback on low-level issues such as formatting, instead of high-level code design issues.
Remember to write good commit messages.
Always say what was done, not how, and use meaningful messages.
Do not explain too much in the headline.
Respecting these guidelines will make your commits list understandable for the reviewers and will help if you need to go back in the history of modifications.
To review a pull request, go to the "files changed" tab, and look at the code. When you have a question or remark, hover over a line and click on the "+" button that appears, write your thoughts down, then click "Start a review". Write down as many comments as you want, then use the "Finish your review" button at the top. You can refer to people through their GitHub usernames so they get a notification; for instance, "@alice might know how to better integrate this" will send a notification to "alice" so she can give her opinion. You can refer to GitHub issues and pull requests using their number; for instance, "this is related to #123" will link to issue/PR 123 of the repository.
GitHub also lets you create "draft" pull requests, which cannot be merged, as a way to show others what you're doing and get early feedback on important design decisions.
## 4. Summary
Before the weekly meeting:
- The team orders the Product Backlog according to their priorities
- The team moves all completed issues to the "Done in Sprint N" column, where N is the current Sprint, including User Stories whose tasks have all been completed
- The team creates a new "Done in Sprint N+1" column to be used for the next Sprint
During the weekly meeting:
- The team demoes the app as it is in their repository's "master" branch to the coaches, in 3 minutes or less
- The demo should treat the coaches as customers: they have no software development knowledge, and they do not know what the app can do
- The demo should be from scratch, i.e., explain the app from zero, not explain what the team added since the previous week
- The demo does not need to show all of the app's features, only the key ones; for instance, creating a forum post is a nice feature to show, but editing it is probably a waste of demo time
- The team discusses any developer tasks that were not completed in time, to understand why and to improve their estimation skills
- The coaches reorder the Product Backlog if necessary to meet the app requirements
- While not all team members have a full 8 hours of work for the week:
- The team picks the topmost User Story from the Product Backlog
- The team moves that story to the Sprint backlog
- The team decides on how to split it into developer tasks
- For each such developer task:
- The team estimates how long the task will take
- The team assigns the task to someone who can take on that amount of work
- If no team member has enough time to implement the task, it can exceptionally stay at the top of the Sprint backlog, to be carried over for the next Sprint
During the week:
- Each team member works on their assigned task
- When a task is completed, the member opens a pull requests and assigns at least two reviewers, who should provide a thorough review of the code
- When the reviewers are satisfied, and continuous integration accepts the code, any team member can merge the pull request and delete the corresponding branch
- The team adds any bug they find to the Product Backlog
- The team adds as many new User Stories to the Product Backlog as they want
- At least twice a week, the team meets for a "standup meeting" in which they shortly describe what they are working on and whether anything is blocking their work
- This meeting should last 10 minutes at most, ideally less
- Any blockers identified this way should be discussed between a few of the team members later, so that one member does not waste time figuring out something that one of their teammates knows how to solve
- The team prepares a demo to show the coaches for the next meeting
The Scrum master is in charge of making sure the team works smoothly and prepares a good demo.
The coaches are there to help the team both during the weekly meeting and outside of it if needed.
After a few weeks, once the app gets into shape, the team may do more and more of the "weekly meeting" work itself, before the meeting happens.
Then the meeting becomes more of a formality: demo the app, explain what you did, present the tasks you'd like to do next, and get the coaches' approval.
The goal is to make you autonomous developers who deliver working high-quality software and are able to work in a team.
|
C++ | UTF-8 | 402 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
char a[50];
cin >> a;
int i=0;
if(a[i] == 9){
i++;
}
//iterate over remaining numbers
for ( ; a[i]!='\0';i++){
int digit = a[i] - '0'; // to convert ascii to integer
if(digit >= 5){
digit = 9-digit ;
a[i] = digit + '0';
}
}
cout<<a<<endl;
return 0;
}
|
C++ | UTF-8 | 650 | 2.734375 | 3 | [] | no_license | /*
* CS585
*
* Team Bammm
* Alvaro Home
* Matt Konstantinou
* Michael Abramo
* Matt Witkowski
* Bradley Crusco
* Description:
* IWeaponType header file.
*
*/
#ifndef IWEAPONTYPE_H_
#define IWEAPONTYPE_H_
#include "../Weapons/WeaponData.h"
namespace bammm
{
class Actor;
class IWeaponType
{
protected:
WeaponData* _weaponData;
public:
IWeaponType();
virtual ~IWeaponType();
/**
attack
@Pre-Condition- No input
@Post-Condition- Attack is executed
*/
virtual int attack()=0;
/**
canAttack
@Pre-Condition- No input
@Post-Condition- Returns true if weapon can attack
*/
virtual bool canAttack()=0;
};
}
#endif
|
Python | UTF-8 | 358 | 3.578125 | 4 | [] | no_license | def outer(func):
cached = {}
def inner(x):
if x in cached:
return cached[x]
result = func(x)
cached[x] = result
return result
return inner
@outer
def calculate_something(x):
print("calculate_something(" + str(x) +")")
return x * x
print(calculate_something(5))
print(calculate_something(5)) |
Markdown | UTF-8 | 1,077 | 4.03125 | 4 | [] | no_license | ### JavaScript uses prototype inheritance
In JavaScript, a sub-class inherite it's parent properties and methods through "prototype".
Every JS instance has a "\_\_proto\_\_" which pointing to it's parent prototype. For example, every
array instance pointing to Array.prototype.
const arr = [1, 2, 3]
> arr
(3) [1, 2, 3]
0: 1
1: 2
2: 3
length: 3
__proto__: Array(0)
You see arr.\_\_proto\_\_ pointing to Array[0] (prototype)
If you run below function:
arr.map( e => e * 2) // will return [2, 4, 6]
It's actually doing this behind the scene
Array.prototype.map.call( [1,2,3], e => e * 2 )
arr get the "map" method from Array's prototype. "arr" itself doesn't have "map" method.
But arr is an instance of Array, it traverse up to Array using \_\_proto\_\_ to get the "map" method.
### Prototype chain
> var arr = ['a', 'b'];
> var p = Object.getPrototypeOf;
> p(arr) === Array.prototype
true
> p(p(arr)) === Object.prototype
true
> p(p(p(arr)))
null
|
Python | UTF-8 | 1,700 | 3.765625 | 4 | [] | no_license | #the below code is for multiple groupings or mixed pairs
def test_groupings(li, _map={'(': ')', '[': ']', '{': '}'}):
stack = []
for el in li:
if el in _map:
# opening element, add to stack to look for matching close
stack.append(el)
elif not stack or _map[stack[-1]] != el:
# not an opening element; is the stack is empty?
# or is this element not paired with the stack top?
return False
elif el == _map[stack[-1]]:
stack.pop()
else:
# closing element matched, remove opening element from stack
stack.pop()
# if the stack is now empty, everything was matched
return not stack
print test_groupings(['{', '[', '(', ')', ']', '}'])
#True
print test_groupings(['[', '(', ')', ']'])
#True
print test_groupings(['{', '[', '(', ']', ')', '}'])
#False
print test_groupings(['(', '{', '}', '[', ']', ')'])
#True
print "================================================================="
#the below solution is only for single dimension of nesting and not mixed pairs like above example inputs
def test_pairs(li, _map={'(': ')', '[': ']', '{': '}'}):
l = len(li)
if l % 2 == 1:
# odd length list, can't be paired
return False
print li[:l//2]
# pair up the first half with the second half, reversed
for first, second in zip(li[:l // 2], reversed(li)):
if _map.get(first) != second:
# Either first is not a left bracket, or right bracket is not a match
return False
# everything tested, so everything matched
return True
print test_pairs(['{', '[', '(', ')', ']', '}'])
#True
print test_pairs(['[', '(', ')', ']'])
#True
print test_pairs(['{', '[', '(', ']', ')', '}'])
#False
print "================================================================="
|
Shell | UTF-8 | 1,416 | 3.46875 | 3 | [
"MIT"
] | permissive | #!/bin/bash
parallelism=4
while getopts j: flag
do
case "${flag}" in
j) parArg=${OPTARG};;
esac
done
if [ "$parArg" -eq "$parArg" ] 2>/dev/null
then
parallelism=$parArg
fi
echo -e "\033[1m* Building math libraries \033[0m"
make -s clean
make -s
echo -e "\033[1m\tBuilding done \033[0m"
echo -e "\033[1m* Performing math library correctness test \033[0m"
echo -e "\033[1m\tParallelism: $parallelism jobs\033[0m"
echo -e "\033[1m\t* PWLibm and GLibc math library correctness test \033[0m"
cd libtest/float/glibc
make --silent clean
make --silent
cat Commands.txt | parallel -j $parallelism
make clean
cd ../intel
make --silent clean
make --silent
cat Commands.txt | parallel -j $parallelism
make --silent clean
echo -e "\033[1m\tMath library correctness test complete \033[0m"
echo -e "\033[1m\tResult: \033[0m"
cd ..
cat glibc/Log_FGResult.txt
cat intel/Log_FIResult.txt
cat glibc/Log2_FGResult.txt
cat intel/Log2_FIResult.txt
cat glibc/Log10_FGResult.txt
cat intel/Log10_FIResult.txt
cat glibc/Exp_FGResult.txt
cat intel/Exp_FIResult.txt
cat glibc/Exp2_FGResult.txt
cat intel/Exp2_FIResult.txt
cat glibc/Exp10_FGResult.txt
cat intel/Exp10_FIResult.txt
cat glibc/Sinh_FGResult.txt
cat intel/Sinh_FIResult.txt
cat glibc/Cosh_FGResult.txt
cat intel/Cosh_FIResult.txt
cat glibc/Sinpi_FGResult.txt
cat intel/Sinpi_FIResult.txt
cat glibc/Cospi_FGResult.txt
cat intel/Cospi_FIResult.txt
cd ../..
|
Java | UTF-8 | 38,241 | 2.015625 | 2 | [
"MIT"
] | permissive | /****************************************************************************
* Copyright (c) 2012-2015 Zachary L. Stauber
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
package spacewar;
import javax.swing.*;
import spacewar.StaticSprite.Level;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class GamePanel extends JApplet implements Runnable, KeyListener, MouseListener
{
private static final long serialVersionUID = 1L;
private static final int PWIDTH = 800;
private static final int PHEIGHT = 600;
private static final int MAX_FRAME_SKIPS = 5;
private static final int MAX_FRAME_RATE = 60;
private static final int SHIP_TOP_SPEED = 6;
private static final int SHIP_TOP_ENERGY = 50;
private static final int SLUG_SPEED = 6;
private static final int TORPEDO_SPEED = 6;
private static final int CLOAK_SECONDS = 4;
private static final int TORPEDO_DAMAGE = 10;
private static final int SLUG_DAMAGE = 5;
private static final int PLANET_DAMAGE = 5;
private static final int SHIP_DAMAGE = 2;
private Thread animator; // for the animation
private ArrayList<SpriteAnimation> spriteAnimations = new ArrayList<SpriteAnimation>();
private double avgups, avgfps;
public static enum GameState
{
PRE, RUNNING, PAUSED, OVER;
}
private GameState gameState = GameState.PRE;
// global variables for off-screen rendering
private Graphics2D dbg;
private Image dbImage = null;
int mouseX = 0, mouseY = 0;
int player1Wins = 0, player2Wins = 0;
final double G = 2.5; // 6.674e-11 // gravitational constant
final double M = 2.5; // 5.9722e24 // Earth mass
final double R = 0.0; // 6.3671e6 // Earth radius
ImagesLoader il = new ImagesLoader();
//BufferedImage imgShip1 = il.loadImage("Ship1.png");
//BufferedImage imgShip2 = il.loadImage("Ship2.png");
BufferedImage imgShip1 = il.loadImage("Ship1.png");
BufferedImage imgShip2 = il.loadImage("Ship2.png");
BufferedImage imgSlug = il.loadImage("Slug.png");
BufferedImage imgTorpedo = il.loadImage("Torpedo.png");
BufferedImage imgPlanet = il.loadImage("Planet.png");
BufferedImage imgStarfield = il.loadImage("Starfield.png");
BufferedImage[] imgsExplosion = il.loadStripImageArray("Explosion.png", 10);
BufferedImage[] imgsShield = il.loadStripImageArray("Shield.png", 1);
AudioClip ship_explosion = new AudioClip("ship_explosion.wav");
AudioClip ship_warp = new AudioClip("ship_warp.wav");
AudioClip slug_launch = new AudioClip("slug_launch.wav");
AudioClip torpedo_explosion = new AudioClip("torpedo_explosion.wav");
AudioClip torpedo_launch = new AudioClip("torpedo_launch.wav");
StaticSprite planet = new StaticSprite(imgPlanet);
IntelligentSprite player1 = new IntelligentSprite(imgShip1);
IntelligentSprite player2 = new IntelligentSprite(imgShip2);
ArrayList<StaticSprite> planets = new ArrayList<StaticSprite>();
//List<DynamicSprite> slugs = Collections.synchronizedList(new ArrayList<DynamicSprite>());
ArrayList<DynamicSprite> slugs = new ArrayList<DynamicSprite>();
ArrayList<DynamicSprite> torpedoes = new ArrayList<DynamicSprite>();
ArrayList<IntelligentSprite> ships = new ArrayList<IntelligentSprite>();
public GamePanel()
{
//String userDir = System.getProperty("user.dir");
//JOptionPane.showMessageDialog(null, userDir);
setBackground(Color.BLACK);
setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
setFocusable(true);
requestFocus(); // JPanel now receives key events
readyForTermination();
initializeGame();
} // end of GamePanel() constructor
public void addNotify()
{
/* Wait for the JPanel to be added to the FRame/JApplet before starting. */
super.addNotify(); // creates the peer
startGame(); // start the thread
} // and of addNotify()
private void readyForTermination()
{
addKeyListener(this);
addMouseListener(this);
} // end of readyForTermination()
public void keyPressed(KeyEvent ke)
{
switch (ke.getKeyCode())
{
case KeyEvent.VK_Q:
if (gameState == GameState.RUNNING) shootSlug(player1);
break;
case KeyEvent.VK_W:
if (gameState == GameState.RUNNING) cloak(player1);
break;
case KeyEvent.VK_E:
if (gameState == GameState.RUNNING) shootTorpedo(player1);
break;
case KeyEvent.VK_A:
if (gameState == GameState.RUNNING) player1.rotate(-1); // rotate left
break;
case KeyEvent.VK_S:
if (gameState == GameState.RUNNING) player1.accelerate(1); // rotate right
break;
case KeyEvent.VK_D:
if (gameState == GameState.RUNNING) player1.rotate(1); // rotate right
break;
case KeyEvent.VK_Z:
if (gameState == GameState.RUNNING) player1.transferStoW(); // weapon energy
break;
case KeyEvent.VK_X:
if (gameState == GameState.RUNNING) hyperspace(player1);
break;
case KeyEvent.VK_C:
if (gameState == GameState.RUNNING) player1.transferWtoS(); // shield energy
break;
case KeyEvent.VK_NUMPAD7:
if (gameState == GameState.RUNNING) shootSlug(player2);
break;
case KeyEvent.VK_NUMPAD8:
if (gameState == GameState.RUNNING) cloak(player2);
break;
case KeyEvent.VK_NUMPAD9:
if (gameState == GameState.RUNNING) shootTorpedo(player2);
break;
case KeyEvent.VK_NUMPAD4:
if (gameState == GameState.RUNNING) player2.rotate(-1); // rotate left
break;
case KeyEvent.VK_NUMPAD5:
if (gameState == GameState.RUNNING) player2.accelerate(1); // rotate right
break;
case KeyEvent.VK_NUMPAD6:
if (gameState == GameState.RUNNING) player2.rotate(1); // rotate right
break;
case KeyEvent.VK_NUMPAD1:
if (gameState == GameState.RUNNING) player2.transferStoW(); // weapon energy
break;
case KeyEvent.VK_NUMPAD2:
if (gameState == GameState.RUNNING) hyperspace(player2);
break;
case KeyEvent.VK_NUMPAD3:
if (gameState == GameState.RUNNING) player2.transferWtoS(); // shield energy
break;
case KeyEvent.VK_P:
if (gameState == GameState.RUNNING)
stopGame();
else
resumeGame();
break;
case KeyEvent.VK_ESCAPE:
this.endGame();
}
}
public void keyReleased(KeyEvent ke) {}
public void keyTyped(KeyEvent ke) {}
public void mouseClicked(MouseEvent e)
{
mouseX = e.getX();
mouseY = e.getY();
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, mouseX, mouseY));
torpedo_explosion.play();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void run()
{
/*
* Repeatedly update, render, sleep
* We intend to separate updates from renders to have an adaptive frame
* rate. Since our timer is System.nanoTime(), we will divide all values
* by 1e6d (a million) to convert ns -> ms.
* If we are achieving rendering and update speeds of less than 10 ms
* (100 FPS) we sleep. If we are achieving rendering and update speeds
* of greater than 33 ms (30 FPS), we start skipping frames, up to 5.
* In any case we want 100 UPS.
*/
int updates, extraUpdates;
long totalUpdates = 0L, totalFrames = 0L;
double beginTime, startTime, updateTime, totalTime, frameTime, excessTime, periodTime;
beginTime = System.nanoTime() / 1e6d;
periodTime = 1e3d / MAX_FRAME_RATE; // desired time for an update/render in ms
while (gameState != GameState.OVER)
{
updates = 0;
extraUpdates = 0;
startTime = System.nanoTime() / 1e6d;
gameUpdate(); // if running, game state is updated
updates++;
totalUpdates++;
updateTime = System.nanoTime() / 1e6d - startTime;
gameRender(); // render to a buffer
repaint(); // paint with the buffer
//try { Thread.sleep(50); } catch (InterruptedException ex) {};
totalFrames++;
totalTime = System.nanoTime() / 1e6d - startTime;
frameTime = totalTime - updateTime;
excessTime = periodTime - totalTime;
if (excessTime > 0)
/* We computed an ideal frame rate (period) and see if we're meeting that
* speed. If we have time left over, we just sleep it off and cycle the
* animation.
*/
try
{
Thread.sleep(Math.round(excessTime)); // sleep a bit
}
catch (InterruptedException ex) {}
else if (excessTime < 0)
{
/* If we went over the period with the frame rendering, we still need
* to update every period, but we can drop frames. So we compute how
* many periods we can reliably do a frame once while still doing an
* update every period.
*/
extraUpdates = (int)Math.ceil(frameTime / (periodTime - updateTime));
while (updates <= extraUpdates && updates <= MAX_FRAME_SKIPS)
{
/* Do these extra updates, unless we run up against the user defined
* MAX_FRAME_SKIPS.
*/
gameUpdate();
updates++;
totalUpdates++;
}
totalTime = System.nanoTime() / 1e6d - startTime;
excessTime = extraUpdates * periodTime - totalTime;
if (excessTime >= 0)
/* Even though we did a number of updates without frames we still want
* to wait for the end of a full period before cycling the animation.
*/
try
{
Thread.sleep(Math.round(excessTime));
}
catch (InterruptedException ex) {}
}
/* Compute some totals for statistics. */
avgups = totalUpdates / (System.nanoTime() / 1e6d - beginTime) * 1000d;
avgfps = totalFrames / (System.nanoTime() / 1e6d - beginTime) * 1000d;
}
System.exit(0); // so enclosing JFrame/JApplet exits
} // end of run()
private void initializeGame()
{
gameState = GameState.PRE;
planets.clear();
ships.clear();
slugs.clear();
torpedoes.clear();
// add starting sprites
planet.setX(PWIDTH/2);
planet.setY(PHEIGHT/2);
planet.setWidth(100);
planet.setHeight(100);
planet.setBufImg(imgPlanet);
planet.setVisible(true);
planet.setExistsOnLevel(Level.PLANET);
planet.setCollidesWithLevels(new Level[] {Level.PLAYER1,Level.PLAYER2,Level.SLUG,Level.TORPEDO});
planets.add(planet);
player1.setX(400);
player1.setY(150);
player1.setWidth(20);
player1.setHeight(20);
player1.setVisible(true);
player1.setExistsOnLevel(Level.PLAYER1);
player1.setCollidesWithLevels(new Level[] {Level.PLANET,Level.PLAYER2,Level.SLUG,Level.TORPEDO});
player1.setHVelocity(3);
player1.setVVelocity(0);
player1.setRotation(0);
player1.rotate(0); // necessary on game reset if ship is not rotated to 0
player1.setTopSpeed(SHIP_TOP_SPEED);
player1.setTopEnergy(SHIP_TOP_ENERGY);
player1.setWeaponEnergy(SHIP_TOP_ENERGY);
player1.setShieldEnergy(SHIP_TOP_ENERGY);
player1.setAlive(true);
ships.add(player1);
player2.setX(400);
player2.setY(450);
player2.setWidth(20);
player2.setHeight(20);
player2.setVisible(true);
player2.setExistsOnLevel(Level.PLAYER2);
player2.setCollidesWithLevels(new Level[] {Level.PLANET,Level.PLAYER1,Level.SLUG,Level.TORPEDO});
player2.setHVelocity(-3);
player2.setVVelocity(0);
player2.setRotation(0);
player2.rotate(8);
player2.setTopSpeed(SHIP_TOP_SPEED);
player2.setTopEnergy(SHIP_TOP_ENERGY);
player2.setWeaponEnergy(SHIP_TOP_ENERGY);
player2.setShieldEnergy(SHIP_TOP_ENERGY);
player2.setAlive(true);
ships.add(player2);
}
private void startGame()
{
// initialize and start the thread
{
if (animator == null || gameState == GameState.RUNNING)
{
animator = new Thread(this);
animator.start();
}
}
}
public void stopGame()
{
// called by the user to pause execution
gameState = GameState.PAUSED;
}
public void resumeGame()
{
// called by the user to resume execution
gameState = GameState.RUNNING;
}
public void endGame()
{
// called by the user to stop execution
gameState = GameState.OVER;
}
private void gameUpdate()
{
long currentTime = (long) (System.nanoTime() / 1e9);
if (gameState == GameState.RUNNING) // update game state
{
for (int i = slugs.size() - 1; i >= 0; i--)
{
// much thanks for the formulas: http://physics.stackexchange.com/questions/17285/split-gravitational-force-into-x-y-and-z-componenets
// alter velocity based on gravity well
double x = 0.0, y = 0.0;
DynamicSprite d = slugs.get(i);
x = PWIDTH/2.0 - d.getX();
y = PHEIGHT/2.0 - d.getY();
// move ship based on velocity
d.setX(d.getX() + d.getHVelocity());
d.setY(d.getY() + d.getVVelocity());
// wrap around screen if necessary
if (d.getX() <= 0 )
d.setX(PWIDTH);
else if (d.getX() >= PWIDTH)
d.setX(0);
if (d.getY() < 0 )
d.setY(PHEIGHT);
else if (d.getY() >= PHEIGHT)
d.setY(0);
collide(d, planet);
collide(ships.get(0), d);
collide(ships.get(1), d);
for (int j = torpedoes.size() - 1; j >= 0; j--)
{
DynamicSprite d2 = torpedoes.get(j);
collide(d2, d);
}
if (d.getAlive() == false)
slugs.remove(i);
}
for (int i = torpedoes.size() - 1; i >= 0; i--)
{
DynamicSprite d = torpedoes.get(i);
// much thanks for the formulas: http://physics.stackexchange.com/questions/17285/split-gravitational-force-into-x-y-and-z-componenets
// alter velocity based on gravity well
double x = 0.0, y = 0.0, rsq = 0.0, a = 0.0, ax = 0.0, ay = 0.0;
x = PWIDTH/2.0 - d.getX();
y = PHEIGHT/2.0 - d.getY();
rsq = Math.pow(x,2.0) + Math.pow(y,2.0);
// compute each component of acceleration
ax = (G * M) * x / rsq;
ay = (G * M) * y / rsq;
// don't need to worry about top speed here since DynamicSprites can neither increase nor decrease speed
float newHVelocity = d.getHVelocity() + (float)ax;
float newVVelocity = d.getVVelocity() + (float)ay;
float newVelocity = (float)Math.pow(Math.pow(newHVelocity, 2.0) + Math.pow(newVVelocity, 2.0), 0.5);
d.setHVelocity(newHVelocity);
d.setVVelocity(newVVelocity);
// move torpedo based on velocity
d.setX(d.getX() + d.getHVelocity());
d.setY(d.getY() + d.getVVelocity());
// wrap around screen if necessary
if (d.getX() <= 0 )
d.setX(PWIDTH);
else if (d.getX() >= PWIDTH)
d.setX(0);
if (d.getY() < 0 )
d.setY(PHEIGHT);
else if (d.getY() >= PHEIGHT)
d.setY(0);
collide(d, planet);
collide(ships.get(0), d);
collide(ships.get(1), d);
/* The next loop adds not only torpedoes that just collided, but the ones the
* slugs collided with in the above slugs loop.
*/
if (d.getAlive() == false)
torpedoes.remove(d);
}
for (int j = ships.size() - 1; j >= 0; j--)
{
IntelligentSprite i = ships.get(j);
// much thanks for the formulas: http://physics.stackexchange.com/questions/17285/split-gravitational-force-into-x-y-and-z-componenets
// alter velocity based on gravity well
double x = 0.0, y = 0.0, rsq = 0.0, a = 0.0, ax = 0.0, ay = 0.0;
x = PWIDTH/2.0 - i.getX();
y = PHEIGHT/2.0 - i.getY();
rsq = Math.pow(x,2.0) + Math.pow(y,2.0);
// compute each component of acceleration
ax = (G * M) * x / rsq;
ay = (G * M) * y / rsq;
// tricky here, unlike thruster acceleration, we still need the ships to be affected even if they are already at their speed limit
// so we need to find the magnitude in each direction and scale them back if they're above the top speed
float newHVelocity = i.getHVelocity() + (float)ax;
float newVVelocity = i.getVVelocity() + (float)ay;
float newVelocity = (float)Math.pow(Math.pow(newHVelocity, 2.0) + Math.pow(newVVelocity, 2.0), 0.5);
if (newVelocity <= i.getTopSpeed())
{
i.setHVelocity(newHVelocity);
i.setVVelocity(newVVelocity);
}
else
{
float scaleFactor = i.getTopSpeed() / newVelocity;
i.setHVelocity(newHVelocity * scaleFactor);
i.setVVelocity(newVVelocity * scaleFactor);
}
// move ship based on velocity
i.setX(i.getX() + i.getHVelocity());
i.setY(i.getY() + i.getVVelocity());
// wrap around screen if necessary
if (i.getX() <= 0 )
i.setX(PWIDTH);
else if (i.getX() >= PWIDTH)
i.setX(0);
if (i.getY() < 0 )
i.setY(PHEIGHT);
else if (i.getY() >= PHEIGHT)
i.setY(0);
// Move shields along with sprites as soon as possible
for (int i2 = spriteAnimations.size() - 1; i2 >= 0; i2--)
{
SpriteAnimation s = spriteAnimations.get(i2);
if (s.getSprite() == i)
{
s.setX(s.getSprite().getX());
s.setY(s.getSprite().getY());
}
}
// now we regenerate energy at the rate of 1 point per second
if (currentTime > i.getLastRegenTime())
{
i.regen();
i.setLastRegenTime(currentTime);
}
// if either player is cloaked, we check to see if time is up and set to visible
if (i.getVisible() == false)
{
if (currentTime > i.getLastCloakTime() + CLOAK_SECONDS)
i.setVisible(true);
}
}
collide(ships.get(0), ships.get(1));
collide(ships.get(0), planet);
collide(ships.get(1), planet);
/* Iterate over SpriteAnimations updating each one. If attached
* to a StaticSprite, update it's X,Y.
*/
for (int j = ships.size() - 1; j >= 0; j--)
{
IntelligentSprite i = ships.get(j);
if (i.getAlive() == false && spriteAnimations.size() == 0)
{
if (i == player1)
player2Wins++;
else if (i == player2)
player1Wins++;
initializeGame();
break;
}
}
}
}
private void gameRender()
{
// draw the current frame to an image buffer
if (dbImage == null) // create the buffer
{
dbImage = createImage(PWIDTH, PHEIGHT);
if (dbImage == null)
{
System.out.println("dbImage is null");
return;
}
else
dbg = (Graphics2D)dbImage.getGraphics();
}
// clear the background
//dbg.setColor(Color.BLACK);
//dbg.fillRect(0, 0, PWIDTH, PHEIGHT);
dbg.drawImage(imgStarfield, 0, 0, null);
// draw game elements
for (int i = planets.size() - 1; i >= 0; i--)
{
StaticSprite s = planets.get(i);
s.draw(dbg, this);
}
for (int i = slugs.size() - 1; i >= 0; i--)
{
DynamicSprite d = slugs.get(i);
d.draw(dbg, this);
}
for (int i = torpedoes.size() - 1; i >= 0; i--)
{
DynamicSprite d = torpedoes.get(i);
d.draw(dbg, this);
}
for (int j = ships.size() - 1; j >= 0; j--)
{
IntelligentSprite i = ships.get(j);
i.draw(dbg, this);
}
if (gameState == GameState.PRE)
{ // title screen and player wins
Font oldFont = dbg.getFont();
dbg.setFont(new Font("SansSerif", Font.BOLD, 48));
dbg.setColor(Color.WHITE);
dbg.drawString("SPACEWAR", 260, 100);
dbg.setFont(oldFont);
dbg.setColor(Color.RED);
dbg.drawString("Wins: " + player1Wins, 150, 160);
dbg.drawString("Q", 75, 200);
dbg.drawString("Fire", 75, 220);
dbg.drawString("Slug", 75, 240);
dbg.drawString("A", 75, 270);
dbg.drawString("Rotate", 75, 290);
dbg.drawString("CCW", 75, 310);
dbg.drawString("Z", 75, 340);
dbg.drawString("Weapon", 75, 360);
dbg.drawString("Energy", 75, 380);
dbg.drawString("W", 150, 200);
dbg.drawString("", 150, 220);
dbg.drawString("Cloak", 150, 240);
dbg.drawString("S", 150, 270);
dbg.drawString("Engine", 150, 290);
dbg.drawString("Thrust", 150, 310);
dbg.drawString("X", 150, 340);
dbg.drawString("Hyper", 150, 360);
dbg.drawString("Space", 150, 380);
dbg.drawString("E", 225, 200);
dbg.drawString("Fire", 225, 220);
dbg.drawString("Torpedo", 225, 240);
dbg.drawString("D", 225, 270);
dbg.drawString("Rotate", 225, 290);
dbg.drawString("CW", 225, 310);
dbg.drawString("C", 225, 340);
dbg.drawString("Shield", 225, 360);
dbg.drawString("Energy", 225, 380);
dbg.drawLine(50, 175, 275, 175);
dbg.drawLine(50, 250, 275, 250);
dbg.drawLine(50, 325, 275, 325);
dbg.drawLine(50, 400, 275, 400);
dbg.drawLine(50, 175, 50, 400);
dbg.drawLine(125, 175, 125, 400);
dbg.drawLine(200, 175, 200, 400);
dbg.drawLine(275, 175, 275, 400);
dbg.setColor(Color.BLUE);
dbg.drawString("Wins: " + player2Wins, 625, 160);
dbg.drawString("7", 550, 200);
dbg.drawString("Fire", 550, 220);
dbg.drawString("Slug", 550, 240);
dbg.drawString("4", 550, 270);
dbg.drawString("Rotate", 550, 290);
dbg.drawString("CCW", 550, 310);
dbg.drawString("1", 550, 340);
dbg.drawString("Weapon", 550, 360);
dbg.drawString("Energy", 550, 380);
dbg.drawString("8", 625, 200);
dbg.drawString("", 625, 220);
dbg.drawString("Cloak", 625, 240);
dbg.drawString("5", 625, 270);
dbg.drawString("Engine", 625, 290);
dbg.drawString("Thrust", 625, 310);
dbg.drawString("2", 625, 340);
dbg.drawString("Hyper", 625, 360);
dbg.drawString("Space", 625, 380);
dbg.drawString("9", 700, 200);
dbg.drawString("Fire", 700, 220);
dbg.drawString("Torpedo", 700, 240);
dbg.drawString("6", 700, 270);
dbg.drawString("Rotate", 700, 290);
dbg.drawString("CW", 700, 310);
dbg.drawString("3", 700, 340);
dbg.drawString("Shield", 700, 360);
dbg.drawString("Energy", 700, 380);
dbg.drawLine(525, 175, 750, 175);
dbg.drawLine(525, 250, 750, 250);
dbg.drawLine(525, 325, 750, 325);
dbg.drawLine(525, 400, 750, 400);
dbg.drawLine(525, 175, 525, 400);
dbg.drawLine(600, 175, 600, 400);
dbg.drawLine(675, 175, 675, 400);
dbg.drawLine(750, 175, 750, 400);
dbg.setColor(Color.WHITE);
dbg.drawString("P: start / pause / resume", 87, 450);
dbg.drawString("Esc: quit", 562, 450);
}
else if (gameState == GameState.RUNNING || gameState == GameState.PAUSED)
{ // ships, planet, bullets, etc., all gameplay elements
// iterate over sprites updating each one. If currentFrame is -1, delete, otherwise, draw current frame
for (int i = spriteAnimations.size() - 1; i >= 0; i--)
{
SpriteAnimation si = spriteAnimations.get(i);
si.updateFrame();
if (si.getCurrentFrame() == -1)
spriteAnimations.remove(i);
else
si.draw(dbg, this);
}
/* dbg.setColor(Color.WHITE);
dbg.drawString("Acceleration a: " + String.format("%3.2f",a) + "\n ax: " + String.format("%3.2f",ax) + "\n ay: " + String.format("%3.2f",ay), 20, 40);
dbg.drawString("Coordinates rsq: " + String.format("%6.2f",rsq) + "\n x: " + String.format("%3.2f",x) + "\n y: " + String.format("%3.2f",y), 20, 80);
dbg.drawString("Average UPS: " + String.format("%4.1f",avgups), 20, 120);
dbg.drawString("Average FPS: " + String.format("%4.1f",avgfps), 20, 160);
dbg.drawString("Mouse Click: " + String.format("X: %d Y: %d", mouseX, mouseY), 20, 200); */
dbg.setColor(Color.RED);
dbg.drawString("S", 20, 530);
dbg.fillRect(35, 525, player1.getShieldEnergy() * 3, 2);
dbg.drawString("W", 20, 550);
dbg.fillRect(35, 545, player1.getWeaponEnergy() * 3, 2);
dbg.setColor(Color.BLUE);
dbg.drawString("S", 760, 530);
dbg.fillRect(755 - player2.getShieldEnergy() * 3, 525, player2.getShieldEnergy() * 3, 2);
dbg.drawString("W", 760, 550);
dbg.fillRect(755 - player2.getWeaponEnergy() * 3, 545, player2.getWeaponEnergy() * 3, 2);
if (gameState == GameState.OVER)
gameOverMessage(dbg);
}
} // end of gameRender();
/* possible collisions
* static sprite: planet
* dynamic sprite: slug or missile
* intelligent sprite: player 1 or player 2 ships
* intelligent sprite vs. intelligent sprite: both bounce, take moderate damage
* intelligent sprite vs. dynamic sprite: intelligent takes minor damage, dynamic is destroyed
* intelligent sprite vs. static sprite: intelligent bounces, takes major damage
* dynamic sprite vs. dynamic sprite: both are destroyed
* dynamic sprite vs. static sprite: dynamic is destroyed
* static sprite vs. static sprite: no collisions possible, neither are capable of movement
*/
public boolean doCollide(StaticSprite a, StaticSprite b)
{
/* We first check if the two sprites even can collide
* and if so, then we check if their circles intersect
*/
Level aLevel = a.getExistsOnLevel();
Level aLevels[] = a.getCollidesWithLevels();
Level bLevel = b.getExistsOnLevel();
Level bLevels[] = b.getCollidesWithLevels();
for (int i = 0, j = aLevels.length; i < j; i++ )
{
if (aLevels[i] == bLevel)
{
for (int k = 0, l = bLevels.length; k < l; k++ )
{
if (bLevels[k] == aLevel)
{
if (Math.pow((b.getX() - a.getX()) * (b.getX() - a.getX()) + (b.getY() - a.getY()) * (b.getY() - a.getY()), 0.5) <= (a.getWidth()/2 + b.getWidth()/2))
return true;
else
return false;
}
}
}
}
return false;
}
public boolean collide(IntelligentSprite a, IntelligentSprite b)
{ // ship with ship
//if (b instanceof IntelligentSprite) {} // stop checking using instanceof and do it using overloading
// thanks to http://archive.ncsa.illinois.edu/Classes/MATH198/townsend/math.html
// check for collision
if (doCollide(a, b))
{
// find trajectories of each ball
double a_dir_before = Math.atan2(a.getVVelocity(),a.getHVelocity());
double b_dir_before = Math.atan2(((IntelligentSprite)b).getVVelocity(),((IntelligentSprite)b).getHVelocity());
// find combined vector velocity of each ball
double a_vel_before = Math.pow(a.getHVelocity() * a.getHVelocity() + a.getVVelocity() * a.getVVelocity(), 0.5);
double b_vel_before = Math.pow(((IntelligentSprite)b).getHVelocity() * ((IntelligentSprite)b).getHVelocity() + ((IntelligentSprite)b).getVVelocity() * ((IntelligentSprite)b).getVVelocity(), 0.5);
// find normal of collision
double normal = Math.atan2(b.getY() - a.getY(), b.getX() - a.getX());
// find separation between ball trajectories and normal
double a_dir_normal_before = a_dir_before - normal;
double b_dir_normal_before = b_dir_before - normal;
// find the velocities of each ball along the normal and tangent directions
double a_vel_nor_before = a_vel_before * Math.cos(a_dir_normal_before);
double a_vel_tan_before = a_vel_before * Math.sin(a_dir_normal_before);
double b_vel_nor_before = b_vel_before * Math.cos(b_dir_normal_before);
double b_vel_tan_before = b_vel_before * Math.sin(b_dir_normal_before);
// find velocities after collision, relative to the normal
// balls keep their normal velocities but exchange tangent velocities
double a_vel_nor_after = b_vel_nor_before;
double a_vel_tan_after = a_vel_tan_before;
double b_vel_nor_after = a_vel_nor_before;
double b_vel_tan_after = b_vel_tan_before;
// find velocities after collision, total
double a_vel_after = Math.pow(a_vel_nor_after * a_vel_nor_after + a_vel_tan_after * a_vel_tan_after, 0.5);
double b_vel_after = Math.pow(b_vel_nor_after * b_vel_nor_after + b_vel_tan_after * b_vel_tan_after, 0.5);
// shrink speeds to speed limit
if (a_vel_after > ((IntelligentSprite)a).getTopSpeed()) a_vel_after = ((IntelligentSprite)a).getTopSpeed();
if (b_vel_after > ((IntelligentSprite)b).getTopSpeed()) b_vel_after = ((IntelligentSprite)b).getTopSpeed();
// find trajectory (relative to normal), after collision
double a_dir_normal_after = Math.atan2(a_vel_tan_after, a_vel_nor_after);
double b_dir_normal_after = Math.atan2(b_vel_tan_after, b_vel_nor_after);
// find trajectory (relative to original coordinate system), after collision
// ball keeps normal velocity but tangent velocity goes negative since it is reflecting at an angle equal to the angle of incidence
double a_dir_after = a_dir_normal_after + normal;
double b_dir_after = b_dir_normal_after + normal;
// find vector velocities (relative to original coordinate system), after collision
a.setHVelocity((float)(a_vel_after * Math.cos(a_dir_after)));
a.setVVelocity((float)(a_vel_after * Math.sin(a_dir_after)));
/* a.setCollidable(false); */
((IntelligentSprite)b).setHVelocity((float)(b_vel_after * Math.cos(b_dir_after)));
((IntelligentSprite)b).setVVelocity((float)(b_vel_after * Math.sin(b_dir_after)));
// both take minor damage
a.damage(SHIP_DAMAGE);
b.damage(SHIP_DAMAGE);
if (a.getAlive() == true)
spriteAnimations.add(new SpriteAnimation(imgsShield, 0.1, false, a));
else
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, a));
ship_explosion.play();
}
if (b.getAlive() == true)
spriteAnimations.add(new SpriteAnimation(imgsShield, 0.1, false, b));
else
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, b));
ship_explosion.play();
}
return true;
}
else
return false;
}
public boolean collide(IntelligentSprite a, DynamicSprite b)
{ // ship with slug or torpedo
if (doCollide(a, b))
{
// ship takes moderate damage, slug or torpedo
if (b.getExistsOnLevel() == Level.SLUG)
a.damage(SLUG_DAMAGE);
else
{ // torpedo causes explosion on itself
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, b));
torpedo_explosion.play();
a.damage(TORPEDO_DAMAGE);
}
b.damage();
if (a.getAlive() == true) // shield flickers or ship explodes if it dies
spriteAnimations.add(new SpriteAnimation(imgsShield, 0.1, false, a));
else
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, a));
ship_explosion.play();
}
return true;
}
else
return false;
}
public boolean collide(IntelligentSprite a, StaticSprite b)
{ // ship with planet
/* if a ship gets inside a planet's radius before bouncing out due to a threading pause
* it will start colliding rapidly, die, but still collide and produce animations of
* exploding forever, and therefore the game will never reset. This doesn't eliminate
* the problem of snagging on the planet, but at least once the ship is dead it won't
* continue to collide and produce animations, so the game will reset.
*/
if (a.getAlive() == false)
return false;
if (doCollide(a, b))
{
// find trajectory of ship
double a_dir_before = Math.atan2(a.getVVelocity(),a.getHVelocity());
// find combined vector velocity of ship
double a_vel_before = Math.pow(a.getHVelocity() * a.getHVelocity() + a.getVVelocity() * a.getVVelocity(), 0.5);
// find normal of collision
double normal = Math.atan2(b.getY() - a.getY(), b.getX() - a.getX());
// find separation between ship trajectory and normal
double a_dir_normal_before = a_dir_before - normal;
// find the velocity of ball along the normal and tangent directions
double a_vel_nor_before = a_vel_before * Math.cos(a_dir_normal_before);
double a_vel_tan_before = a_vel_before * Math.sin(a_dir_normal_before);
// find velocity after collision, relative to the normal
double a_vel_nor_after = -a_vel_nor_before;
double a_vel_tan_after = a_vel_tan_before;
// find velocity after collision, total
double a_vel_after = Math.pow(a_vel_nor_after * a_vel_nor_after + a_vel_tan_after * a_vel_tan_after, 0.5);
// do not need to check speed limit because ship can't increase speed on bounce
// find trajectory (relative to normal), after collision
double a_dir_normal_after = Math.atan2(a_vel_tan_after, a_vel_nor_after);
// find trajectory (relative to original coordinate system), after collision
double a_dir_after = a_dir_normal_after + normal;
// find vector velocity (relative to original coordinate system), after collision
a.setHVelocity((float)(a_vel_after * Math.cos(a_dir_after)));
a.setVVelocity((float)(a_vel_after * Math.sin(a_dir_after)));
/* a.setCollidable(false); */
// ship takes major damage
a.damage(PLANET_DAMAGE);
if (a.getAlive() == true)
spriteAnimations.add(new SpriteAnimation(imgsShield, 0.1, false, a));
else
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, a));
ship_explosion.play();
}
return true;
}
else
return false;
}
public boolean collide(DynamicSprite a, DynamicSprite b)
{ // slug with torpedo
if (doCollide(a, b))
{
// Both slugs/torpedoes die, they have no shield points
if (a.getExistsOnLevel () == Level.TORPEDO)
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, a));
torpedo_explosion.play();
}
if (b.getExistsOnLevel () == Level.TORPEDO)
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, b));
torpedo_explosion.play();
}
a.damage();
b.damage();
return true;
}
else
return false;
}
public boolean collide(DynamicSprite a, StaticSprite b)
{ // slug or torpedo with planet
if (doCollide(a, b))
{
// Planet cannot be damaged, slug/torpedo dies
if (a.getExistsOnLevel () == Level.TORPEDO)
{
spriteAnimations.add(new SpriteAnimation(imgsExplosion, 1.0, false, a));
torpedo_explosion.play();
}
a.damage();
return true;
}
else
return false;
}
public boolean collide(StaticSprite a, StaticSprite b)
{ // planet with planet
if (doCollide(a, b))
// not really possible, planets don't move
return true;
else
return false;
}
public void shootSlug(IntelligentSprite i)
{
if (i.getWeaponEnergy() > 0)
{
i.setWeaponEnergy(i.getWeaponEnergy() - 1);
DynamicSprite slug = new DynamicSprite(imgSlug);
slug.setX(i.getX());
slug.setY(i.getY());
slug.setWidth(2);
slug.setHeight(2);
slug.setVisible(true);
slug.setExistsOnLevel(Level.SLUG);
if (i == player1)
slug.setCollidesWithLevels(new Level[] {Level.PLANET, Level.PLAYER2, Level.TORPEDO});
else // player2
slug.setCollidesWithLevels(new Level[] {Level.PLANET, Level.PLAYER1, Level.TORPEDO});
float firingAngleRadians = (float)(i.getRotation() * 22.5 * Math.PI / 180.0f);
slug.setHVelocity(i.getHVelocity() + (float)(Math.cos(firingAngleRadians) * SLUG_SPEED));
slug.setVVelocity(i.getVVelocity() + (float)(Math.sin(firingAngleRadians) * SLUG_SPEED));
slug.setRotation(i.getRotation());
slugs.add(slug);
slug_launch.play();
}
}
public void shootTorpedo(IntelligentSprite i)
{
if (i.getWeaponEnergy() > 0)
{
i.setWeaponEnergy(i.getWeaponEnergy() - 5);
DynamicSprite torpedo = new DynamicSprite(imgTorpedo);
torpedo.setX(i.getX());
torpedo.setY(i.getY());
torpedo.setWidth(8);
torpedo.setHeight(8);
torpedo.setRotation(0);
torpedo.rotate(i.getRotation());
torpedo.setVisible(true);
torpedo.setExistsOnLevel(Level.TORPEDO);
if (i == player1)
torpedo.setCollidesWithLevels(new Level[] {Level.PLANET, Level.PLAYER2, Level.SLUG, Level.TORPEDO});
else // player2
torpedo.setCollidesWithLevels(new Level[] {Level.PLANET, Level.PLAYER1, Level.SLUG, Level.TORPEDO});
float firingAngleRadians = (float)(i.getRotation() * 22.5 * Math.PI / 180.0f);
torpedo.setHVelocity(i.getHVelocity() + (float)(Math.cos(firingAngleRadians) * TORPEDO_SPEED));
torpedo.setVVelocity(i.getVVelocity() + (float)(Math.sin(firingAngleRadians) * TORPEDO_SPEED));
torpedo.setRotation(i.getRotation());
torpedoes.add(torpedo);
torpedo_launch.play();
}
}
public void hyperspace(IntelligentSprite i)
{
if (i.getWeaponEnergy() >= 10)
{
i.setX((float)Math.random() * PWIDTH);
i.setY((float)Math.random() * PHEIGHT);
i.setWeaponEnergy(i.getWeaponEnergy() - 10);
ship_warp.play();
}
}
public void cloak(IntelligentSprite i)
{
if (i.getWeaponEnergy() >= 10)
{
i.setLastCloakTime((long) (System.nanoTime() / 1e9));
i.setVisible(false);
i.setWeaponEnergy(i.getWeaponEnergy() - 10);
}
}
@Override
public void update(Graphics g) { paint(g); }
@Override
public void paint(Graphics g) // why not paintComponent()?
{
//super.paint(g); // why JApplet doesn't have paintComponent()? and why do I get flicker if I use this?
if (dbImage != null)
g.drawImage(dbImage, 0, 0, null);
}
private void gameOverMessage(Graphics g)
{
// center the game-over message
String msg = "Game Over";
// code to calculate x and y
int x = PWIDTH / 2;
int y = PHEIGHT / 2;
g.drawString(msg, x, y);
} // end of gameOverMessage();
}
|
C | UTF-8 | 943 | 3.359375 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2017, Billie Soong <nonkr@hotmail.com>
* All rights reserved.
*
* This file is under MIT, see LICENSE for details.
*
* Author: Billie Soong <nonkr@hotmail.com>
* Datetime: 2018/1/22 15:45
*
*/
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
// 使用clock()构造clock_t对象(实际上是long类型的变量)
clock_t t1 = clock();
// 一段计算
// for (int i = 0; i < 1000000; i++)
// {
// pow(2, i);
// }
sleep(1);
// 计算clock差,除以clock数/每秒,即可求出秒数
printf("%f\n", (double) (clock() - t1) / CLOCKS_PER_SEC);
clock_t old = 0;
clock_t tmp;
while (1)
{
sleep(1);
if (old == 0)
{
old = clock();
}
else
{
tmp = clock();
printf("### %f s\n", (tmp - old) * 1.0 / CLOCKS_PER_SEC);
old = tmp;
}
}
return 0;
}
|
JavaScript | UTF-8 | 261 | 2.6875 | 3 | [] | no_license | const validatePassoword = (passoword) => {
const passwordRegex = /^[0-9]*$/;
(passoword < 4 || passoword > 8 || password.match(passwordRegex) === false)
? { status: 400, message: "Incorrect password" }
: 'OK';
};
module.exports = validatePassoword;
|
Python | UTF-8 | 1,304 | 2.734375 | 3 | [] | no_license | #Google kickstart 2020 round a "Plates"
cases = 0
testcases = int(input())
while cases != testcases:
suma2=0
spb2=[]
spb=[]
cases += 1
var=1
variables = input().split()
array=[]
stacknum=(variables[0])
stacknum=int(stacknum)
platenum=(variables[1])
plateswantednum=(variables[2])
pwm=int(plateswantednum)
stacksplatesbeauty=[]
for i in range((stacknum)):
stacksplatesbeauty.append(input().split())
for i in range(len(stacksplatesbeauty)):
array=(stacksplatesbeauty[i])
spb=[]
for i in range(len(array)):
spb.append(int(array[i]))
spb2.append(spb)
#print(len(spb))
print(spb2)
for i in range(len(spb2)):
print(spb2[i])
stack=spb2[i]
for i in range(len(stack)):
if var == 1:
suma=sum(stack[:(i+1)])
sumas=suma+suma2
print(sumas)
var=0
if var == 0:
suma=sum(stack[:(i+2)])
sumas=suma+suma2
print(sumas)
var=1
suma2=suma
#beauty.append(sum())
#print("Case #"+str(cases)+": "+str( ))
|
PHP | UTF-8 | 1,013 | 2.703125 | 3 | [] | no_license | <?php
function getFromUrl($url, $method = 'GET')
{
$ch = curl_init();
$agent = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)';
switch(strtoupper($method))
{
case 'GET':
curl_setopt($ch, CURLOPT_URL, $url);
break;
case 'POST':
$info = parse_url($url);
$url = $info['scheme'] . '://' . $info['host'] . $info['path'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $info['query']);
break;
default:
return false;
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
?> |
Python | UTF-8 | 7,208 | 2.734375 | 3 | [
"MIT"
] | permissive | from collections import Counter
from operator import itemgetter
from collections import OrderedDict
from random import choice, shuffle
from tqdm import tqdm
import itertools
import torch
import torch.utils.data as data
import torch.nn.functional as fn
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.sampler import Sampler
class TuplesListDataset(Dataset):
def __init__(self, tuplelist,rows=None,immutable=False):
super(TuplesListDataset, self).__init__()
self.tuplelist = tuplelist
self.mappings = {}
self.rows = rows
self.immutable = immutable
def __len__(self):
return len(self.tuplelist)
def __getitem__(self,index):
if len(self.mappings) == 0 or self.immutable:
return self.tuplelist[index]
else:
t = list(self.tuplelist[index])
for i,m in self.mappings.items():
t[i] = m(t[i])
return tuple(t)
def __iter__(self):
return self.tuplelist.__iter__()
def _f2i(self,field):
if type(field) == int:
return field
if type(field) == str:
return self.rows[field]
if type(field) == str and self.rows == None:
raise IndexError("field {} index is unknown, no rows attribute provided".format(field))
raise IndexError("field {} doesn't exist".format(field))
def _check_immutable(self):
if self.immutable:
raise Exception("TuplesListDataset is immutable --> set self.immutable to False to override")
def field_gen(self,field,transform=False):
field = self._f2i(field)
if transform:
for i in range(len(self)):
yield self[i][field]
else:
for x in self:
yield x[field]
def get_stats(self,field):
field = self._f2i(field)
d = dict(Counter(self.field_gen(field,True)))
sumv = sum([v for k,v in d.items()])
class_per = {k:(v/sumv) for k,v in d.items()}
return d,class_per
def get_field_dict(self,field,offset=0):
field = self._f2i(field)
d2k = {c:i for i,c in enumerate(set(self.field_gen(field)),offset)}
return d2k
def set_mapping(self,field,mapping=None,offset=0, unk=None):
"""
Sets or creates a mapping for a tuple field. Mappings are {k:v} with keys starting at offset.
"""
self._check_immutable()
field = self._f2i(field)
if mapping is None:
mapping = self.get_field_dict(field,offset)
else:
if unk is not None:
mapping.update(((uk,unk) for uk in set(self.field_gen(field)) if uk not in mapping))
self.mappings[field] = mapping.__getitem__
return mapping
def set_transform(self,field,transform):
"""
sets a field transformation where transform is a function of the field i.e f(field) -> transformed
"""
self._check_immutable()
field = self._f2i(field)
self.mappings[field] = transform
def prebuild(self,inplace=False,keep_maps=False,keep_trans=False):
"""
pre-makes all transformations - usefull if they are heavy.
inplace -> object is modified inplace
keep_maps -> if inplace, to keep dictionnary mappings (functions are discarded.)
"""
self._check_immutable() # already built.
if not inplace:
return TuplesListDataset([self[i] for i in tqdm(range(len(self)),total=len(self),desc="Prebuilding set")],rows=self.rows,immutable=True)
else:
for i in tqdm(range(len(self)),desc="Prebuilding set",total=len(self)):
self.tuplelist[i] = self[i]
if not keep_maps:
self.mappings = {}
else:
if not keep_trans:
self.mappings = {x:v for x,v in self.mappings.items() if type(v) == dict}
self.immutable = True
@staticmethod
def build_train_test(datatuples,splits,split_num=0,validation=0.5,rows=None,hide=None):
"""
Builds train/val/test sets
Validation set at 0.5 if n split is 5 gives an 80:10:10 split as usually used.
hi
"""
train,test = [],[]
for split,data in tqdm(zip(splits,datatuples),total=len(datatuples),desc="Building train/test of split #{}".format(split_num)):
if split == split_num:
test.append(data)
else:
train.append(data)
if len(test) <= 0:
raise IndexError("Test set is empty - split {} probably doesn't exist".format(split_num))
if rows and type(rows) is tuple:
rows = {v:k for k,v in enumerate(rows)}
print("TuplesListDataset rows are the following:")
print(rows)
if validation > 0:
if 0 < validation < 1:
val_len = int(validation * len(test))
validation = test[-val_len:]
test = test[:-val_len]
return TuplesListDataset(train,rows),TuplesListDataset(validation,rows),TuplesListDataset(test,rows)
return TuplesListDataset(train,rows),None,TuplesListDataset(test,rows) #None for no pb
class Vectorizer():
def __init__(self,word_dict=None,max_sent_len=8,max_word_len=32):
self.word_dict = word_dict
self.max_sent_len = max_sent_len
self.max_word_len = max_word_len
def _get_words_dict(self,data,max_words):
word_counter = Counter(itertools.chain.from_iterable(w for s in data for w in s))
dict_w = {w: i for i,(w,_) in tqdm(enumerate(word_counter.most_common(max_words),start=2),desc="building word dict",total=max_words)}
dict_w["_padding_"] = 0
dict_w["_unk_word_"] = 1
print("Dictionnary has {} words".format(len(dict_w)))
return dict_w
def build_dict(self,text_iterator,max_f):
self.word_dict = self._get_words_dict(text_iterator,max_f)
def vectorize_batch(self,t,trim=True):
return self._vect_dict(t,trim)
def _vect_dict(self,t,trim):
if self.word_dict is None:
print("No dictionnary to vectorize text \n-> call method build_dict \n-> or set a word_dict attribute \n first")
raise Exception
if type(t) == str:
t = [t]
revs = []
for rev in t:
review = []
for j,sent in enumerate(rev):
if trim and j>= self.max_sent_len:
break
s = []
for k,word in enumerate(sent):
if trim and k >= self.max_word_len:
break
if word in self.word_dict:
s.append(self.word_dict[word])
else:
s.append(self.word_dict["_unk_word_"]) #_unk_word_
if len(s) >= 1:
review.append(s)
if len(review) == 0:
review = [[self.word_dict["_unk_word_"]]]
revs.append(review)
return revs
|
C++ | UTF-8 | 1,747 | 3.140625 | 3 | [
"MIT"
] | permissive | #include "../../include/Utils/MCString.hpp"
#include <cstring>
using namespace Utils;
MCString::MCString() : m_stringLength(0)
{
InitializeFromString("");
}
MCString::MCString(const std::string& str)
{
InitializeFromString(str);
}
// Copy constructor
MCString::MCString(const MCString& str)
{
*this = str;
}
// Copy assignment
MCString& MCString::operator=(const MCString& str)
{
std::memcpy(m_data, str.m_data, sizeof(m_data));
Sanitize();
return *this;
}
// Copy assignment
MCString& MCString::operator=(const std::string& str)
{
InitializeFromString(str);
return *this;
}
std::string MCString::ToString() const
{
return std::string(reinterpret_cast<const char*>(m_data), m_stringLength);
}
void MCString::InitializeFromString(const std::string& str)
{
size_t dataLength = sizeof(m_data);
m_stringLength = str.length();
if (m_stringLength < dataLength) {
std::memset(&m_data[m_stringLength], 0x20, dataLength - m_stringLength);
std::memcpy(m_data, str.c_str(), m_stringLength);
} else {
std::memcpy(m_data, str.c_str(), dataLength);
m_stringLength = dataLength;
}
}
void MCString::InitializeFromRawBuffer(const std::uint8_t(&buffer)[64])
{
std::memcpy(m_data, buffer, 64);
Sanitize();
}
void MCString::Sanitize()
{
// Default string length; used if loop below doesn't find padding
m_stringLength = 64;
int paddingIndex = -1;
// Minecraft classic string padding
for (int i = 0; i < sizeof(m_data); ++i) {
if (m_data[i] == 0x20 || m_data[i] == 0x00) {
if (paddingIndex == -1)
paddingIndex = i;
} else {
paddingIndex = -1;
}
}
if (paddingIndex >= 0)
m_stringLength = static_cast<size_t>(paddingIndex);
}
|
C++ | UTF-8 | 1,473 | 3.296875 | 3 | [] | no_license | #include "piece.hh"
#include <stdio.h>
const char* Piece::pieceNames[] = { "Pawn", "Rook", "Bishop", "Knight", "Queen", "King" };
const char* Piece::colorNames[] = { "white", "black" };
Piece::Piece(Board* board, ePieceColor color, ePieceType type) :
board(board),
color(color),
type(type),
field(NULL),
moved(false) {
}
Piece::~Piece() {
}
ePieceColor Piece::getColor() {
return color;
}
ePieceColor Piece::getAttackColor() {
if (color == white) {
return black;
} else {
return white;
}
}
const char* Piece::getColorName() {
return colorNames[color];
}
ePieceType Piece::getType() {
return type;
}
const char* Piece::getName() {
return Piece::pieceNames[type];
}
void Piece::setField(Field* newField) {
field = newField;
moved = true;
}
Field* Piece::getField() {
return field;
}
void Piece::setMoved(bool moved) {
this->moved = moved;
}
bool Piece::isMoved() {
return moved;
}
bool Piece::isOnBoard() {
return field;
}
void Piece::removeFromBoard() {
field = NULL;
}
void Piece::getSymbol(char* symbol) {
unsigned char letter = 0;
switch(type) {
case pawn: letter = 'P'; break;
case rook: letter = 'R'; break;
case bishop: letter = 'B'; break;
case knight: letter = 'N'; break;
case queen: letter = 'Q'; break;
case king: letter = 'K'; break;
}
if (color == white) {
sprintf(symbol, "%c", letter);
} else {
sprintf(symbol, "\033[7m%c\033[0m", letter);
}
}
|
Python | UTF-8 | 1,336 | 3.203125 | 3 | [] | no_license | with open('file16.in') as f:
content = f.readlines()
content = [x.strip() for x in content]
content = content[0].split(',')
dance = "abcdefghijklmnop"
def flipdance(first, second, dance):
if first < second:
temp = first
first = second
second = temp
return dance[:second] + dance[first] + dance[second+1:first] + dance[second] + dance[first+1:]
dancelist = []
found = False
count = 0
while found == False:
for each in content:
if 's' == each[:1]:
flip = 16 - int(each[1:])
dance = dance[flip:] + dance[:flip]
elif 'x' == each[:1]:
temp = each[1:]
tempfirst = int(temp[:temp.index('/')])
tempsecond = int(temp[temp.index('/')+1:])
dance = flipdance(tempfirst, tempsecond, dance)
elif 'p' == each[:1]:
temp = each[1:]
firstflip = temp[:temp.index('/')]
secondflip = temp[temp.index('/')+1:]
dance = flipdance(dance.index(firstflip), dance.index(secondflip), dance)
if dance in dancelist:
found = True
else:
dancelist.append(dance)
count += 1
print(dancelist[0]) #part 1
value = 0
if 1000000 % count == 0:
value = count -1
else:
value = (1000000 % count) - 1
print(dancelist[value]) #part 2
|
C++ | UTF-8 | 8,037 | 3.109375 | 3 | [] | no_license | #include <cmath>
#include <exception>
#include <fstream>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include "mathio.hpp"
// Exception para Falha de Abertura de arquivo
class bad_arquivo : public std::exception {
public:
const char* what() const noexcept {return "Erro ao abrir arquivo\n";}
};
// Constantes matematicas
const double PI = acos(-1);
const double e = exp(1);
const double TAU = 2 * PI;
// Texto para cada operacao implementada:
const std::array<std::string, 25> OPS = {
"+", "-", "*", "/", "^", // 5
"sin", "asin", "cos", "acos", "tg", "atg", // 6
"sinh", "asinh", "cosh", "acosh", "tgh", "atgh", // 6
"sqrt", "log", "ln", "exp", "abs", // 5
"tau", "pi", "e"}; // 3
// Elementos a serem adicionados quando a respectiva operacao em OPS for realizada (-1 indica que a pilha tera 1 elemento a menos):
const std::array<int, 25> EFEITO = {
-1, -1, -1, -1, -1,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
1, 1, 1};
// Diferentes tipos de operacao em uma stack.(Adicionar numero no topo, realizar operacao matematica e adicionar valor de variavel no topo)
enum {NUM, OP, VAR};
union tipoDado_u {
double num;
uint64_t op;
uint64_t var;
};
// Cada operacao em RPN tem dois valores, o primeiro indica qual o segundo dado. O segundo dado pode ser um numero, operacao ou variavel.
// Caso o segundo dado seja um numero, isso significa que esse numero deve ser adicionado a stack.
// Caso o segundo dado seja uma operacao, a operacao deve ser realizada com os numeros no topo da stack.
// Caso o segundo dado seja uma variavel, o valor da variavel deve ser adicionada a stack.
typedef std::queue<std::pair<uint8_t, tipoDado_u>> fRPN_t;
// Calcula resultado de uma funcao calculada em _args. Funcao descrita por _RPN.
double executar_operacoes(fRPN_t _RPN, std::vector<double> _args);
// Calcula o resultado de uma unica operacao na pilha.
void operacao_stack(std::stack<double> *_pilha, uint64_t _op);
// # # # Definicao das funcoes # # #
std::function<double(std::vector<double>)> ler_funcao(std::vector<std::string> _vars) {
fRPN_t _funcao; // Descricao da funcao em RPN
tipoDado_u _temp;
std::string _entrada;
int _prof = 0; // Acumula quantos elementos a stack possui
while(std::cin.rdbuf()->in_avail() != 0) {
std::cin.get();
}
do {
// Descarta espacos:
if(std::cin.peek() == ' ') {
std::cin.get();
continue;
}
std::cin >> _entrada;
// Verifica se o valor inserido e um numero:
if(isdigit(_entrada[0]) || (_entrada[0] == '-' && isdigit(_entrada[1]))) {
_temp.num = stod(_entrada);
_funcao.push(std::pair(NUM, _temp));
_prof++;
}
else {
// Verifica se a entrada analisada e uma operacao:
for(size_t i = 0; i != OPS.size(); i++) {
if(_entrada == OPS[i]) {
_temp.op = i;
_funcao.push(std::pair(OP, _temp));
_prof += EFEITO[i];
break;
}
}
// Verifica se a entrada analisada e uma variavel:
for(size_t i = 0; i != _vars.size(); i++) {
if(_entrada == _vars[i]) {
_temp.var = i;
_funcao.push(std::pair(VAR, _temp));
_prof++;
break;
}
}
}
// Verifica se a ultima operacao nao utiliza elementos que nao estao na stack:
if(_prof <= 0) return nullptr;
}while(std::cin.peek() != '\n');
if(_funcao.size() == 0) return nullptr;
// Funcao lambda que calcula a funcao no ponto definido por _args:
return [_funcao](std::vector<double> _args) {
return executar_operacoes(_funcao, _args);
};
}
inline double executar_operacoes(fRPN_t _RPN, std::vector<double> _args) {
std::stack<double> _pilha;
// Executa cada passo descrito por _RPN:
while(_RPN.size() > 0) {
// Passo atual:
auto i = _RPN.front();
_RPN.pop();
// Verifica se o passo atual manda adicionar um numero a stack:
if(i.first == NUM) {
_pilha.push(i.second.num);
}
// Verifica se o passo atual e uma operacao matematica:
else if(i.first == OP) {
operacao_stack(&_pilha, i.second.op);
}
// Verifica se o passo atual e adicionar o valor de uma variavel a pilha:
else if(i.first == VAR) {
_pilha.push(_args[i.second.var]);
}
}
// Retorna o que esta no topo da pilha
return _pilha.top();
}
void operacao_stack(std::stack<double> *_pilha, uint64_t _op) {
double a, b;
// Executa a respectiva operacao(O numero e definido pela posicao da operacao no array OPS):
switch(_op) {
case 0: // "+"
a = _pilha -> top();
_pilha -> pop();
b = _pilha -> top();
_pilha -> pop();
_pilha -> push(a + b);
break;
case 1: // "-"
a = _pilha -> top();
_pilha -> pop();
b = _pilha -> top();
_pilha -> pop();
_pilha -> push(b - a);
break;
case 2: // "*"
a = _pilha -> top();
_pilha -> pop();
b = _pilha -> top();
_pilha -> pop();
_pilha -> push(a * b);
break;
case 3: // "/"
a = _pilha -> top();
_pilha -> pop();
b = _pilha -> top();
_pilha -> pop();
_pilha -> push(b / a);
break;
case 4: // "^"
a = _pilha -> top();
_pilha -> pop();
b = _pilha -> top();
_pilha -> pop();
_pilha -> push(pow(b, a));
break;
case 5: // "sin"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(sin(a));
break;
case 6: // "asin"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(asin(a));
break;
case 7: // "cos"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(cos(a));
break;
case 8: // "acos"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(acos(a));
break;
case 9: // "tg"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(tan(a));
break;
case 10: // "atg"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(atan(a));
break;
case 11: // "sinh"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(sinh(a));
break;
case 12: // "asinh"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(asinh(a));
break;
case 13: // "cosh"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(cosh(a));
break;
case 14: // "acosh"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(acosh(a));
break;
case 15: // "tgh"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(tanh(a));
break;
case 16: // "atgh"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(atanh(a));
break;
case 17: // "sqrt"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(sqrt(a));
break;
case 18: // "log"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(log10(a));
break;
case 19: // "ln"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(log(a));
break;
case 20: // "exp"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(exp(a));
break;
case 21: // "abs"
a = _pilha -> top();
_pilha -> pop();
_pilha -> push(fabs(a));
break;
// Operacoes tau, pi e e sao utilizadas para adicionar elemento na lista
case 22: // "tau"
_pilha -> push(TAU);
break;
case 23: // "pi"
_pilha -> push(PI);
break;
case 24: // "e"
_pilha -> push(e);
break;
}
return;
}
void gerar_grafico(std::string _nomeArquivo, std::list<std::pair<double, double>>::iterator _inicio, std::list<std::pair<double, double>>::iterator _fim) {
std::ofstream _arquivo(_nomeArquivo);
if(_arquivo.is_open()) {
while(_inicio != _fim) {
_arquivo << _inicio -> first << "\t" << _inicio -> second << std::endl;
_inicio++;
}
}
else {
throw bad_arquivo();
}
return;
}
void gerar_grafico(std::string _nomeArquivo, std::function<double(std::vector<double>)> f, intervalo_t _I, double _step) {
std::list<std::pair<double, double>> _lista;
for(auto i = _I.first; i <= _I.second; i += _step) {
_lista.push_back(std::pair(i, f({i})));
}
gerar_grafico(_nomeArquivo, _lista.begin(), _lista.end());
return;
}
|
JavaScript | UTF-8 | 507 | 4.09375 | 4 | [] | no_license | //!What is logged out?
var arr1 = [];
var arr2 = new Array(50);
var arr3 = new Array(1, 2, "three", 4, "five");
var arr4 = new Array([1, 2, 3, 4, 5]);
console.log('arr1: ', arr1); // []
console.log('arr2: ', arr2); // [<50 empty items>] array of length 50, but every element in the array is empty. That is how the array constructor method works if we pass in a single NUMBER of 0 or greater.
console.log('arr3: ', arr3); // [1, 2, 'three', 4, 'five']
console.log('arr4: ', arr4); // [ [1, 2, 3, 4, 5 ] ] |
C# | UTF-8 | 21,400 | 2.765625 | 3 | [] | no_license | using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using TouhouCardEngine;
using TouhouCardEngine.Interfaces;
namespace TouhouHeartstone
{
public static class THHCard
{
public static THHPlayer getOwner(this Card card)
{
return card.owner as THHPlayer;
}
public static int getCost(this Card card)
{
return card.getProp<int>(nameof(ServantCardDefine.cost));
}
public static void setCost(this Card card, int value)
{
card.setProp(nameof(ServantCardDefine.cost), value);
}
public static int getCost(this CardDefine card)
{
return card.getProp<int>(nameof(ServantCardDefine.cost));
}
public static int getAttack(this Card card)
{
int result = card.getProp<int>(nameof(ServantCardDefine.attack));
if (result < 0)
result = 0;
return result;
}
public static int getAttack(this CardDefine card)
{
int result = card.getProp<int>(nameof(ServantCardDefine.attack));
if (result < 0)
result = 0;
return result;
}
public static void setAttack(this Card card, int value)
{
card.setProp(nameof(ServantCardDefine.attack), value);
}
public static int getLife(this Card card)
{
return card.getProp<int>(nameof(ServantCardDefine.life));
}
public static int getLife(this CardDefine card)
{
return card.getProp<int>(nameof(ServantCardDefine.life));
}
public static void setLife(this Card card, int value)
{
card.setProp(nameof(ServantCardDefine.life), value);
}
public static int getArmor(this Card card)
{
return card.getProp<int>("armor");
}
public static int getCurrentLife(this Card card)
{
return card.getProp<int>("currentLife");
}
public static void setCurrentLife(this Card card, int value)
{
card.setProp("currentLife", value);
}
public static bool isReady(this Card card)
{
return card.getProp<bool>("isReady");
}
public static void setReady(this Card card, bool value)
{
card.setProp("isReady", value);
}
public static int getAttackTimes(this Card card)
{
return card.getProp<int>("attackTimes");
}
public static void setAttackTimes(this Card card, int value)
{
card.setProp("attackTimes", value);
}
public static int getMaxAttackTimes(this Card card)
{
return 1;
}
/// <summary>
/// 这个角色能否进行攻击?
/// </summary>
/// <param name="card"></param>
/// <returns></returns>
public static bool canAttack(this Card card, THHGame game)
{
if (card.getAttack() <= 0)//没有攻击力
return false;
if (!card.isReady()//还没准备好
&& !card.isCharge()//且没有冲锋
&& !(card.isRush() && game.getOpponent(card.getOwner()).field.Any(c => card.isAttackable(game, card.getOwner(), c, out _)))//且并非有突袭且有可以攻击的敌方随从
)
return false;
if (card.getAttackTimes() >= card.getMaxAttackTimes())//已经攻击过了
return false;
return true;
}
/// <summary>
/// 这个角色能否对目标进行攻击?
/// </summary>
/// <param name="card"></param>
/// <param name="game"></param>
/// <param name="player"></param>
/// <param name="target"></param>
/// <returns></returns>
public static bool isAttackable(this Card card, THHGame game, THHPlayer player, Card target, out string tip)
{
if (target == player.master || player.field.Contains(target))
{
tip = "你不能攻击友方角色";
return false;
}
if (target.getCurrentLife() <= 0)
{
tip = "目标随从已经死亡";
return false;
}
if (game.getOpponent(player).field.Any(c => c.isTaunt()) && !target.isTaunt())
{
tip = "你必须先攻击具有嘲讽的随从";
return false;
}
if (card.isRush() && !card.isReady() && game.players.Any(p => p.master == target) && !card.isCharge())
{
tip = "具有突袭的随从在没有准备好的情况下不能攻击敌方英雄";//除非你具有冲锋
return false;
}
if (target.isStealth())
{
tip = "无法攻击潜行的目标";
return false;
}
tip = null;
return true;
}
/// <summary>
/// 技能是否已经使用过?
/// </summary>
/// <param name="card"></param>
/// <returns></returns>
public static bool isUsed(this Card card)
{
return card.getProp<bool>("isUsed");
}
/// <summary>
/// 设置技能是否使用过。
/// </summary>
/// <param name="card"></param>
/// <param name="value"></param>
public static void setUsed(this Card card, bool value)
{
card.setProp("isUsed", value);
}
public static bool isTaunt(this Card card)
{
return card.getProp<bool>(Keyword.TAUNT);
}
public static void setTaunt(this Card card, bool value)
{
card.setProp(Keyword.TAUNT, value);
}
public static bool isCharge(this Card card)
{
return card.getProp<bool>(Keyword.CHARGE);
}
public static void setCharge(this Card card, bool value)
{
card.setProp(Keyword.CHARGE, value);
}
public static bool isRush(this Card card)
{
return card.getProp<bool>(Keyword.RUSH);
}
public static void setRush(this Card card, bool value)
{
card.setProp(Keyword.RUSH, value);
}
public static bool isShield(this Card card)
{
return card.getProp<bool>(Keyword.SHIELD);
}
public static void setShield(this Card card, bool value)
{
card.setProp(Keyword.SHIELD, value);
}
public static bool isStealth(this Card card)
{
return card.getProp<bool>(Keyword.STEALTH);
}
public static void setStealth(this Card card, bool value)
{
card.setProp(Keyword.STEALTH, value);
}
public static bool isDrain(this Card card)
{
return card.getProp<bool>(Keyword.DRAIN);
}
public static void setDrain(this Card card, bool value)
{
card.setProp(Keyword.DRAIN, value);
}
public static bool isPoisonous(this Card card)
{
return card.getProp<bool>(Keyword.POISONOUS);
}
public static void setPoisonous(this Card card, bool value)
{
card.setProp(Keyword.POISONOUS, value);
}
public static bool isElusive(this Card card)
{
return card.getProp<bool>(Keyword.ELUSIVE);
}
public static void setElusive(this Card card, bool value)
{
card.setProp(Keyword.ELUSIVE, value);
}
public static int getSpellDamage(this Card card)
{
return card.getProp<int>(nameof(ServantCardDefine.spellDamage));
}
public static void setSpellDamage(this Card card, int value)
{
card.setProp(nameof(ServantCardDefine.spellDamage), value);
}
public static bool hasTag(this Card card, string tag)
{
return card.getProp<string[]>(nameof(ServantCardDefine.tags)).Contains(tag);
}
public static bool isUsable(this Card card, THHGame game, THHPlayer player, out string info)
{
if (game.currentPlayer != player)//不是你的回合
{
info = "这不是你的回合";
return false;
}
if (card.getOwner() != player)
{
info = "你不能使用不属于你的卡牌";
return false;
}
if (card.define is ServantCardDefine servant)
{
if (player.gem < card.getCost())//费用不够
{
info = "你没有足够的法力值";
return false;
}
if (player.field.count >= player.field.maxCount)
{
info = "你无法将更多的随从置入战场";
return false;
}
}
else if (card.define is SpellCardDefine spell)
{
if (player.gem < card.getCost())
{
info = "你没有足够的法力值";
return false;
}
}
else if (card.define is SkillCardDefine skill)
{
if (card.isUsed())//已经用过了
{
info = "你已经使用过技能了";
return false;
}
if (player.gem < card.getCost())//费用不够
{
info = "你没有足够的法力值";
return false;
}
if (card.define.getEffectOn<THHPlayer.ActiveEventArg>(game.triggers) is IActiveEffect effect && !effect.checkCondition(game, card, new object[]
{
new THHPlayer.ActiveEventArg(player,card,new object[0])
}))
{
info = "技能不可用";
return false;
}
}
else
{
info = "这是一张未知的卡牌";
return false;//不知道是什么卡
}
info = null;
return true;
}
public static Card[] getAvaliableTargets(this Card card, THHGame game)
{
IActiveEffect effect = card.define.getEffectOn<THHPlayer.ActiveEventArg>(game.triggers) as IActiveEffect;
if (effect == null)
return null;
List<Card> targetList = new List<Card>();
foreach (THHPlayer player in game.players)
{
if (effect.checkTarget(game, null, card, new object[] { player.master }))
targetList.Add(player.master);
foreach (Card servant in player.field)
{
if (effect.checkTarget(game, null, card, new object[] { servant }))
targetList.Add(servant);
}
}
return targetList.ToArray();
}
public static bool isValidTarget(this Card card, THHGame game, Card target)
{
IActiveEffect effect = card.define.getEffectOn<THHPlayer.ActiveEventArg>(game.triggers) as IActiveEffect;
if (effect == null)
return false;
if (target.isStealth())
return false;
return effect.checkTarget(game, null, card, new object[] { target });
}
public static async Task<bool> tryAttack(this Card card, THHGame game, THHPlayer player, Card target)
{
if (!card.canAttack(game))
{
game.logger.log(card + "无法进行攻击");
return false;
}
if (!card.isAttackable(game, player, target, out var reason))
{
game.logger.log(card + "无法攻击" + target + ",因为" + reason);
return false;
}
await game.triggers.doEvent(new AttackEventArg() { card = card, target = target }, async arg =>
{
game.logger.log(arg.card + "攻击" + arg.target);
arg.card.setAttackTimes(arg.card.getAttackTimes() + 1);
if (arg.card.getAttack() > 0)
await arg.target.damage(game, arg.card, arg.card.getAttack());
if (arg.target.getAttack() > 0)
await arg.card.damage(game, arg.target, arg.target.getAttack());
if (arg.card.isDrain())
await player.master.heal(game, arg.card.getAttack());
if (arg.target.isDrain())
await (arg.target.owner as THHPlayer).master.heal(game, arg.target.getAttack());
if (arg.card.isPoisonous() && arg.target.owner != null)
{
DamageEventArg damage = game.triggers.getRecordedEvents().LastOrDefault(e => e is THHCard.DamageEventArg) as THHCard.DamageEventArg;
//剧毒角色造成伤害后,对方死亡
if (damage.value > 0)
{
await arg.target.die(game, new DeathEventArg.Info()
{
card = target,
player = (THHPlayer)arg.target.owner,
position = player.field.indexOf(card)
});
}
}
if (arg.target.isPoisonous() && arg.card != player.master)
{
DamageEventArg damage = game.triggers.getRecordedEvents().LastOrDefault(e => e is THHCard.DamageEventArg) as THHCard.DamageEventArg;
if (damage.value > 0)
{
await arg.card.die(game, new DeathEventArg.Info()
{
card = card,
player = player,
position = player.field.indexOf(card)
});
}
}
});
await game.updateDeath();
return true;
}
public class AttackEventArg : EventArg
{
public Card card;
public Card target;
}
public static Task damage(this Card card, THHGame game, Card source, int value)
{
return damage(new Card[] { card }, game, source, value);
}
public static async Task damage(this IEnumerable<Card> cards, THHGame game, Card source, int value)
{
await game.triggers.doEvent(new DamageEventArg() { cards = cards.ToArray(), source = source, value = value }, arg =>
{
cards = arg.cards;
source = arg.source;
value = arg.value;
if (source != null && source.isStealth())
source.setStealth(false);
foreach (Card card in arg.cards)
{
if (card.isShield())
{
card.setShield(false);
arg.infoDic.Add(card, new DamageEventArg.Info()
{
damagedValue = 0,
currentLife = card.getCurrentLife()
});
game.logger.log(card + "受到伤害,失去圣盾");
}
else
{
card.setCurrentLife(card.getCurrentLife() - arg.value);
arg.infoDic.Add(card, new DamageEventArg.Info()
{
damagedValue = value,
currentLife = card.getCurrentLife()
});
game.logger.log(card + "受到" + arg.value + "点伤害,生命值=>" + card.getCurrentLife());
}
}
return Task.CompletedTask;
});
}
public class DamageEventArg : EventArg
{
public Card[] cards;
public Card source;
public int value;
public Dictionary<Card, Info> infoDic = new Dictionary<Card, Info>();
public class Info
{
public int damagedValue;
public int currentLife;
}
}
public static async Task heal(this IEnumerable<Card> cards, THHGame game, int value)
{
cards = cards.Where(c => c.getCurrentLife() < c.getLife());
if (cards.Count() < 1)
return;
await game.triggers.doEvent(new HealEventArg() { cards = cards.ToArray(), value = value }, arg =>
{
cards = arg.cards;
value = arg.value;
foreach (Card card in cards)
{
if (card.getCurrentLife() + value < card.getLife())
{
card.setCurrentLife(card.getCurrentLife() + value);
arg.infoDic.Add(card, new HealEventArg.Info()
{
healedValue = value
});
game.logger.log(card + "恢复" + value + "点生命值,生命值=>" + card.getCurrentLife());
}
else
{
int healedValue = card.getLife() - card.getCurrentLife();
card.setCurrentLife(card.getLife());
arg.infoDic.Add(card, new HealEventArg.Info()
{
healedValue = healedValue
});
game.logger.log(card + "恢复" + healedValue + "点生命值,生命值=>" + card.getCurrentLife());
}
}
return Task.CompletedTask;
});
}
public static async Task heal(this Card card, THHGame game, int value)
{
await heal(new Card[] { card }, game, value);
}
public class HealEventArg : EventArg
{
public Card[] cards;
public int value;
public Dictionary<Card, Info> infoDic = new Dictionary<Card, Info>();
public class Info
{
public int healedValue;
}
}
public static Task die(this Card card, THHGame game, DeathEventArg.Info info)
{
return die(new Card[] { card }, game, new Dictionary<Card, DeathEventArg.Info>() { { card, info } });
}
public static async Task die(this IEnumerable<Card> cards, THHGame game, Dictionary<Card, DeathEventArg.Info> infoDic)
{
List<THHPlayer> remainPlayerList = new List<THHPlayer>(game.players);
await game.triggers.doEvent(new DeathEventArg() { infoDic = infoDic }, arg =>
{
infoDic = arg.infoDic;
foreach (var pair in infoDic)
{
Card card = pair.Key;
if (!game.players.Any(p => p.field.Contains(card) || p.master == card))
continue;
THHPlayer player = game.players.FirstOrDefault(p => p.master == card);
if (player != null)
{
remainPlayerList.Remove(player);
game.logger.log(player + "失败");
}
else
{
pair.Value.player.field.moveTo(game, card, pair.Value.player.grave);
game.logger.log(card + "阵亡");
}
}
return Task.CompletedTask;
});
if (remainPlayerList.Count != game.players.Length)
{
if (remainPlayerList.Count > 0)
await game.gameEnd(remainPlayerList.ToArray());
else
await game.gameEnd(new THHPlayer[0]);
}
}
public class DeathEventArg : EventArg
{
public Dictionary<Card, Info> infoDic = new Dictionary<Card, Info>();
public class Info
{
public THHPlayer player;
public Card card;
public int position;
}
}
public static Card[] getNearbyCards(this Card card)
{
if (card.pile == null || card.pile.count < 2)
return new Card[0];
int index = card.pile.indexOf(card);
if (index == 0 && card.pile.count > 1)
return new Card[] { card.pile[1] };
if (index == card.pile.count - 1 && card.pile.count > 1)
return new Card[] { card.pile[card.pile.count - 2] };
return new Card[] { card.pile[index - 1], card.pile[index + 1] };
}
}
} |
Python | UTF-8 | 2,193 | 2.734375 | 3 | [] | no_license | import easygui as g
import urllib.request
import urllib.error
import re
from urllib import parse
import socket
from bs4 import BeautifulSoup
import cloudscraper
titles = "快来搜搜 V1.2\t 作者:Henry Xue\t 邮箱:kidfullystar@gmail.com"
def open_url(url):
scraper = cloudscraper.create_scraper()
resp = scraper.get(url).text
html = BeautifulSoup(resp, "lxml")
return html
def get_magnet(html):
p = r'<a href="(magnet:\?xt=urn:btih:[^"]+)'
name = r'<td class="name">([^<]+)'
size = r'<td class="size">([^<]+)'
date = r'<td class="date">([^<]+)'
content = ['ETH 地址:0x00011D3a9091F8e317f1ff3d5DcEEf5dEf77a661\n','欢迎打赏!\n']
result = re.findall(p,str(html))
result_name = re.findall(name,str(html))
result_size = re.findall(size, str(html))
result_date = re.findall(date, str(html))
for num, c in enumerate(result):
content.append('\n%d. 资源名:%s 种子大小:%s 资源时间:%s\n下载链接:\n%s\n' % (num + 1,result_name[num],result_size[num],result_date[num],c))
return content,result_name
if __name__ == '__main__':
while 1:
words = g.enterbox(msg='请输入关键词(多个关键词请用空格分开): ',title="快来搜搜 V1.2\t 作者:Henry Xue ")
if words == None :
exit(1)
url = r'https://torkitty.com/search/' + parse.quote(words)+ '//'
try:
content,result_name = get_magnet(open_url(url))
if result_name[0] == 0:
raise IndexError
g.textbox(msg="您查询的关键词对应的下载链接如下(请将下载链接用Ctrl+C粘贴至下载软件进行下载,容量为种子大小,非文件大小):", title=titles, text=content)
except (socket.timeout,urllib.error.URLError,IndexError):
g.textbox(msg='错误信息',title=titles, text='您输入的关键词无法找到资源,请尝试其它关键词,谢谢!')
choices = g.ccbox(msg='是否需要继续查找',choices=('是','否'),title="快来搜搜 V1.2\t 作者:Henry Xue ")
if choices: pass
else:
break
|
Java | UTF-8 | 1,776 | 3.203125 | 3 | [] | no_license | package hotel;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Room {
private String name;
private int capacity;
private ObservableList<Event> events;
public Room() { events = FXCollections.observableArrayList(); }
public String getName() { return name; }
public boolean allowsEvent(Event newEvent) {
if(newEvent.getGroupSize() > capacity)
return false;
for(Event e : events) {
if(e.compareTo(newEvent) == 0)
return false;
}
return true;
}
public void addEvent(Event newEvent) {
events.add(newEvent);
FXCollections.sort(events);
}
public void removeEvent(Event toRemove) {
events.remove(toRemove);
}
public void readFrom(Scanner input) {
// Read the room details and events from the file
name = input.next() + input.nextLine();
capacity = input.nextInt();
int howManyEvents = input.nextInt();
for(int n = 0;n < howManyEvents;n++) {
Event nextEvent = new Event();
nextEvent.readFrom(input);
events.add(nextEvent);
}
FXCollections.sort(events);
}
public void writeTo(PrintWriter output) {
output.println(name);
output.println(capacity);
int howManyEvents = events.size();
output.println(howManyEvents);
for(int n = 0;n < howManyEvents;n++)
events.get(n).writeTo(output);
}
public ObservableList<Event> getEvents() { return events; }
}
|
Python | UTF-8 | 2,105 | 3.234375 | 3 | [] | no_license | from collections import deque
class MaxQueue:
def __init__(self):
self.p = list()
self.q = list()
pass
def __len__(self):
return len(self.p) + len(self.q)
def __add__(self, other):
return self.enqueue(other)
def enqueue(self, other):
min_val = other if len(self.p) == 0 else max(other, self.p[-1][1])
self.p.append((other, min_val))
def dequeue(self):
if len(self.q) == 0:
while len(self.p) > 0:
item = self.p.pop()[0]
min_val = item if len(self.q) == 0 else max(item, self.q[-1][1])
self.q.append((item, min_val))
if len(self.q) > 0:
return self.q.pop()[0]
def max(self):
if len(self) == 0:
return None
if len(self.p) == 0:
return self.q[-1][1]
elif len(self.q) == 0:
return self.p[-1][1]
else:
return max(self.p[-1][1], self.q[-1][1])
class MaxWindowedQueue(MaxQueue):
def __init__(self, wnd_size):
super().__init__()
self.wnd_size = wnd_size
def enqueue(self, other):
super().enqueue(other)
if len(self) > self.wnd_size:
return super().dequeue()
def max_of_window(A, wnd):
mwq = MaxWindowedQueue(wnd)
ret = list()
mwq.enqueue(0)
for elm in A:
mwq.enqueue(elm)
ret.append(mwq.max())
last_max = mwq.max()
for _ in range(wnd - 1):
mwq.enqueue(0)
if len(mwq) > 1:
last_max = mwq.max()
ret.append(last_max)
return ret
def main():
n, w = map(int, input().split())
A = [0] * w
for _ in range(n):
arr = deque(map(int, input().split()))
wnd = w - arr.popleft() + 1
if wnd > 1:
# lr
max_suffix = max_of_window(arr, wnd)
for i in range(w):
A[i] += max_suffix[i]
else:
for i in range(w):
A[i] += arr[i]
print(*A)
import sys
input = sys.stdin.readline
if __name__ == "__main__":
main() |
Java | ISO-8859-1 | 5,690 | 2.25 | 2 | [] | no_license | package com.example.domotique;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.utils.JSONParser;
import com.example.utils.User;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Params extends Activity {
//Dclaration
EditText mail,mdp;
Button confirm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (verify())
{
Intent intent= new Intent(Params.this,Maison.class);
startActivity(intent);
}
setContentView(R.layout.activity_params);
mail=(EditText) findViewById(R.id.editText4);
mdp=(EditText) findViewById(R.id.editText2);
confirm=(Button) findViewById(R.id.button1);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Rcuprer les texte des zones
String smail=mail.getText().toString();
String smdp=mdp.getText().toString();
Log.d("textinput", smail);
//Instance de la classe Settings :Cration des donnes dans l'XML
new Settings(Params.this).createSettings(smail, smdp);
Toast.makeText(Params.this, "Success", Toast.LENGTH_LONG).show();
Log.d("ConnectTask", "ConnectTask");
if(isOnline())
{
new ConnectTask().execute();
}
else
{
Toast.makeText(Params.this, "Connection Failed", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean verify()
{
if(new Settings(Params.this).getID().equals("0"))
return false;
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.params, menu);
return true;
}
//Connection au serveur
public class ConnectTask extends AsyncTask<String, String, String>
{
private ProgressDialog pDialog;
private Settings config;
private String msg;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pDialog=new ProgressDialog(Params.this);
pDialog.setMessage("Loading.. Please Wait ");
pDialog.show();
Log.d("loding","I am here");
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONParser jParse =new JSONParser();
config=new Settings(Params.this);
//Une liste parames contenant deux types de paramtres
ArrayList<NameValuePair> parames=new ArrayList<NameValuePair>();
parames.add(new BasicNameValuePair("mail", config.getMail()));
parames.add(new BasicNameValuePair("mdp", config.getMdp()));
Log.d("jsonparser","jsonparser");
//Log.d("Mail", config.getMail());
Log.d("jsonparser",parames.get(0).toString());
Log.d("jsonparser",parames.get(1).toString());
JSONObject json =jParse.makeHttpRequest(new Settings(Params.this).getHost()+"/Domotique/Param.php", "GET", parames);
Log.d("Status", json.toString());
Log.e("Status", json.toString());
Log.i("Status", json.toString());
try {
int success=json.getInt("success");
if (success==1)
{
//Test sur le cas success : je vais stock l'ID et je retourne success
String id=json.getString("id");
String nom_user=json.getString("nom_user");
String prenom_user=json.getString("prenom_user");
String tel_user=json.getString("tel_user");
String date_naissance_user=json.getString("date_naissance_user");
String pic_user=json.getString("pic_user");
new Settings(Params.this).setId(id);
new Settings(Params.this).setnom_user(nom_user);
new Settings(Params.this).setprenom_user(prenom_user);
new Settings(Params.this).settel_user(tel_user);
new Settings(Params.this).setdate_naissance_user(date_naissance_user);
new Settings(Params.this).setpic_user(pic_user);
Log.d("picture", config.getPic_user());
User u=new User(id, nom_user, prenom_user, date_naissance_user, pic_user);
return "success";
}else
{
//Test sur le cas fail
return "fail";
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pDialog.dismiss();
if (result.equals("fail"))
{
Toast.makeText(Params.this, msg, Toast.LENGTH_LONG).show();
}
if (result.equals("success"))
{
Toast.makeText(Params.this, msg, Toast.LENGTH_LONG).show();
Intent intent= new Intent(Params.this,Maison.class);
startActivity(intent);
}
super.onPostExecute(result);
}
}
}
|
C# | UTF-8 | 1,235 | 2.6875 | 3 | [
"MIT"
] | permissive | using System.Text;
using System.Xml.Linq;
namespace PListFormatter
{
public class PListDataElement : PListElement
{
public PListDataElement(string key, object value)
: base(key, "data", value)
{ }
public PListDataElement(object value)
{
this.value = value;
}
internal override void AppendToXml(XElement parentElement)
{
AddKeyElement(parentElement);
XElement valueElement = null;
if (value as string != null)
{
byte[] asciiString = Encoding.ASCII.GetBytes((string)value);
string elementValue = this.Encode ? System.Convert.ToBase64String(asciiString) : (string)value;
valueElement = new XElement("data", elementValue);
}
else
{
string asciiString = Encoding.ASCII.GetString((byte[])value);
string elementValue = this.Encode ? System.Convert.ToBase64String((byte[])value) : asciiString;
valueElement = new XElement("data", elementValue);
}
parentElement.Add(valueElement);
}
public bool Encode { get; set; }
}
}
|
Markdown | UTF-8 | 1,043 | 2.6875 | 3 | [
"MIT"
] | permissive | # @nearform/trail-hapi-plugin
[![npm][npm-badge]][npm-url]
trail-hapi-plugin is a plugin to add the trail REST API to a [Hapi][hapi] server.
## Install
To install via npm:
```
npm install @nearform/trail-hapi-plugin
```
## Usage
```javascript
const main = async function() {
const server = require('hapi').Server({host: 'localhost', port: 80})
await server.register([
{
plugin: require('@nearform/trail-hapi-plugin'),
}
])
await server.start()
logMessage(`Server running at: ${server.info.uri}`)
}
main().catch(console.error)
```
Trails route will be then accessible on the `/trails` path.
For more information on the REST API, you can check the generated OpenAPI / Swagger JSON file, which will available at the `/trails/swagger.json` path.
## License
Copyright nearForm Ltd 2018. Licensed under [MIT][license].
[npm-url]: https://npmjs.org/package/@nearform/trail-hapi-plugin
[npm-badge]: https://img.shields.io/npm/v/@nearform/trail-hapi-plugin.svg
[hapi]: https://hapijs.com/
[license]: ./LICENSE.md
|
JavaScript | UTF-8 | 2,536 | 2.515625 | 3 | [] | no_license | import React from 'react';
import { Form, FormGroup, Input, Row, Col} from 'reactstrap';
import PregnancyvitalsBloodsugar from './AddBloodsugar';
import PregnancyvitalsThroid from './AddThyroid'
import PregnancyvitalsBloodpressure from './AddBloodpresssure'
// const desease = ["thyroid", "bloodPressure", "bloodSugar"]
class AddPregnancyvitals extends React.Component {
state = {
deseaseType: "Thyroid"
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleForm = deseaseType => {
if (deseaseType === "Thyroid") {
return <PregnancyvitalsThroid deseaseType={this.state.deseaseType} />;
}
if (deseaseType === "Blood Sugar") {
return <PregnancyvitalsBloodsugar deseaseType={this.state.deseaseType} />;
}
if (deseaseType === "Blood Pressure") {
return (
<PregnancyvitalsBloodpressure deseaseType={this.state.deseaseType} />
);
}
};
// handleClick = (data, files) =>{
// console.log(data)
// if(data=== null || files===undefined){
// return false
// }
// const formdata = new FormData();
// for(let key in data){
// formdata.append(key,data[key])
// }
// formdata.append("deseaseType", this.state.deseaseType)
// for(let i=0; i<files.length; i++){
// formdata.append(files[i])
// }
// const config = {
// headers: {
// 'Content-Type': 'multipart/form-data'
// }
// };
// Axios.post(baseURL+`users/thyroid`, config, formdata)
// .then((res)=>{
// console.log(res)
// }).catch((err)=>{
// console.log(err)
// })
// }
render() {
const { deseaseType } = this.state;
return (
<div>
<Form>
<Row className="mt-3">
<Col xs="12" className="col-md-4">
<FormGroup>
<Input
type="select"
name="deseaseType"
onChange={this.handleChange}
>
<option>Thyroid</option>
<option>Blood Sugar</option>
<option>Blood Pressure</option>
</Input>
</FormGroup>
</Col>
</Row>
</Form>
{this.handleForm(deseaseType)}
</div>
);
}
}
export default AddPregnancyvitals;
|
JavaScript | UTF-8 | 383 | 3.125 | 3 | [] | no_license | "use strict";
const salary = 7500;
const friendSalaries = [7500, 12300, 17200, 9400, 8400];
const friends = ['sakib', 'tamim', 'musfiq', 'nokib'];
// friendSalaries[0] = 10500;
// friendSalaries.push(10700);
friends.push('akib');
friends[2] = ('akib');
// friends.push(34000);
let max = 0;
for (const salary of friendSalaries) {
if (salary > max) {
max = salary;
}
}
|
Markdown | UTF-8 | 767 | 2.53125 | 3 | [] | no_license | ---
title : Week 2 of Art-A-Hack 2015
image : /images/og/2015-week-2.jpg
---
The pressure was on for our second week as teams delved into their individual and group projects together.
<figure class="video">
<iframe src="https://www.flickr.com/photos/125924023@N07/19059208352/in/set-72157654525286918/player/" allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>
</figure>
Collaborations, breakthroughs and excitement, as well as exasperation, frustration and general angst came to pass. Yet, by the end of the day, the teams rallied ready to tackle another week of hard work.
<!--excerpt-ends-->
This pattern is typical at this stage of intensive collaborations, with ground to be discovered in the coming weeks. |
Python | UTF-8 | 4,945 | 2.6875 | 3 | [] | no_license | import urllib3
import json
import traceback
import os
'''
原始URL
http://www.nmgtj.gov.cn/acmrdatashownmgpub/tablequery.htm?
m=QueryData&code=OA0C&wds=[{"wdcode":"reg","valuecode":"150000"},{"wdcode":"sj","valuecode":"201804"}]&fvrt_code=
'''
#通过控制,data_name,code,time 三个参数获取内蒙古地区的数据
def get_data(data_name,code,date_list,path):
ori_path = path+'/'+'原始数据'
data_path = path+'/'+'解析数据'
try:
os.mkdir(path+'/'+'原始数据')
except:
pass
try:
os.mkdir(path + '/' + '解析数据')
except:
pass
#----------------原始参数--------------------
url='http://www.nmgtj.gov.cn/acmrdatashownmgpub/tablequery.htm'
#data_name = '工业经济效率'
#code = 'OA0104'
wdcode1='reg'
valuecode1='150000'
wdcode2='sj'
valuecode2='201804' #日期?
#-----------------------------------
data_list=[]# 储存数据流
try:
os.mkdir(ori_path+'/'+data_name)
except:
#目录存在
pass
for valuecode2 in date_list:
#参数
wds2=[{"wdcode":"{}".format(wdcode1),"valuecode":"{}".format(valuecode1)},{"wdcode":"{}".format(wdcode2),'valuecode':'{}'.format(valuecode2)}]
url_parmas={"m":"QueryData","code":"{}".format(code),"wds":"{}".format(str(wds2).replace('\'','\"')),"fvrt_code":""}
try:
#http请求
http=urllib3.PoolManager()
r=http.request("GET",url,fields=url_parmas)
#数据加载
hs=json.loads(r.data)
file_name=ori_path+'/'+data_name+'/'+str(valuecode2)+".json"
#原始数据保存
with open(file_name,"w") as f :
json.dump(hs,f,ensure_ascii=False)
#print(data_name,' : ',valuecode2,"原始json数据保存成功")
print('正在下载: 内蒙古 {} {} 原始数据'.format(valuecode2,data_name))
#数据解析
b=hs['exceltable']
ll=[] #用来记录属性值。
data=[]
temp={}
for a in b : # a即为单个字典
if(a['sort']=='row'):
temp={}
if(a['sort']=='col'):
ll.append(a['data'])
elif(a['sort']=='row' or a['sort']=='cell'):
temp["{}".format(ll[a['col']])]=a['data']
if(a['col']==len(ll)-1):
temp['time']=str(valuecode2)
data.append(temp)
else:
print('error : ',a['sort'],a['col'])
print('----------------')
data_list.append(data)
except:
print("内蒙古地区,原始数据 {} 出错!".format(data_name))
#traceback.print_exc(file=open("Exc.txt","a"))
continue
#解析后总数据保存
file_nn="{}.json".format(data_path+'/'+date_list[0][:4]+data_name)
print(file_nn)
with open(file=file_nn,mode='w') as f:
json.dump(data_list, f,ensure_ascii=False)
print('内蒙古 {} {} 数据 解析成功!'.format(valuecode2, data_name))
def get_neimenggu(year,path):
try:
a=int(year)
except:
print("内蒙古地区 目标年鉴 {} 时间格式错误!".format(year))
return 0
if int(year)<=2016 and int(year)>=2000:
try:
os.mkdir(path+'/'+'内蒙古')
except:
pass
path=path+'/'+'内蒙古'
try:
os.mkdir(path + '/' + '{}'.format(year))
except:
pass
path = path + '/' + '{}'.format(year)
list = [{'工业增加值增长速度': 'OA0101'},
{'工业产品销售率': 'OA0102'},
{'主要工业产品产量': 'OA0103'},
{'工业经济效率': 'OA0104'},
{'固定投资资产': 'OA0505'},
{'主要行业固定投资资产': 'OA0506'},
{'房地产开发': 'OA0507'},
{'社会消费品零售总额': 'OA08'},
{'对外经济': 'OA09'},
{'财政': 'OA0A'},
{'金融': 'OA0C'},
{'全区及全国主要经济指标': 'OA1F'}
]
t_list = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
time_list=[]
for num in t_list:
time_list.append("{}{}".format(str(year),num))
for a in list:
# 读取list里的字典的第一个键值对
for key, value in a.items():
#print("data_name: {},code : {}".format(key, value))
get_data(key, value, time_list,path=path)
break
else:
print("内蒙古地区目标年限 {} 超出可抓取范围!".format(year))
if __name__ == '__main__':
get_neimenggu('2001',"F:/ec")
|
Java | UTF-8 | 1,768 | 1.71875 | 2 | [] | no_license | /*
* Copyright (C) 2010 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wikbook.core.xml;
/**
* @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
* @version $Revision$
*/
public class OutputFormat
{
/** . */
private final Integer indent;
/** . */
private final boolean emitDoctype;
/** . */
private final String publicId;
/** . */
private final String systemId;
public OutputFormat(Integer indent, boolean emitDoctype)
{
this(indent, emitDoctype, null, null);
}
public OutputFormat(Integer indent, boolean emitDoctype, String publicId, String systemId)
{
this.indent = indent;
this.emitDoctype = emitDoctype;
this.publicId = publicId;
this.systemId = systemId;
}
public Integer getIndent()
{
return indent;
}
public boolean isEmitDoctype()
{
return emitDoctype;
}
public String getPublicId()
{
return publicId;
}
public String getSystemId()
{
return systemId;
}
}
|
C++ | UTF-8 | 380 | 2.875 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "MemCalculator.h"
// Factory
static MemCalculator MakeCalc()
{
return MemCalculator();
}
TEST( Sum, DefualtReturnZero )
{
MemCalculator calc;
int lastSum = calc.doSum();
EXPECT_EQ( 0, lastSum );
}
TEST( Sum, AddReturnChange )
{
MemCalculator calc = MakeCalc();
calc.doAdd( 1 );
int lastSum = calc.doSum();
EXPECT_EQ( 1, lastSum );
}
|
C++ | UTF-8 | 855 | 2.953125 | 3 | [] | no_license | #include <avr/delay.h>
#include "AVRPortPin.h"
#define TRUE ((uint8_t)1)
#define FALSE ((uint8_t)0)
AVRPortPin::AVRPortPin(volatile uint8_t *ddr, volatile uint8_t *port, volatile uint8_t *inPort, uint8_t pin)
:_ddr(ddr),_port(port),_inPort(inPort), _pinMask(_BV(pin)), _pin(pin) {
}
AVRPortPin::~AVRPortPin(){
}
void AVRPortPin::setAsOutput(){
*_ddr |= _pinMask;
}
void AVRPortPin::setAsInput(){
*_ddr &= ~_pinMask;
}
void AVRPortPin::set(){
*_port |= _pinMask;
}
void AVRPortPin::set(uint8_t val){
val <<= _pin;
*_port = val;
}
void AVRPortPin::clear(){
*_port &= ~_pinMask;
}
uint8_t AVRPortPin::read(){
return (*_inPort & _pinMask)?TRUE:FALSE;
}
void AVRPortPin::toggle(){
*_inPort |= _pinMask;
}
void AVRPortPin::pulse(uint16_t millis) {
toggle();
for(uint16_t count =0;count <millis;count++) {
_delay_us(1);
}
toggle();
} |
C++ | UTF-8 | 3,063 | 2.78125 | 3 | [] | no_license | #pragma once
#include <type_traits>
#include "Array.h"
#include "GameObject.h"
#include "Logger.h"
#include "SceneComponent.h"
namespace Noble
{
typedef MemoryArena<BlockAllocator, DefaultTracking> GameMemoryArena;
class Controller;
/**
* The World class encompasses a "map" or area of play.
* Worlds hold all of the currently spawned GameObjects.
*/
class World
{
public:
friend class GameObject;
// Renderer is friend to access list of SceneComponents
friend class Renderer;
World();
/**
* Spawns a new GameObject of the specified type
* Optionally takes a location at which to spawn the GameObject
*/
template <typename T>
T* SpawnGameObject(Vector3f spawnPos = Vector3f(0.0F))
{
T* object = (T*)BuildGameObject(T::GetStaticClass());
object->OnSpawn();
object->SetPosition(spawnPos);
return object;
}
/**
* Spawns a new GameObject of the specified type
* Optionally takes a location at which to spawn the GameObject
*/
GameObject* SpawnGameObject(NClass* type, Vector3f spawnPos = Vector3f(0.0F));
/**
* Creates a new Component that is part of the given GameObject
*/
template <typename T>
T* CreateComponent(GameObject* owner, const NIdentifier& name)
{
CHECK(owner);
T* comp = (T*)BuildComponent(T::GetStaticClass());
comp->SetOwningObject(owner);
comp->SetComponentName(name);
owner->AddComponent(comp);
return comp;
}
/**
* Creates a new Component that is part of the given GameObject
*/
Component* CreateComponent(NClass* type, GameObject* owner, const NIdentifier& name);
/**
* Creates a new Controller of the requested type
*
*/
template <typename T>
T* CreateController()
{
T* controller = (T*)BuildController(T::GetStaticClass());
return controller;
}
/**
* Creates a new Controller of the requested type
*/
Controller* CreateController(NClass* type);
/**
* Called each frame - runs logic updates on all spawned GameObjects and Components
* The ordering is to call update on a GameObject, then on all of its Components immediately after
*/
void Update();
/**
* Called at a fixed rate - runs logic updates on all spawned GameObjects and Components
* The ordering is to call update on a GameObject, then on all of its Components immediately after
*/
void FixedUpdate();
private:
/**
* Internal code to create a game object from an NClass
*/
GameObject* BuildGameObject(NClass* type);
/**
* Internal code to create a component from an NClass
*/
Component* BuildComponent(NClass* type);
/**
* Internal code to create a controller from an NClass
*/
Controller* BuildController(NClass* type);
private:
// Memory Arena for GameObjects + Components
GameMemoryArena m_GameMemory;
// Array of all currently spawned GameObjects
Array<GameObject*> m_GameObjects;
// Array of all renderable Components in the game
Array<SceneComponent*> m_SceneComponents;
// Array of Controllers
Array<Controller*> m_Controllers;
};
} |
Swift | UTF-8 | 981 | 2.984375 | 3 | [] | no_license | //
// ViewController.swift
// Destini-iOS13
//
// Created by Angela Yu on 08/08/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var storyLabel: UILabel!
@IBOutlet weak var choice1Button: UIButton!
@IBOutlet weak var choice2Button: UIButton!
var storyBrain = StoryBrain()
override func viewDidLoad() {
super.viewDidLoad()
load()
}
@IBAction func choice1Pressed(_ sender: UIButton) {
storyBrain.setNextStory(choice: 1)
load()
}
@IBAction func choice2Pressed(_ sender: UIButton) {
storyBrain.setNextStory(choice: 2)
load()
}
func load() {
storyLabel.text = storyBrain.getStory()
choice1Button.setTitle(storyBrain.getChoices()[0], for: UIControl.State.normal)
choice2Button.setTitle(storyBrain.getChoices()[1], for: UIControl.State.normal)
}
}
|
PHP | UTF-8 | 3,231 | 2.75 | 3 | [] | no_license | <?php
namespace Fruitware\GabrielApi\Model;
interface SearchInterface
{
const LANG_RU = 'ru';
const LANG_RO = 'ro';
const LANG_EN = 'en';
const TYPE_ONE_WAY = 'oneway';
const TYPE_ROUND_TRIP = 'roundtrip';
const MAX_PASSENGERS_NUMBER = 9;
/**
* Set language ru|en|ro
*
* @param string $lang
*
* @return $this
*/
public function setLang($lang);
/**
* @return string
*/
public function getLang();
/**
* Set type
*
* @param string $type
*
* @return $this
*/
public function setType($type);
/**
* @return string
*/
public function getType();
/**
* @return array
*/
static public function getTypes();
/**
* Set departure airport/city
*
* @param string $departureAirport
*
* @return $this
*/
public function setDepartureAirport($departureAirport);
/**
* @return string
*/
public function getDepartureAirport();
/**
* Set arrival airport/city
*
* @param string $arrivalAirport
*
* @return $this
*/
public function setArrivalAirport($arrivalAirport);
/**
* @return string
*/
public function getArrivalAirport();
/**
* Set departure date
*
* @param \DateTime $departureDate
*
* @return $this
*/
public function setDepartureDate(\DateTime $departureDate);
/**
* @return \DateTime
*/
public function getDepartureDate();
/**
* Set return date
*
* @param \DateTime $returnDate
*
* @return $this
*/
public function setReturnDate(\DateTime $returnDate = null);
/**
* @return \DateTime
*/
public function getReturnDate();
/**
* Set number of adults
*
* @param int $adults
*
* @return $this
*/
public function setAdults($adults);
/**
* @return int
*/
public function getAdults();
/**
* Set number of children (2 -12 years)
*
* @param int $children
*
* @return $this
*/
public function setChildren($children);
/**
* @return int
*/
public function getChildren();
/**
* Set number of infants (under 2 years)
*
* @param int $infants
*
* @return $this
*/
public function setInfants($infants);
/**
* @return int
*/
public function getInfants();
/**
* Set search identifier – ability to have more than one active searches
*
* @param int $searchOption
*
* @return $this
*/
public function setSearchOption($searchOption);
/**
* @return int
*/
public function getSearchOption();
/**
* Ignore cached data of available segments. Default is false
* @param bool $directSearch
*
* @return $this
*/
public function setDirectSearch($directSearch);
/**
* @return bool
*/
public function getDirectSearch();
/**
* @return bool
*/
public function hasAllowedNumberOfPassengers();
/**
* @return bool
*/
public function hasAllowedNumberOfInfants();
} |
Shell | UTF-8 | 679 | 3.421875 | 3 | [
"MIT"
] | permissive | #!/bin/bash
# disableGuestAccount.sh
# disable the macOS guest account
# Last Edited: 6/19/18 Julian Thies
if [ "$(whoami)" != "root" ] ; then
echo "This script must be run as root or with sudo privileges"
exit
else
if [ -e "/Users/Guest" ] ; then
# use dscl to delete the account
dscl . -delete /Users/Guest
# write to the login window plist to disable Guest
defaults write /Library/Preferences/com.apple.loginwindow GuestEnabled -bool NO
# write to the file server plists
defaults write /Library/Preferences/com.apple.AppleFileServer guestAccess -bool NO
defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server AllowGuestAccess -bool NO
fi
fi
|
Java | UTF-8 | 454 | 2.25 | 2 | [] | no_license | import Domain.PersonValidator;
import Repository.PersonRepository;
import Service.PersonService;
import UI.Console;
public class Main {
public static void main(String[] args) {
PersonValidator validator= new PersonValidator();
PersonRepository repository = new PersonRepository(validator);
PersonService service = new PersonService(repository);
Console console = new Console(service);
console.run();
}
}
|
Python | UTF-8 | 599 | 3.015625 | 3 | [] | no_license | import re
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_phone_number(phone_number):
phone_number = phone_number.strip()
if re.search('^[^0-9+-/]{17}$', phone_number):
raise ValidationError(
_('Phone number must not contain letters!'))
def validate_gte(value, validator, value_name_1, value_name_2=None):
if value < validator:
raise ValidationError(
_(f'{value_name_1} has to be equal to or greater '
f'than {value_name_2}')
)
|
JavaScript | UTF-8 | 1,234 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /**
* ------------------------------------------------- CATALOG TEST -------------------------------------------
*
*/
function TestWindow() {
var win = Ti.UI.createWindow({
title : 'Prueba SCROLLVIEW',
backgroundColor : 'white'
});
var scrollView = Ti.UI.createScrollView({
contentWidth : 'auto',
contentHeight : '16.66%',
height : '16.66%',
width : Ti.UI.FILL,
top : 20
});
var view = Ti.UI.createView({
backgroundColor : '#336699',
width : Ti.UI.SIZE,
height : Ti.UI.FILL,
layout : 'horizontal'
});
var button = Ti.UI.createButton({
title : "Add numbers",
width : Ti.UI.FILL,
top : 200
});
button.addEventListener('click', function() {
var end = 3;
for (var i = 0; i < end; i++) {
view.add(Ti.UI.createLabel({
color : '#FFFFFF',
font : {
fontSize : 50
},
width : Ti.UI.SIZE,
text : i
}));
};
});
scrollView.add(view);
win.add(scrollView);
win.add(button);
return win;
};
module.exports = TestWindow();
|
Markdown | UTF-8 | 1,393 | 2.546875 | 3 | [
"MIT"
] | permissive | ---
page_type: sample
languages:
- csharp
products:
- azure
- azure-hdinsight
name: Azure HDInsight SDK for .NET Samples
urlFragment: azure-hdinsight-sdk-for-dotnet-samples
description: "This repo provides samples for the Azure HDInsight SDK for .NET."
---
# Azure HDInsight SDK for .NET Samples
This repo provides samples for the Azure [HDInsight](https://azure.microsoft.com/services/hdinsight/) SDK for .NET NuGet Packages.
## Features
C# samples showing the use of the Azure HDInsight SDK for .NET NuGet packages. The idea behind these samples is to showcase 1) how to utilize the Azure HDInsight SDK for .NET and 2) best practices for handling data associated with these APIs.
## Getting Started
If you are getting started with the Azure HDInsight SDK for .NET for the first time, start with [this documentation](https://docs.microsoft.com/dotnet/api/overview/azure/hdinsight?view=azure-dotnet) for install and setup instructions.
## Resources
- [Azure HDInsight SDK for .NET documentation](https://docs.microsoft.com/dotnet/api/overview/azure/hdinsight?view=azure-dotnet)
- [Azure HDInsight Python samples](https://github.com/Azure-Samples/hdinsight-python-sdk-samples)
- [Azure HDInsight Java samples](https://github.com/Azure-Samples/hdinsight-java-sdk-samples)
- [Azure HDInsight Documentation](https://docs.microsoft.com/azure/hdinsight/)
|
Python | UTF-8 | 2,040 | 3.453125 | 3 | [
"MIT"
] | permissive | from dataclasses import dataclass,field
import csv
from typing import List
@dataclass
class Product:
name: str
price: float =0.0
@dataclass
class ProductStock:
product: Product
quantity: int
@dataclass
class Shop:
cash: float =0.0
stock: List[ProductStock] = field(default_factory=list)
@dataclass
class Customer:
name: str
budget: float
shopping_list: List[ProductStock] = field(default_factory=list)
def create_and_stock_shop():
s= Shop()
with open("../stock.csv") as csv_file:
csv_reader= csv.reader(csv_file, delimiter=',')
line_count=0
first_row= next(csv_reader)
s.cash=float(first_row[0])
for row in csv_reader:
p= Product(row[0],float(row[1]))
ps= ProductStock(p,float(row[2]))
s.stock.append(ps)
#print(ps)
return s
def read_customer(file_path):
with open(file_path) as csv_file:
csv_reader= csv.reader(csv_file, delimiter=',')
first_row= next(csv_reader)
c = Customer(first_row[0], float(first_row[1]))
print(c)
for row in csv_reader:
name=row[0]
quantity = float(row[1])
p=Product(name)
ps=ProductStock(p,quantity)
c.shopping_list.append(ps)
return c
def print_product(p):
print(f'\n Product Name: {p.name} \n Product Price:{p.price}')
def print_customer(c):
print(f'\n Customer Name: {c.name} \n Customer Budget:{c.budget}')
for items in c.shopping_list:
print_product(items.product)
print(f'{c.name} Orders {items.quantity} of above product')
cost=items.quantity*items.product.price
print(f'the cost to {c.name} is ${cost}')
def print_shop(s):
print(f'Shop has{s.cash} in cash')
for item in s.stock:
print_product(item.product)
print(f'The item have {item.quantity} in stock' )
p= Product("COke",1.0)
#s=create_and_stock_shop()
#print_shop(s)
c= read_customer("../customer.csv")
print_customer(c) |
Python | UTF-8 | 1,210 | 2.5625 | 3 | [] | no_license | import numpy as np
import time
from copy import copy
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
from control_interfaces.msg import PositionCommand
class SimpleControllerNode(Node):
def __init__(self):
super().__init__('simple_robot_controller')
self._pub = self.create_publisher(PositionCommand, 'command', 10)
self._sub = self.create_subscription(
JointState, 'joint_states', self._callback, 10)
self._t0 = None
self._initial_position = None
def _callback(self, msg):
if self._t0 is None:
self._t0 = time.time()
self._initial_position = copy(msg.position)
command_msg = PositionCommand()
command_msg.command = copy(msg.position)
correction = 0.1 * (np.sin(3.0 * (time.time() - self._t0)))
command_msg.command[0] = self._initial_position[0] + correction
self._pub.publish(command_msg)
def main(args=None):
rclpy.init(args=args)
simple_controller_node = SimpleControllerNode()
rclpy.spin(simple_controller_node)
simple_controller_node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() |
Java | UTF-8 | 1,330 | 3.53125 | 4 | [
"MIT"
] | permissive | package boj11650;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Main {
static class Coordinate implements Comparable<Coordinate> {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Coordinate o) {
int compareValue = this.x - o.x;
if(compareValue == 0) {
return this.y - o.y;
}else {
return compareValue;
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
List<Coordinate> coordinateList = new LinkedList<Coordinate>();
for (int i = 0; i < n; i++) {
String[] input = br.readLine().split(" ");
coordinateList.add(new Coordinate(Integer.parseInt(input[0]),Integer.parseInt(input[1])));
}
Collections.sort(coordinateList);
Iterator<Coordinate> it = coordinateList.iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
Coordinate coordinate = it.next();
sb.append(coordinate.x).append(" ").append(coordinate.y).append("\n");
}
System.out.println(sb);
}
}
|
Python | UTF-8 | 552 | 2.6875 | 3 | [] | no_license | """
This class is used for the SSA version of slithIR
It is similar to the non-SSA version of slithIR
as the TemporaryVariable are in SSA form in both version
"""
from fortress.slithir.variables.temporary import TemporaryVariable
class TemporaryVariableSSA(TemporaryVariable): # pylint: disable=too-few-public-methods
def __init__(self, temporary):
super().__init__(temporary.node, temporary.index)
self._non_ssa_version = temporary
@property
def non_ssa_version(self):
return self._non_ssa_version
|
Python | UTF-8 | 3,110 | 3.125 | 3 | [] | no_license | from ClasePersona import Persona
from ClaseInscripcion import Inscripcion
import numpy as np
from ClaseTallerCapacitacion import TallerCapacitacion
import csv
#talleres = np.empty(3, dtype=TallerCapacitacion)
#print(puntos)
class ManejadorTalleres:
__talleres=None
__i=0
def __init__(self,dimension=5):
self.__talleres= np.empty(dimension, dtype=TallerCapacitacion)
def agregarTaller(self):
archivo = open('talleres.csv')
leer = csv.reader(archivo,delimiter=',')
for fila in leer:
idt=int(fila[0])
nombre=fila[1]
vacante=int(fila[2])
monto=int(fila[3])
unTaller = TallerCapacitacion(idt,nombre,vacante,monto)
self.__talleres[self.__i]=unTaller
self.__i+=1
#print(unTaller)
archivo.close()
def inscrip(self,listaInscripcion):
print("----Datos----")
nombre=input("Ingresar Nombre:")
direccion=input("Ingresar Direccion:")
dni=input("Ingresar DNI:")
unaPersona=Persona(nombre,direccion,dni)
print(unaPersona)
fecha=input("Ingresar Fecha de Inscripcion:")
numeroTaller=int(input("Ingresar Numero de el taller:"))
#SiONo=input("Ingresar si Pago(Si o No):")
pago=False
'''while pago==None:
if SiONo=="si" or SiONo=="Si":
pago=True
print("Hola1")
elif SiONo=="No" or SiONo=="no":
pago=False
print("Hola2")
else:
print("La respuesta dada no es correcta")
SiONo=(input("Pruebe nuevamente"))'''
controlResta=self.restar(numeroTaller)
if controlResta==True:
i=self.validarNum(numeroTaller)
unaInscripcion=Inscripcion(fecha,pago ,unaPersona,self.__talleres[i])
#print(unaInscripcion)
listaInscripcion.agregarInscripcion(unaInscripcion)
else: print("El Numero de taller ha sido ingresado de forma incorrecta")
def restar(self,num):
band=False
i=self.validarNum(num)
if i!=None:
self.__talleres[i].restVacante()
print("Se ha restado el numero de talleres correctamente")
band=True
return band
def validarNum(self,xnum):
i=0
print(xnum)
encontrado=True
while encontrado==True and i<len(self.__talleres):
x=self.__talleres[i].getNumero()
if x==xnum:
encontrado=False
i+=1
if encontrado==False:
i=i-1
return i
def __str__(self):
s=""
for TallerCapacitacion in self.__talleres:
s+=TallerCapacitacion.__str__() + '\n'
return s
def mostrarTalleres(self):
for i in range (len(self.__talleres)):
# self.__talleres[i].mostrarDatos()
print(self.__talleres[i]) |
Python | UTF-8 | 1,193 | 3.359375 | 3 | [] | no_license | #
# @lc app=leetcode.cn id=13 lang=python3
#
# [13] 罗马数字转整数
#
# @lc code=start
class Solution:
def romanToInt(self, s: str) -> int:
d = {'I': 1, 'IV': -1, 'V': 5, 'IX': -1,
'X': 10, 'XL': -10, 'L': 50, 'XC': -10,
'C': 100, 'CD': -100, 'D': 500, 'CM': -100,
'M': 1000}
thesum = 0
for i in range(len(s)):
if s[i:i+2] in d:
thesum += d[s[i:i+2]]
else:
thesum += d[s[i]]
return thesum
def romanToInt(self, s: str) -> int:
d = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000}
isjump = thesum = 0
for i in range(len(s)):
## 判断是否是遍历过的小大组合中的数。
if isjump == s[i]:
continue
twoliteral = s[i:i+2]
## 判断是不是小大组合
if twoliteral in d:
thesum += d[twoliteral]
isjump = twoliteral[-1]
else: ## 只有大
thesum += d[twoliteral[0]]
return thesum
# @lc code=end
|
Java | UTF-8 | 25,656 | 1.875 | 2 | [] | no_license | package priv.starfish.mall.manager.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import priv.starfish.common.annotation.Remark;
import priv.starfish.common.model.*;
import priv.starfish.common.model.Result.Type;
import priv.starfish.common.user.UserContext;
import priv.starfish.common.util.MapContext;
import priv.starfish.common.util.StrUtil;
import priv.starfish.common.util.TypeUtil;
import priv.starfish.mall.comn.dict.AuthScope;
import priv.starfish.mall.comn.entity.Agreement;
import priv.starfish.mall.comn.entity.Permission;
import priv.starfish.mall.comn.entity.Role;
import priv.starfish.mall.comn.entity.User;
import priv.starfish.mall.mall.dto.MallDto;
import priv.starfish.mall.mall.entity.Mall;
import priv.starfish.mall.mall.entity.MallNotice;
import priv.starfish.mall.mall.entity.Operator;
import priv.starfish.mall.web.base.BaseController;
import priv.starfish.mall.service.MallService;
import priv.starfish.mall.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Remark("商城")
@Controller
@RequestMapping(value = "/mall")
public class MallController extends BaseController {
@Resource
MallService mallService;
@Resource
private UserService userService;
// ---------------------------------商城注册页面---------------------------------
/**
* 跳转商城注册页面
*
* @author 王少辉
* @date 2015年5月13日 上午9:45:07
*
* @return 返回页面路径
*/
@Remark("商城注册页面")
@RequestMapping(value = "/regist/jsp", method = RequestMethod.GET)
public String index() {
return "mall/mallRegist";
}
/**
* 跳转商城资金账户
*
* @author 郝江奎
* @date 2015年10月30日 下午13:45:07
*
* @return 返回页面路径
*/
@Remark("商城资金账户页面")
@RequestMapping(value = "/userAccount/jsp", method = RequestMethod.GET)
public String toGetAccount() {
return "mall/mallAccount";
}
/**
* 跳转商城公告
*
* @author 郝江奎
* @date 2015年10月30日 下午13:50:07
*
* @return 返回页面路径
*/
@Remark("商城公告页面")
@RequestMapping(value = "/notice/jsp", method = RequestMethod.GET)
public String toGetNotice() {
return "mall/mallNotice";
}
/**
* 跳转各方协议
*
* @author 郝江奎
* @date 2015年10月30日 下午13:55:07
*
* @return 返回页面路径
*/
@Remark("各方协议页面")
@RequestMapping(value = "/agreement/jsp", method = RequestMethod.GET)
public String toGetAgreement() {
return "mall/mallAgreement";
}
/**
* 获取商城基本信息
*
* @author 王少辉
* @date 2015年5月13日 上午9:45:13
*
* @return 返回商城基本信息
*/
@Remark("获取商城基本信息")
@RequestMapping(value = "/get", method = RequestMethod.POST)
@ResponseBody
public Result<MallDto> getMall(HttpServletRequest request) {
Result<MallDto> result = Result.newOne();
//
MallDto mallDto = mallService.getMallInfo();
result.data = mallDto;
//
return result;
}
/**
* 获取商城协议信息
*
* @author 王少辉
* @date 2015年8月18日 下午1:30:15
*
* @param request
* @return 返回商城协议信息
*/
@Remark("获取商城协议信息")
@RequestMapping(value = "/mallAgreement/get", method = RequestMethod.POST)
@ResponseBody
public Result<Agreement> getMallAgreement(HttpServletRequest request) {
Result<Agreement> result = Result.newOne();
try {
result.data = mallService.getMerchAgreement();
} catch (Exception e) {
result.type = Result.Type.error;
result.message = "获取商城协议失败";
}
return result;
}
/**
* 获取代理商协议信息
*
* @author 郝江奎
* @date 2015年9月6日 下午11:00:15
*
* @param request
* @return 返回代理协议信息
*/
@Remark("获取代理商协议信息")
@RequestMapping(value = "/agentAgreement/get", method = RequestMethod.POST)
@ResponseBody
public Result<Agreement> getAgentAgreement(HttpServletRequest request) {
Result<Agreement> result = Result.newOne();
try {
result.data = mallService.getAgentAgreement();
} catch (Exception e) {
result.type = Result.Type.error;
result.message = "获取代理商协议失败";
}
return result;
}
/**
* 获取供应商商协议信息
*
* @author 郝江奎
* @date 2015年10月12日 下午2:10:15
*
* @param request
* @return 返回供应商协议信息
*/
@Remark("获取供应商协议信息")
@RequestMapping(value = "/vendorAgreement/get", method = RequestMethod.POST)
@ResponseBody
public Result<Agreement> getVendorAgreement(HttpServletRequest request) {
Result<Agreement> result = Result.newOne();
try {
result.data = mallService.getVendorAgreement();
} catch (Exception e) {
result.type = Result.Type.error;
result.message = "获取供应商协议失败";
}
return result;
}
/**
* 获取会员协议信息
*
* @author 郝江奎
* @date 2015年9月6日 下午11:30:15
*
* @param request
* @return 返回会员协议信息
*/
@Remark("获取会员协议信息")
@RequestMapping(value = "/memberAgreement/get", method = RequestMethod.POST)
@ResponseBody
public Result<Agreement> getMemberAgreement(HttpServletRequest request) {
Result<Agreement> result = Result.newOne();
try {
result.data = mallService.getMemberAgreement();
} catch (Exception e) {
result.type = Result.Type.error;
result.message = "获取会员协议失败";
}
return result;
}
/**
* 获取商城管理员信息
*
* @author 王少辉
* @date 2015年5月13日 上午9:45:17
*
* @return 返回商城管理员信息
*/
@Remark("获取商城管理员信息")
@RequestMapping(value = "/admin/get", method = RequestMethod.POST)
@ResponseBody
public Result<User> getMallAdmin(HttpServletRequest request) {
Result<User> result = Result.newOne();
try {
Operator operator = mallService.getOperator();
if (operator != null && operator.getId() != null) {
result.data = userService.getUserById(operator.getId());
}
} catch (Exception e) {
e.printStackTrace();
result.type = Type.error;
result.message = "获取商城管理员信息失败";
}
return result;
}
/**
* 检验商城编号是否唯一
*
* @author 王少辉
* @date 2015年7月23日 上午11:46:26
*
* @param request
* @param mall
* @return 返回验证结果
*/
@Remark("检验商城编号是否唯一")
@RequestMapping(value = "/code/validate/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> validateCode(HttpServletRequest request, @RequestBody Mall mall) {
Result<?> result = Result.newOne();
if (mall != null && mall.getCode() != null) {
Mall existMall = mallService.getMallByCode(mall.getCode());
// 如果商城编号已存在,返回error
if (existMall != null) {
result.type = Type.error;
}
}
return result;
}
/**
* 检验用户手机号是否唯一
*
* @author 王少辉
* @date 2015年7月23日 上午11:46:26
*
* @param request
* @param user
* @return 返回验证结果
*/
@Remark("检验用户手机号是否唯一")
@RequestMapping(value = "/phoneNo/validate/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> validatePhoneNo(HttpServletRequest request, @RequestBody User user) {
Result<?> result = Result.newOne();
if (user != null && user.getPhoneNo() != null) {
User existUser = userService.getUserByPhoneNo(user.getPhoneNo());
// 如果商城手机号已存在,返回error
if (existUser != null && existUser.getId() != user.getId()) {
result.type = Type.error;
}
}
return result;
}
/**
* 注册商城基本信息(如果已存在则修改)
*
* @author 王少辉
* @date 2015年5月13日 上午9:45:27
*
* @return 返回注册结果
*/
@Remark("注册或修改商城信息")
@RequestMapping(value = "/regist/or/update/do", method = RequestMethod.POST)
@ResponseBody
public Result<MallDto> registerOrUpdate(HttpServletRequest request, @RequestBody MallDto mallDto) {
Result<MallDto> result = Result.newOne();
try {
mallDto.setOpenTime(new Date());
boolean ok = false;
if (mallDto.getId() == null) {
ok = mallService.createOrUpdateMall(mallDto);
} else {
ok = mallService.updateMallAndUser(mallDto);
}
if (ok) {
result.message = "保存成功";
result.data = mallDto;
} else {
result.type = Type.error;
result.message = "保存失败";
}
} catch (Exception e) {
e.printStackTrace();
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
/**
* 保存商城基本信息
*
* @author 王少辉
* @date 2015年5月13日 上午9:45:27
*
* @return 返回保存结果
*/
@Remark("保存商城基本信息")
@RequestMapping(value = "/save/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> saveMall(@RequestBody Mall mall) {
Result<?> result = Result.newOne();
try {
boolean ok = mallService.updateMall(mall);
if (ok) {
result.message = "保存成功";
} else {
result.type = Type.error;
result.message = "保存失败";
}
} catch (Exception e) {
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
/**
* 保存商城协议信息
*
* @author 王少辉
* @date 2015年8月18日 下午1:49:07
*
* 协议
* @return 返回保存结果
*/
@Remark("保存商城协议信息")
@RequestMapping(value = "/mallAgreement/save/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> saveMallAgreement(@RequestBody Agreement agreement) {
Result<?> result = Result.newOne();
boolean ok = false;
try {
Agreement agr = mallService.getMerchAgreement();
if (agr == null) {
ok = mallService.saveMerchAgreement(agreement);
} else {
agr.setContent(agreement.getContent());
ok = mallService.updateAgreement(agr);
}
if (ok) {
result.message = "保存成功";
} else {
result.type = Type.error;
result.message = "保存失败";
}
} catch (Exception e) {
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
/**
* 保存代理协议信息
*
* @author 郝江奎
* @date 2015年9月6日 下午11:38:07
*
* 协议
* @return 返回保存结果
*/
@Remark("保存代理协议信息")
@RequestMapping(value = "/agentAgreement/save/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> saveAgentAgreement(@RequestBody Agreement agreement) {
Result<?> result = Result.newOne();
boolean ok = false;
try {
Agreement agr = mallService.getAgentAgreement();
if (agr == null) {
ok = mallService.saveAgentAgreement(agreement);
} else {
agr.setContent(agreement.getContent());
ok = mallService.updateAgreement(agr);
}
if (ok) {
result.message = "保存成功";
} else {
result.type = Type.error;
result.message = "保存失败";
}
} catch (Exception e) {
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
/**
* 保存供应商协议信息
*
* @author 郝江奎
* @date 2015年10月12日 下午14:38:07
*
* 协议
* @return 返回保存结果
*/
@Remark("保存供应商协议信息")
@RequestMapping(value = "/vendorAgreement/save/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> saveVendorAgreement(@RequestBody Agreement agreement) {
Result<?> result = Result.newOne();
boolean ok = false;
try {
Agreement agr = mallService.getVendorAgreement();
if (agr == null) {
ok = mallService.saveVendorAgreement(agreement);
} else {
agr.setContent(agreement.getContent());
ok = mallService.updateAgreement(agr);
}
if (ok) {
result.message = "保存成功";
} else {
result.type = Type.error;
result.message = "保存失败";
}
} catch (Exception e) {
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
/**
* 保存会员协议信息
*
* @author 郝江奎
* @date 2015年9月6日 下午11:40:07
*
* 协议
* @return 返回保存结果
*/
@Remark("保存会员协议信息")
@RequestMapping(value = "/memberAgreement/save/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> saveMemberAgreement(@RequestBody Agreement agreement) {
Result<?> result = Result.newOne();
boolean ok = false;
try {
Agreement agr = mallService.getMemberAgreement();
if (agr == null) {
ok = mallService.saveMemberAgreement(agreement);
} else {
agr.setContent(agreement.getContent());
ok = mallService.updateAgreement(agr);
}
if (ok) {
result.message = "保存成功";
} else {
result.type = Type.error;
result.message = "保存失败";
}
} catch (Exception e) {
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
// ----------------------------------商城设置----------------------------------
/**
* 商城设置页面
*
* @author 王少辉
* @date 2015年5月21日 上午9:56:46
*
* @return 返回商城设置页面
*/
@Remark("商城设置页面")
@RequestMapping(value = "/setting/jsp", method = RequestMethod.GET)
public String toPersonalInfoJsp() {
return "mall/mallSetting";
}
/**
* 获取商城公告列表
*
* @author 王少辉
* @date 2015年5月21日 上午10:04:29
*
* @return 返回商城公告列表
*/
@RequestMapping(value = "/notice/list/get", method = RequestMethod.POST)
@ResponseBody
public JqGridPage<MallNotice> getMallNoticeList(HttpServletRequest request) {
JqGridRequest jqGridRequest = JqGridRequest.fromRequest(request);
PaginatedFilter paginatedFilter = jqGridRequest.toPaginatedFilter();
PaginatedList<MallNotice> paginatedList = mallService.getMallNoticesByFilter(paginatedFilter);
JqGridPage<MallNotice> jqGridPage = JqGridPage.fromPaginatedList(paginatedList);
return jqGridPage;
}
/**
* 获取商城公告
*
* @author 王少辉
* @date 2015年8月21日 上午10:29:56
*
* @return 返回商城公告
*/
@RequestMapping(value = "/notice/get", method = RequestMethod.POST)
@ResponseBody
public Result<MallNotice> getMallNotice() {
Result<MallNotice> result = Result.newOne();
try {
Integer id = 1;
MallNotice mallNotice = mallService.getMallNoticeById(id);
if (mallNotice == null) {
return result;
}
result.data = mallNotice;
} catch (Exception e) {
result.type = Type.error;
result.message = "获取商城公告失败";
}
return result;
}
/**
* 保存商城公告
*
* @author 王少辉
* @date 2015年5月21日 上午11:13:50
*
* @param mallNotice
* 商城公告
* @return 返回保存结果
*/
@RequestMapping(value = "/notice/save/do", method = RequestMethod.POST)
@ResponseBody
public Result<MallNotice> saveMallNotice(@RequestBody MallNotice mallNotice) {
Result<MallNotice> result = Result.newOne();
try {
if (mallNotice.getAutoFlag()) {
// 自动发布
mallNotice.setStartDate(mallNotice.getPubTime());
mallNotice.setEndDate(mallNotice.getEndTime());
} else {
// 手动发布
mallNotice.setEndDate(mallNotice.getPubTime());
}
result.message = mallService.saveMallNotice(mallNotice) ? "保存成功" : "保存失败";
result.data = mallNotice;
} catch (Exception e) {
result.type = Type.error;
result.message = "保存失败";
}
return result;
}
/**
* 修改商城公告
*
* @author 王少辉
* @date 2015年8月27日 下午7:36:10
*
* @param mallNotice
* 商城公告
* @return 返回修改商城公告结果
*/
@Remark("修改商城公告")
@RequestMapping(value = "/notice/update/do", method = RequestMethod.POST)
@ResponseBody
public Result<MallNotice> updateMallNotice(@RequestBody MallNotice mallNotice) {
Result<MallNotice> result = Result.newOne();
if (mallNotice.getAutoFlag()) {
// 自动发布
mallNotice.setStartDate(mallNotice.getPubTime());
mallNotice.setEndDate(mallNotice.getEndTime());
} else {
// 手动发布
mallNotice.setPubTime(null);
mallNotice.setEndDate(mallNotice.getPubTime());
}
result.message = mallService.updateMallNotice(mallNotice) ? "修改成功!" : "修改失败!";
result.data = mallNotice;
return result;
}
/**
* 发布商城公告
*
* @author 王少辉
* @date 2015年8月27日 下午7:36:47
*
* @param requestData
* @return 返回发布商城公告结果
*/
@Remark("发布商城公告")
@RequestMapping(value = "/notice/publish/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> publishMallNotice(@RequestBody MapContext requestData) {
Result<?> result = Result.newOne();
Integer id = requestData.getTypedValue("id", Integer.class);
MallNotice mallNotice = mallService.getMallNoticeById(id);
Date pubTime = new Date();
mallNotice.setStatus(1);
mallNotice.setPubTime(pubTime);
mallNotice.setStartDate(pubTime);
result.message = mallService.updateMallNotice(mallNotice) ? "发布成功!" : "发布失败!";
return result;
}
/**
* 停止店铺公告
*
* @author 王少辉
* @date 2015年8月27日 下午7:38:22
*
* @param requestData
* @return 返回停止商城公告结果
*/
@Remark("停止店铺公告")
@RequestMapping(value = "/notice/stop/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> stopMallNotice(@RequestBody MapContext requestData) {
Result<?> result = Result.newOne();
Integer id = requestData.getTypedValue("id", Integer.class);
MallNotice mallNotice = mallService.getMallNoticeById(id);
Date endTime = new Date();
mallNotice.setStatus(2);
mallNotice.setEndTime(endTime);
mallNotice.setEndDate(endTime);
result.message = mallService.updateMallNotice(mallNotice) ? "停止成功!" : "停止失败!";
return result;
}
/**
* 删除店铺公告
*
* @author 王少辉
* @date 2015年8月27日 下午7:39:26
*
* @param id
* 删除的店铺公告id
* @return 返回删除店铺公告结果
*/
@Remark("删除店铺公告")
@RequestMapping(value = "/notice/delete/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> deleteMallNotice(@RequestParam("id") Integer id) {
Result<?> result = Result.newOne();
result.message = mallService.delMallNoticeById(id) ? "删除成功!" : "删除失败!";
return result;
}
/**
* 批量删除店铺公告
*
* @author 王少辉
* @date 2015年8月27日 下午7:43:07
*
* @param ids
* 批量删除的店铺公告id
* @return 返回批量删除店铺公告结果
*/
@Remark("批量删除店铺公告")
@RequestMapping(value = "/notice/delete/batch/do", method = RequestMethod.POST)
@ResponseBody
public Result<?> deleteMallNoticeByIds(@RequestBody List<Integer> ids) {
Result<?> result = Result.newOne();
result.message = mallService.delMallNoticeByIds(ids) ? "删除成功!" : "删除失败!";
return result;
}
// ----------------------------------商城人员列表 角色分配----------------------------------
/**
* 人员列表界面
*
* @author zjl
* @date 2015年6月5日 上午11:31:10
*
* @return
*/
@Remark("商城人员列表界面")
@RequestMapping(value = "/staff/list/jsp", method = RequestMethod.GET)
public String toMallStaffListPage() {
return "mall/mallStaffList";
}
/**
* 查询店铺下的人员
*
* @author guoyn
* @date 2015年8月19日 上午9:32:00
*
* @param request
* @return JqGridPage<User>
*/
@Remark("店铺下的人员")
@RequestMapping(value = "/staff/list/get", method = RequestMethod.POST)
@ResponseBody
public JqGridPage<User> listUserRole(HttpServletRequest request) {
// 封装前台参数为JqGridRequest格式
JqGridRequest jqGridRequest = JqGridRequest.fromRequest(request);
// 封装为PaginatedFilter格式
PaginatedFilter paginatedFilter = jqGridRequest.toPaginatedFilter();
//
UserContext userContext = getUserContext(request);
String scope = userContext.getScope();
AuthScope authScope = AuthScope.valueOf(scope);
Integer entityId = userContext.getScopeEntityId(scope);
//
PaginatedList<User> paginatedList = userService.getUsersByScopeAndEntityIdAndFilter(authScope, entityId, paginatedFilter);
//
JqGridPage<User> jqGridPage = JqGridPage.fromPaginatedList(paginatedList);
return jqGridPage;
}
/**
* 根据条件查询用户
*
* @author guoyn
* @date 2015年8月19日 上午9:32:43
*
* @param request
* @return JqGridPage<User>
*/
@Remark("根据条件查询用户")
@RequestMapping(value = "/user/list/get", method = RequestMethod.POST)
@ResponseBody
public JqGridPage<User> listUsersByParms(HttpServletRequest request) {
// 封装前台参数为JqGridRequest格式
JqGridRequest jqGridRequest = JqGridRequest.fromRequest(request);
// 封装为PaginatedFilter格式
PaginatedFilter paginatedFilter = jqGridRequest.toPaginatedFilter();
MapContext filter = paginatedFilter.getFilterItems();
String phoneNo = filter.getTypedValue("phoneNo", String.class);
String nickName = filter.getTypedValue("nickName", String.class);
//
PaginatedList<User> paginatedList = PaginatedList.newOne();
if (!StrUtil.hasText(phoneNo) && !StrUtil.hasText(nickName)) {
paginatedList.setRows(new ArrayList<User>(0));
paginatedList.setPagination(paginatedFilter.getPagination());
} else {
UserContext userContext = getUserContext(request);
String scope = userContext.getScope();
AuthScope authScope = AuthScope.valueOf(scope);
Integer entityId = userContext.getScopeEntityId(scope);
//
paginatedList = userService.getUsersByFilter(paginatedFilter, true);
List<User> userList = paginatedList.getRows();
for (User user : userList) {
List<Role> roles = authxService.getRolesByUserIdAndScopeAndEntityId(user.getId(), authScope, entityId);
user.setRoles(roles);
}
//
paginatedList.setRows(userList);
}
//
JqGridPage<User> jqGridPage = JqGridPage.fromPaginatedList(paginatedList);
return jqGridPage;
}
/**
* 获取店铺下所有的角色及相应权限列表
*
* @author guoyn
* @date 2015年8月19日 上午9:33:00
*
* @param requestData
* @return Result<List<Role>>
*/
@Remark("获取店铺下所有的角色及相应权限列表")
@RequestMapping(value = "/roles/and/perms/get", method = RequestMethod.POST)
@ResponseBody
public Result<List<Role>> getAllRoles(HttpServletRequest request, @RequestBody MapContext requestData) {
//
Result<List<Role>> result = Result.newOne();
//
UserContext userContext = getUserContext(request);
String scope = userContext.getScope();
AuthScope authScope = AuthScope.valueOf(scope);
Integer entityId = userContext.getScopeEntityId(scope);
//
List<Role> roles = authxService.getRolesByScopeAndEntityId(authScope, entityId, true);
for (Role role : roles) {
List<Permission> perms = authxService.getPermissonsByRoleId(role.getId());
role.setPerms(perms);
}
//
result.data = roles;
//
return result;
}
/**
* 更新店铺人员的角色列表
*
* @author guoyn
* @date 2015年8月19日 下午5:26:02
*
* @param requestData
* @return Result<Object>
*/
@Remark("更新店铺人员的角色")
@RequestMapping(value = "/user/roles/update/do", method = RequestMethod.POST)
@ResponseBody
@SuppressWarnings("unchecked")
public Result<Object> updateUserRoles(HttpServletRequest request, @RequestBody MapContext requestData) {
//
Result<Object> result = Result.newOne();
result.message = "保存成功";
//
UserContext userContext = getUserContext(request);
String scope = userContext.getScope();
AuthScope authScope = AuthScope.valueOf(scope);
Integer entityId = userContext.getScopeEntityId(scope);
//
RelChangeInfo relChangeInfo = new RelChangeInfo();
//
Integer userId = requestData.getTypedValue("userId", Integer.class);
List<Integer> deleteRoleIds = requestData.getTypedValue("deleteRoleIds", TypeUtil.Types.IntegerList.getClass());
List<Integer> addRoleIds = requestData.getTypedValue("addRoleIds", TypeUtil.Types.IntegerList.getClass());
//
relChangeInfo.setMainId(userId);
relChangeInfo.setSubIdsDeleted(deleteRoleIds);
relChangeInfo.setSubIdsAdded(addRoleIds);
//
boolean ok = authxService.updateUserRoles(relChangeInfo, authScope, entityId);
//
result.message = ok ? "保存成功!" : "保存失败!";
return result;
}
/**
* 解除用户所有角色
*
* @author guoyn
* @date 2015年8月19日 下午5:32:25
*
* @param requestData
* @return Result<Object>
*/
@Remark("解除用户所有角色")
@RequestMapping(value = "/user/roles/unbind/do", method = RequestMethod.POST)
@ResponseBody
public Result<Object> unbindUserRoles(HttpServletRequest request, @RequestBody MapContext requestData) {
Result<Object> result = Result.newOne();
//
UserContext userContext = getUserContext(request);
String scope = userContext.getScope();
AuthScope authScope = AuthScope.valueOf(scope);
Integer entityId = userContext.getScopeEntityId(scope);
//
Integer userId = requestData.getTypedValue("userId", Integer.class);
boolean ok = authxService.unbindUserRolesByUserIdAndScopeAndEntityId(userId, authScope, entityId);
result.message = ok ? "操作成功" : "操作失败";
return result;
}
}
|
Java | UTF-8 | 912 | 3.125 | 3 | [] | no_license | package by.dev.gui.core.struct;
public class Rect {
private int left;
private int top;
private int width;
private int height;
public Rect(int left, int top, int width, int height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
public Rect(Rect rect) {
this.left = rect.left;
this.top = rect.top;
this.width = rect.width;
this.height = rect.height;
}
public boolean contains(Point point) {
return left <= point.x && left + width > point.x && top <= point.y && top + height > point.y;
}
public int getLeft() {
return left;
}
public int getTop() {
return top;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public boolean equals(Object texture) {
Rect r = (Rect)texture;
return r.left == this.left && r.top == this.top && r.width == this.width && r.height == this.height;
}
} |
Java | UTF-8 | 16,653 | 2.421875 | 2 | [] | no_license | /*
*
* Copyright (c) 2007, Sun Microsystems, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Sun Microsystems nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package example.imageviewer;
import java.io.*;
import javax.microedition.content.*;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* Simple Image Viewer for PNG images.
* This application uses the CHAPI API both
* to invoke a content handler via a URL and to handle
* an Invocation request.
*
* The application implements the CHAPI request listener to respond
* to requests. The listener constructs an Image from the
* URL and displays it. A "Back" command is made available
* to finish the request.
*
* A response listener is used to handle the response
* as an informational alert to the user.
*
* The application provides a simple user interface to enter a URL
* and a "Go" command to invoke the URL.
*
* A "Save" command is used to invoke a ScreenSaver application.
*
*/
public class ImageViewer extends MIDlet implements CommandListener, RequestListener,
ResponseListener {
/** The type for PNG. */
static final String PNG_TYPE = "image/png";
/** The suffix supported. */
static final String PNG_SUFFIX = ".png";
/** The Content Handler ID. */
static final String CHID = "com.sun.example.imageviewer";
/** The list of applications allowed to access. */
static final String[] ACCESS_ALLOWED = { "com.sun.example" };
/** The content handlers class that implements the image viewer. */
static final String CH_CLASSNAME = "example.imageviewer.ImageViewer";
/** The application class that will be calling Registry functions. */
static final String CALLER_CLASSNAME = "example.imageviewer.ImageViewer";
/** Current invocation, null if no current Invocation. */
Invocation invoc;
/** ContentHandlerServer from which to get requests. */
ContentHandlerServer handler;
/** Access to Registry functions and responses. */
Registry registry;
/** The Display for the viewer. */
Display display;
/** The Form to display the image. */
Form form;
/** The ImageItem displaying the image. */
ImageItem imageItem;
/** The TextField to input a URL. */
TextField urlField;
/** The Back Command to dismiss the viewer. */
Command backCommand = new Command("Back", Command.BACK, 1);
/** The Go Command to invoke the link. */
Command goCommand = new Command("Go", Command.OK, 1);
/** The Save Command to invoke the screen saver. */
Command saveCommand = new Command("Save", Command.SCREEN, 2);
/**
* Initialize the viewer user interface and listeners for requests
* and responses.
*/
public ImageViewer() {
// Setup the user interface components
display = Display.getDisplay(this);
form = new Form("Image Viewer");
urlField = new TextField("Enter a link to an image", "http://", 80, TextField.HYPERLINK);
imageItem = new ImageItem(null, null, Item.LAYOUT_CENTER, "-no image-");
form.setCommandListener(this);
showURL();
/*
* Get access to the registry for this application
* and setup the listener for responses to invocations.
*/
registry = Registry.getRegistry(CALLER_CLASSNAME);
registry.setListener(this);
/*
* Get access to the ContentHandlerServer for
* incoming invocation requests.
*/
try {
handler = Registry.getServer(CH_CLASSNAME);
} catch (ContentHandlerException che) {
// Our registration is missing, reinstate it
register();
}
/*
* Register the listener to be notified of new requests.
* If there is a pending request the listener will be
* notified immediately.
*/
if (handler != null) {
handler.setListener(this);
}
}
/**
* Switch to show the URL input field.
* Enable the "Go" command.
*/
void showURL() {
form.deleteAll();
form.removeCommand(backCommand);
form.removeCommand(saveCommand);
form.addCommand(goCommand);
form.append(urlField);
display.setCurrent(form);
}
/**
* Show an image.
* Enable the "Go" command.
* @param image the Image to display
*/
void showImage(Image image) {
form.deleteAll();
form.removeCommand(goCommand);
imageItem.setImage(image);
form.addCommand(backCommand);
form.addCommand(saveCommand);
form.append(imageItem);
display.setCurrent(form);
}
/**
* Start the application; no additional action needed.
*/
public void startApp() {
}
/**
* Pause the application; no additional action needed.
*/
public void pauseApp() {
}
/**
* Cleanup and destroy the application.
*
* @param force true to force the exit (always exit)
*/
public void destroyApp(boolean force) {
// Reset the listeners
if (handler != null) {
handler.setListener(null);
}
if (registry != null) {
registry.setListener(null);
}
/*
* Finish any pending invocation;
* ignore the mustExit return since the application is exiting
*/
finish(Invocation.OK);
}
/**
* Process a new Invocation request.
* In this example, the new request may interrupt the display of a
* current request.
* If so, the current request is "finished" so the new
* request can be displayed.
*
* To avoid application thrashing do not exit, even if requested,
* until the new request is finished.
*
* @param h the ContentHandlerServer with the new request
*/
public void invocationRequestNotify(ContentHandlerServer h) {
/*
* If there is a current Invocation finish it
* so the next Contact can be displayed.
*/
if (invoc != null) {
handler.finish(invoc, Invocation.OK);
}
// Dequeue the next invocation
invoc = handler.getRequest(false);
if (invoc != null) {
// Display the content of the image
displayImage(invoc);
}
}
/**
* Process a response to a previous request.
* Put up the prompt for URL again.
* @param r the Registry with the response
*/
public void invocationResponseNotify(Registry r) {
Invocation resp = r.getResponse(false);
if (resp != null) {
int st = resp.getStatus();
String msg;
if (st == Invocation.OK) {
msg = "Request successful";
} else if (st == Invocation.CANCELLED) {
msg = "Request cancelled";
} else {
msg = "Request failed";
}
// Restore the URL prompt after the alert
showURL();
Alert alert = new Alert("Request completed", msg, null, AlertType.INFO);
display.setCurrent(alert, form);
}
}
/**
* Handle command on the Form.
* On user command "Back", finish the Invocation request.
* On user command "Go", invoke the supplied URL.
* @param c the Command
* @param s the Displayable the command occurred on
*/
public void commandAction(Command c, Displayable s) {
if (c == backCommand) {
finish(Invocation.OK);
/*
* Relinquish the display until this application
* receives another request to display.
* The image will stay visible until the next request
* or the application is destroyed.
*/
display.setCurrent(null);
}
if (c == goCommand) {
/*
* Invoke the URL in a new Thread to prevent blocking the
* user interface.
*/
Runnable r =
new Runnable() {
public void run() {
doInvoke(urlField.getString());
}
;
};
(new Thread(r)).start();
}
if (c == saveCommand) {
/*
* Use a new thread to send the URL from the
* current invocation to the ScreenSaver.
*/
Runnable r =
new Runnable() {
public void run() {
doSave();
}
;
};
(new Thread(r)).start();
}
}
/**
* Invoke the URL provided.
* @param url the URL of an image
*/
void doInvoke(String url) {
try {
Invocation invoc = new Invocation(url);
boolean mustExit = registry.invoke(invoc);
if (mustExit) {
// App must exit before invoked application can run
destroyApp(true); // cleanup
notifyDestroyed(); // inform the application manager
} else {
// Application does not need to exit
}
} catch (IOException ex) {
Alert alert = new Alert("Image not available", "Could not link to " + url, null, null);
display.setCurrent(alert);
}
}
/**
* Finish the current invocation if any.
* If the application is ask to exit then
* the cleanup in destroyApp is done and the application
* manager notified of the exit.
*
* @param status the status to pass to finish
* @return true if the application should exit
*/
boolean finish(int status) {
if (invoc != null) {
boolean mustExit = handler.finish(invoc, status);
invoc = null;
if (mustExit) {
// Viewer must exit before response can be delivered
destroyApp(true);
notifyDestroyed(); // inform the application manager
return true;
} else {
// Application does not need to exit
}
}
return false;
}
/**
* Fetch the Image and display.
* @param invoc an Invocation with the URL and contents
*/
void displayImage(Invocation invoc) {
HttpConnection conn = null;
InputStream is = null;
if (imageItem != null) {
imageItem.setImage(null); // remove any old image
}
try {
conn = (HttpConnection)invoc.open(false);
// Check the status and read the content
int status = conn.getResponseCode();
if (status != conn.HTTP_OK) {
Alert alert =
new Alert("Can not display the image", "image not found at " + invoc.getURL(),
null, AlertType.ERROR);
display.setCurrent(alert);
finish(Invocation.CANCELLED);
return;
}
String type = conn.getType();
if (!PNG_TYPE.equals(type)) {
Alert alert =
new Alert("Can not display the image", "Unknown type " + type, null,
AlertType.ERROR);
display.setCurrent(alert);
finish(Invocation.CANCELLED);
return;
}
// Get the image from the connection
is = conn.openInputStream();
Image image = Image.createImage(is);
// Display the image
showImage(image);
display.setCurrent(form);
} catch (IOException e) {
Alert alert =
new Alert("Can not display the image", "Image not available", null, AlertType.ERROR);
display.setCurrent(alert);
finish(Invocation.CANCELLED);
return;
} finally {
try {
if (is != null) {
is.close();
}
if (conn != null) {
conn.close();
}
} catch (IOException ioe) {
// Ignore exceptions in close
}
}
}
/**
* Dynamic registration of content handler.
* This example shows the registration of a MIDlet as a handler with
* the application ID "com.sun.example.imageviewer",
* for the type "image/png", suffix ".png", and access
* allowed to the "com.sun.example".
*/
void register() {
try {
// Create a content handler instance for our Generic PNG Handler
String[] chTypes = { PNG_TYPE };
String[] chSuffixes = { PNG_SUFFIX };
String[] chActions = { ContentHandler.ACTION_OPEN };
String chClassname = CH_CLASSNAME;
handler =
registry.register(chClassname, chTypes, chSuffixes, chActions, null, /* action name maps */
CHID, ACCESS_ALLOWED);
} catch (ContentHandlerException ex) {
Alert alert =
new Alert("Unable to register handler", "Handler conflicts with another handler",
null, AlertType.ERROR);
display.setCurrent(alert);
} catch (ClassNotFoundException cnf) {
Alert alert =
new Alert("Unable to register handler", "Handler class not found", null,
AlertType.ERROR);
display.setCurrent(alert);
}
}
/**
* Saving the image to a ScreenSaver application.
*
* Suppose there is a ScreenSaver application that is used to
* control the idle image. This Image viewer application
* should be able to invoke the screen saver so the current image
* can be set as the idle screen. An additional command is
* added to invoke the screensaver.
* Invoking the screen saver MUST not be called
* from the UI thread because it may block while I/O completes.
*/
void doSave() {
try {
/*
* Invoke the application for the ID "ScreenSaver"
* passing the URL if the Image.
*/
Invocation nextInvoc = new Invocation();
nextInvoc.setID("ScreenSaver");
nextInvoc.setURL(invoc.getURL());
nextInvoc.setResponseRequired(false);
// Chain the new invocation to the previous invocation
boolean mustExit = registry.invoke(nextInvoc, invoc);
if (mustExit) {
// App must exit before invoked application can run
destroyApp(true); // cleanup
notifyDestroyed(); // inform the application manager
} else {
// Application does not need to exit
}
} catch (IOException ex) {
Alert alert =
new Alert("Invoking ScreenSaver", "Could not save the image", null, AlertType.ERROR);
display.setCurrent(alert);
}
}
}
|
C# | UTF-8 | 6,577 | 3.25 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using static T297_Hard_Tree_Design.Codec;
using System.Linq;
using System.Text;
namespace T297_Hard_Tree_Design
{
class Program
{
static void Main(string[] args)
{
Codec c = new Codec();
TreeNode root = new TreeNode(1);
TreeNode r = new TreeNode(3);
TreeNode rl = new TreeNode(-1);
TreeNode rr = new TreeNode(5);
root.right = r;
r.left = rl;
r.right = rr;
var res = c.serialize(root);
//var newroot = c.deserialize(res);
TreeNode rootR = new TreeNode(0);
TreeNode r1 = new TreeNode(1);
TreeNode r2 = new TreeNode(2);
TreeNode r3 = new TreeNode(3);
rootR.right = r1;
r1.right = r2;
r2.right = r3;
var resR = c.serialize(rootR);
var newrootR = c.deserialize(resR);
var test = c.deserialize("1,2,3,,,4,5");
}
}
public class Codec
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
// Encodes a tree to a single string.
public string serialize(TreeNode root)
{
if (root == null)
return "";
List<int?> res = new List<int?>();
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
while (q.Count > 0)
{
var node = q.Dequeue();
if (node == null)
res.Add(null);
else
{
res.Add(node.val);
q.Enqueue(node.left);
q.Enqueue(node.right);
}
}
var sb = new StringBuilder();
foreach (var item in res)
{
sb.Append(item);
sb.Append(',');
}
return sb.ToString(0, sb.Length - 1);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(string data)
{
if (data == "")
return null;
List<int?> datalist = data.Split(',').Select(i => i == "" ? (int?)null : int.Parse(i)).ToList();
TreeNode head = new TreeNode((int)datalist[0]);
List<TreeNode> last = new List<TreeNode> { head };
var index = 0;
List<TreeNode> current = new List<TreeNode>();
for(var j = 1; j < datalist.Count; j++)
{
current.Add(datalist[j] == null ? null : new TreeNode((int)datalist[j]));
if (j % 2 != 0)//left
{
last[index].left = current[index * 2];
}
else
{
last[index].right = current[index * 2 + 1];
index++;
if (current.Count == last.Count * 2)
{
last = current.Where(i => i != null).ToList();
index = 0;
current = new List<TreeNode>();
}
}
}
return head;
}
/* 用了满二叉树,逻辑OK,极限情况纯单侧子树时效率极低
// Encodes a tree to a single string.
public string serialize(TreeNode root)
{
if (root == null)
return "";
List<int?> res = new List<int?>();
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
var layer = 0;
var layercount = 0;
var nullcount = 0;
while (q.Count > 0)
{
var node = q.Dequeue();
layercount++;
if (node == null)
{
nullcount += 2;
res.Add(null);
q.Enqueue(null);
q.Enqueue(null);
}
else
{
res.Add(node.val);
if (node.left == null)
nullcount++;
q.Enqueue(node.left);
if (node.right == null)
nullcount++;
q.Enqueue(node.right);
}
if (layercount == Math.Pow(2, layer))
{
if (nullcount == layercount * 2)
break;
else
{
nullcount = 0;
layercount = 0;
layer++;
}
}
}
var sb = new StringBuilder();
foreach (var i in res)
{
sb.Append(i);
sb.Append(',');
}
return sb.ToString(0, sb.Length - 1);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(string data)
{
List<string> datalist = data.Split(',').ToList();
if (datalist[0] == "")
return null;
else
{
TreeNode root = new TreeNode(int.Parse(datalist[0]));
if (1 < datalist.Count && datalist[1] != null)
root.left = deserializeHelp(datalist, 1);
if (2 < datalist.Count && datalist[2] != null)
root.right = deserializeHelp(datalist, 2);
return root;
}
}
private TreeNode deserializeHelp(List<string> datalist, int index)
{
if (index >= datalist.Count)
return null;
else
{
if (datalist[index] == "")
return null;
else
{
TreeNode res = new TreeNode(int.Parse(datalist[index]));
if (2 * index + 1 < datalist.Count && datalist[2 * index + 1] != null)
res.left = deserializeHelp(datalist, 2 * index + 1);
if (2 * index + 2 < datalist.Count && datalist[2 * index + 2] != null)
res.right = deserializeHelp(datalist, 2 * index + 2);
return res;
}
}
}
*/
}
}
|
JavaScript | UTF-8 | 1,647 | 2.734375 | 3 | [] | no_license | //useful for debug until I have a real redirect coming in to read from.
var fakeParams = {
"identifierType" : "Gene",
"identifiers" : ["pparg", "GATA1", "AVP"],
"organism" : "H. sapiens"
}
//let's make the list of mines globally accessible
var mines;
//get all InterMines as soon as the DOM has loaded
document.addEventListener("DOMContentLoaded", function() {
$.ajax("http://registry.intermine.org/service/instances").then(function(response) {
//storing mines globally
mines = response.instances;
var minesList = document.getElementById("interMinesList");
//debug. remove when done.
console.log(mines);
//once everything is loaded, display a list of mines to the user
mines.map(function(mine) {
minesList.append(mineNode(mine));
});
});
});
function mineNode(mine) {
//Generate text for links to each mine.
var mineNode = document.createElement("tr"),
mineRow = "<td>" + mine.name + "</td>" +
"<td>" + mine.organisms.join(", ")
+ "</td><td class='exportToMine'>" + mineNav(mine, fakeParams) + "</td>";
mineNode.organisms = mine.organisms;
mineNode.setAttribute("class", "mineEntry");
mineNode.innerHTML = mineRow;
return mineNode;
}
function mineNav(mine, data) {
return '<form action="' + mine.url +'/portal.do" name="list" method="post">' +
'<input type="hidden" name="externalids" value="' +
fakeParams.identifiers.join(",") + '" />' +
'<input type="hidden" name="class" value="' +
fakeParams.identifierType + '" />' +
'<input type="submit" value="Send to ' + mine.name +'" />' +
'</form>'
}
|
Java | UTF-8 | 1,275 | 3.34375 | 3 | [] | no_license | package Day6;
public class Car {
int releaseYear;
String color;
String model;
public void setReleaseYear(int userReleaseYear){
if(userReleaseYear < 1900) {
System.out.println("Вы указали не верный год выпуска. Человечество еще не изобрело автомобиль");
} else {
releaseYear = userReleaseYear;
}
}
public void setColor(String userColor){
if(userColor.isEmpty()){
System.out.println("Вы не ввели цвет атомобиля");
} else {
color = userColor;
}
}
public void setModel(String userModel){
if(userModel.isEmpty()){
System.out.println("Вы не ввели модель атомобиля");
} else {
model = userModel;
}
}
public int getReleaseYear(){
return releaseYear;
}
public String getColor(){
return color;
}
public String getModel(){
return model;
}
public void info() {
System.out.println("Это автомобиль");
}
public int yearDifference(int year) {
int yearDiff = year - releaseYear;
return yearDiff;
}
}
|
PHP | UTF-8 | 707 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Create_cars_table extends CI_Migration {
public function up() {
$this->dbforge->add_field('id');
$fields = array(
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'userId' => array(
'type' => 'INT',
),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_field('created_at DATETIME NOT NULL');
$this->dbforge->add_field('modified_at DATETIME NOT NULL');
$this->dbforge->create_table('cars');
echo '<p>#003 Created cars table!</p>';
}
public function down() {
$this->dbforge->drop_table('cars');
echo '<p>#003 Deleted cars table!</p>';
}
} |
Markdown | UTF-8 | 1,948 | 2.71875 | 3 | [] | no_license | # WideBox
Design and implementation of a distributed and resilient very-large scale interactive system
## RMI Instructions for the labs
The servers MUST have the `-Djava.rmi.server.hostname=<public-ip-of-the-server>` property set AND the rmiregistry should be started previously (and thus, port 1099 should not be used, or an `AlreadyBoundException` will be thrown). Failure to follow these steps will result in a "Connection Refused" error upon any RMI Invocation.
We include 2 .sh files to run the appservers and the dbservers which already sets the hostname argument automatically, so you can use these executables to run the servers, assuming you have the jar files.
To start the rmi registry, simply run `rmiregistry`. The terminal running this needs to remain open while the server is running.
By default, the appserver runs on port 1090 and the database server on port 1098, but if you want you can specify a new port as an optional argument when running the executables, just run `start.sh 8080`
## Running the Web Client
The web client was tested using two web servers, Wildfly and Tomcat, but it's currently suggested to use Wildfly.
There's also a way to create a standalone jar file of the web client that already contains a copy of the Wildfly Swarm web server. To create this standalone jar file, run `mv install` on the main project.
The `widebox-web-client-swarm.jar` file will be created at `WideBox/widebox-web-client/target`.
The client will be running at `http://localhost:8080/`.
## Provided Jars
We already provide pre-built executable jars of everything: the 3 text clients, the web client, the app server and the database server.
Since the web client jar file has 44 MB, if we can't upload it due to size limits, we'll place a text file with a link to download it instead.
To execute any of the jar files, you just need to use the standart java jar command, eg:
```shell
java -jar widebox-web-client-swarm.jar
``` |
C# | UTF-8 | 528 | 2.859375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ReadingBooties
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\bootie.txt");
string input = sr.ReadToEnd();
sr.Close();
Match m = Regex.Match(input, @"^timeout\s(.*)$", RegexOptions.Multiline);
Console.WriteLine(m.Groups[1]);
}
}
}
|
Python | UTF-8 | 11,800 | 3.328125 | 3 | [] | no_license | # imports
import numpy as np
from proj1_helpers import *
##################################################################################
################################ Least Square GD ###############################
##################################################################################
def least_squares_GD(y, tx, initial_w, max_iters=1000, gamma=1e-2):
"""
Linear regression of mean-square error using gradient descent
Args:
y: Target values
tx: Training data
initial_w: initial w for the gradient descent
max_iters: maximum number of iteration, default_value=1000
gamma: step size
Returns:
ws[best]: Optimal weight vector
losses[best]: MSE error of ws[best]
"""
current_w = initial_w
loss = compute_loss_mse(y, tx, current_w)
#Store the initial_w with the corresponding loss
ws = [current_w]
losses = [loss]
for n_iter in range(max_iters):
gradient = compute_gradient_mse(y,tx,current_w)
#Update w
next_w = current_w - gamma*gradient
#store the new w with the corresponding loss
ws.append(next_w)
losses.append(compute_loss_mse(y, tx, next_w))
current_w = next_w
#get index of w with the minimum loss
best = np.argmin(losses)
return ws[best], losses[best]
##################################################################################
################################ Least Square SGD ###############################
##################################################################################
def least_squares_SGD(y, tx, initial_w, max_iters = 500, gamma=1e-2, batch_size = 200):
"""
Linear regression using stochastic gradient descent
Args:
y: Target values
tx: Training data
initial_w: initial w for the stochastic gradient descent
max_iters: maximum number of iterations, default_value=1000
gamma: step size
batch_size: batch size for stochastic descent
Returns:
ws[best]: Optimal weight vector
losses[best]: MSE error of ws[best]
"""
current_w = initial_w
loss = compute_loss_mse(y, tx, current_w)
#Store the initial_w with the corresponding loss
ws = [current_w]
losses = [loss]
for n_iter in range(max_iters):
for minibatch_y, minibatch_tx in batch_iter(y, tx, batch_size):
stochastic_gradient = compute_gradient_mse(minibatch_y, minibatch_tx, current_w)
#Update the w
next_w = current_w - gamma*stochastic_gradient
#Store current_w and loss
ws.append(next_w)
losses.append(compute_loss_mse(y, tx, next_w))
current_w = next_w
#get index of w with the minimum loss
best = np.argmin(losses)
return ws[best], losses[best]
##################################################################################
################################ Least Squares ###################################
##################################################################################
def least_squares(y, tx):
"""
Least squares regression using normal equations
Args:
y: Target values
tx: Training data
Returns:
w: Optimal weight vector
loss: MSE error of w
"""
AtA = np.dot(tx.T, tx)
Aty = np.dot(tx.T, y)
w = np.linalg.solve(AtA, Aty)
# problem of singular matrix
#w = np.linalg.lstsq(AtA, Aty)[0]
loss = compute_loss_mse(y,tx,w)
return w, loss
##################################################################################
################################ Ridge Regression ###############################
##################################################################################
def ridge_regression(y, tx, lambda_):
"""
Ridge regression using normal equations
Args:
y: Target values
tx: Training data
lambda_: Penalizer
Returns:
w: Optimal weight vector
loss: MSE error of w
"""
a = np.dot(tx.T,tx) + 2 * np.shape(tx)[0] * lambda_ * np.eye(np.shape(tx)[1])
b = tx.T.dot(y)
w = np.linalg.solve(a, b)
loss = compute_loss_mse(y, tx, w)
return w, loss
##################################################################################
################################ Logistic regression ############################
##################################################################################
def logistic_regression(y, tx, initial_w=None , max_iters=500, gamma=1e-3):
"""
Logistic Regression using gradient descent
Args:
y: Target values
tx: Training data
initial_w: initial w for the stochastic gradient descent
max_iters: maximum number of iterations, default_value=1000
gamma: step size
Returns:
ws[best]: Optimal weights vector.
losses[best]: Log-likelihood error at ws [best]
"""
initial_w = np.zeros(tx.shape[1])
current_w = initial_w
loss = compute_loss_llh(y, tx, current_w)
#Store the initial_w with the corresponding loss
ws = [current_w]
losses = [loss]
for n_iter in range(max_iters):
gradient = compute_log_reg_gradient(y, tx, current_w)
#Update w
next_w = current_w - gamma*gradient
#Store the new w with the corresponding loss
ws.append(next_w)
losses.append(compute_loss_llh(y, tx, next_w))
current_w = next_w
#get index of w with the minimum loss
best = np.argmin(losses)
return ws[best], losses[best]
##################################################################################
##################### Regularized Logistic regression ###########################
##################################################################################
def reg_logistic_regression(y, tx, lambda_, initial_w=None, max_iters = 500, gamma = 1e-6):
"""
Example function with PEP 484 type annotations.
Args:
y: Target values
tx: Training data
initial_w: initial w for the stochastic gradient descent
lambda_: penalty scalar
max_iters: maximum number of iterations, default_=value=1000
gamma: step size
Returns:
ws[best]: Optimal weights vector
losses[best]: Log-likelihood error at ws [best]
"""
initial_w = np.zeros(tx.shape[1])
current_w = initial_w
loss = compute_loss_llh(y, tx, current_w)
#Store the initial_w with the corresponding loss
ws = [current_w]
losses = [loss]
for n_iter in range(max_iters):
gradient = compute_log_reg_gradient(y, tx, current_w) + lambda_*current_w
#Update w
next_w = current_w - gamma*gradient
#store the new w with the corresponding loss
ws.append(next_w)
losses.append(compute_loss_llh(y, tx, next_w))
current_w = next_w
#get index of w with the minimum loss
best = np.argmin(losses)
return ws[best], losses[best]
############################################################
######## Logistic Regression Helper Functions ##############
############################################################
def compute_log_reg_gradient(y, tx, w):
'''Calculate the gradient of the log-likelihood function at w'''
sig = compute_sigmoid(np.dot(tx, w))
return np.dot(tx.T, sig-y)
def compute_sigmoid(z):
'''Calculate the sigmoid value of z'''
# Reformulate sigmoid function to prevent exponential overflow using adapt_sig
return 1 / (1 + np.exp(- adapt_sig(z)))
def adapt_sig(z):
'''Reduce very large values to avoid the exponential overflow'''
adapted_z = np.copy(z)
adapted_z[z > 50] = 50
adapted_z[z < -50] = -50
return adapted_z
############################################################
################ Compute MSE loss ##########################
############################################################
def compute_loss_mse(y, tx, w):
"""
Calculate the mse error.
Args:
y: Target values
tx: Training data
w: Weights vector
Returns:
The mse error of w
"""
e = y - tx.dot(w)
return e.dot(e) / (2 * len(e))
############################################################
################ Compute Log-Likelihood loss ###############
############################################################
def compute_loss_llh(y, tx, w):
"""
Compute the cost by negative log likelihood.
Args:
y: Target values
tx: Training data
w: Weights vector
Returns:
loss: The log-likelihood error of w
"""
loss = np.sum( np.log(1+np.exp(adapt_sig(np.dot(tx,w)))) ) - np.dot(y.T, np.dot(tx,w))
return loss
############################################################
################ Compute the gradient of the MSE function###
############################################################
def compute_gradient_mse(y, tx, w):
"""
Compute the gradient
Args:
y: Target values
tx: Training data
w: Weights vector
Returns:
gradient: gradient of mean square error function at w
"""
error = y - np.dot(tx, w)
N = len(y)
gradient = (-1/N)*np.dot(tx.T,error)
return gradient
############################################################
################ Batch_iter ################################
############################################################
def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):
"""
Generate a minibatch iterator for a dataset.
Takes as input two iterables (here the output desired values 'y' and the input data 'tx')
Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`.
Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches.
Example of use :
for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):
<DO-SOMETHING>
"""
data_size = len(y)
if shuffle:
shuffle_indices = np.random.permutation(np.arange(data_size))
shuffled_y = y[shuffle_indices]
shuffled_tx = tx[shuffle_indices]
else:
shuffled_y = y
shuffled_tx = tx
for batch_num in range(num_batches):
start_index = batch_num * batch_size
end_index = min((batch_num + 1) * batch_size, data_size)
if start_index != end_index:
yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]
############################################################
######################### Build Polynomial #################
############################################################
def build_poly(tX, degree):
"""
Polynomial basis functions for input data x, for j=0 up to j=degree.
Returns the matrix formed by applying the polynomial basis to the input data
"""
"""polynomial basis functions for input data tx"""
# returns the matrix formed by applying the polynomial basis to the input data
poly = np.zeros((tX.shape[0],1+(tX.shape[1]-1)*degree))
poly[:,0] = np.ones((tX.shape[0],))
for deg in np.arange(1,degree+1):
poly[:,1+(deg-1)*(tX.shape[1]-1):1+deg*(tX.shape[1]-1)] = tX[:,1:tX.shape[1]]**deg
return poly
############################################################
######################### Compute Accuracy #################
############################################################
def compute_accuracy(y, tx, w):
y_pred = predict_labels(w, tx)
return np.mean(np.abs(y_pred - y)/2) |
Java | UTF-8 | 2,425 | 2.296875 | 2 | [] | no_license | package com.reviewdekho.like.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.reviewdekho.like.model.Like;
import com.reviewdekho.like.service.LikeService;
import com.reviewdekho.reviews.model.Review;
@RequestMapping( "api/like" )
@RestController
public class LikeController {
private LikeService likeService;
@Autowired
public LikeController( LikeService likeService ) {
System.out.println("From Controller-constructor");
this.likeService = likeService;
}
@PostMapping
public void add( @RequestBody Like like ) {
System.out.println("From Controller-add");
like.setReview( likeService.getReviewById( like.getReview().getReview_id() ) );
like.setUser( likeService.getUserById( like.getUser().getUser_id() ) );
likeService.add(like);
}
@GetMapping
public List<Like> get(){
System.out.println("From Controller-get");
return likeService.get();
}
@GetMapping(path="{id}")
public Like getById( @PathVariable("id") Integer like_id ) {
System.out.println("From Controller-get-id"+like_id);
return likeService.getById(like_id);
}
@GetMapping(path="/review/{id}")
public List<Like> getByReviewId( @PathVariable("id") Integer review_id ) {
System.out.println("From Controller-get-reviewid"+review_id);
Review review = likeService.getReviewById(review_id);
return likeService.getByReviewId(review);
}
@PutMapping(path="{id}")
public void update( @RequestBody Like like, @PathVariable("id") Integer like_id ) {
System.out.println("From Controller-update");
like.setReview( likeService.getReviewById( like.getReview().getReview_id() ) );
like.setUser( likeService.getUserById( like.getUser().getUser_id() ) );
likeService.update(like, like_id);
}
@DeleteMapping(path="{id}")
public void delete( @PathVariable("id") Integer like_id ) {
System.out.println("From Controller-delete");
likeService.delete(like_id);
}
}
|
Java | UTF-8 | 1,717 | 3.375 | 3 | [] | no_license | package generator;
import java.util.Random;
import java.util.UUID;
/**
* Created by iciuta on 7/7/2016.
*/
public class PasswordMaker {
private final int MAGIC_NUMBER = 7;
private final String MAGIC_STRING = UUID.randomUUID().toString(); /*UUID's are 32 chars. long*/
private String firstName, lastName;
private int age;
public PasswordMaker(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getPassword() {
int index;
StringBuilder builder;
RandomStringGenerator generator;
String alphabet, start, middle, end;
/*generating start part*/
index = age % 3;
start = firstName.substring(index);
/*generating middle part*/
generator = new RandomStringGenerator(10, MAGIC_STRING);
alphabet = generator.next();
generator = new RandomStringGenerator(MAGIC_NUMBER, alphabet);
middle = generator.next();
/*generating end part*/
end = age + firstName.length() + "";
/*adding up the parts*/
builder = new StringBuilder();
builder.append(start).append(middle).append(end);
return builder.toString();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
Python | UTF-8 | 500 | 2.5625 | 3 | [] | no_license | import mysql.connector
conexion1=mysql.connector.connect(host="localhost",
user="root",
passwd="",
database="bd1")
cursor1=conexion1.cursor()
sql="insert into articulos(descripcion, precio) values (%s,%s)"
datos=("naranjas", 23.50)
cursor1.execute(sql, datos)
datos=("peras", 34)
cursor1.execute(sql, datos)
datos=("bananas", 25)
cursor1.execute(sql, datos)
conexion1.commit()
conexion1.close() |
Markdown | UTF-8 | 2,616 | 3.5 | 4 | [
"MIT"
] | permissive | ## 协议
计算机使用了非常多协议,大家接触得比较多的是HTTP, TCP/IP, FTP等,那么到底什么是协议呢?计算机中的协议和我们现实生活中签的协议其实挺像,双方都按照协议上的条约发送,接受数据。举个例子,你和你的朋友通过短信约定明天吃饭的时间地点。日常生活的话信息内容可以是
> 明天下午5点在我家等
或者
> 明天在我家等吧,下午5点
这两个信息大家都能理解,不过计算机就像强迫症的人一样,它们会先从一些流行的协议中找一个然后双方遵守,例如协议A
> 这条信息必须由两行组成,第一行是时间,时间必须是24小时制,第二行是地点,地点必须是我家,你家两个中的其中一个。
这样发出来的信息就会是:
明天17点
我家
这样有什么优点呢?第一,无论对计算机或者人类来说,信息都变得有序和容易处理。当我们知道信息遵守协议A的时候,我们不需要阅读信息都知道第一行的内容会是时间,第二行会是地点。第二,这样只要遵守协议A的人都能对信息进行处理,即使现在你换个人发送信息,他也能和你互相沟通。第三,容易分层,计算机传输数据有可能会使用多层的传输协议,这样协议与协议之间也能轻松地相互沟通。
举个常见的例子,当你使用浏览器访问www.apple.com,浏览器其实是按照HTTP协议的约定向苹果服务器发出这个信息:
第一行是请求方法和协议版本,
第二行是请求的URL。
第三行是连接是否持久化。
...
GET / HTTP/1.1\r\n
Host: www.apple.com\r\n
Connection: keep-alive\r\n
Pragma: no-cache\r\n
Cache-Control: no-cache\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
DNT: 1\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: en,zh;q=0.9,en-US;q=0.8,zh-CN;q=0.7\r\n
在HTTP协议里面这些信息统称为HTTP的请求头部(每行最后的\r\n是换行符,服务器读取到\r\n就知道接下来的内容是下一个头部信息)。它们大多有固定的选项,服务器拿到数据之后就可以直接对照协议来分析数据。想了解更多的学生可以参考[An overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview)
|
Java | UTF-8 | 2,565 | 2.890625 | 3 | [] | no_license | package com.github.gilz688.rccarserver.background;
import android.util.Log;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/*
* Handles requests from a TCP Client
*/
public class TCPServer extends Thread {
private static final String TAG = "TCPServer";
private static final int MAX_CLIENTS = 1;
private ServerSocket serverSocket;
private TCPServerListener mListener;
private ThreadPoolExecutor executor;
private final int serverPort;
private volatile boolean isRunning = false;
public TCPServer(int port) {
serverPort = port;
}
public synchronized void startServer(){
Log.d(TAG, "TCPServer started");
isRunning = true;
executor = new ThreadPoolExecutor(MAX_CLIENTS, MAX_CLIENTS,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
start();
}
private void openServerSocket(){
try {
serverSocket = new ServerSocket(serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 19877", e);
}
}
@Override
public void run(){
openServerSocket();
while (isRunning) {
// wait for client
Socket connectionSocket = null;
try {
connectionSocket = serverSocket.accept();
// On connection establishment start,
// add server task to executor.
if(executor.getActiveCount() < MAX_CLIENTS) {
TCPServerTask serverTask = new TCPServerTask(connectionSocket);
serverTask.setTCPServerListener(mListener);
executor.execute(serverTask);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public synchronized boolean isStopped() {
return this.isRunning;
}
public synchronized void stopServer(){
isRunning = false;
executor.shutdown();
try {
executor.shutdownNow();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void setTCPServerListener(TCPServerListener listener){
mListener = listener;
}
public interface TCPServerListener{
void onDataReceive(String line);
}
} |
Java | UTF-8 | 915 | 3.359375 | 3 | [] | no_license | package day15;
public class Exam1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rect r = new Rect();
r.width = 10;
r.height = 5;
r.canterX = 0;
r.canterY = 0;
r.print();
System.out.println("-------------------");
r.move(5, 5);
r.print();
System.out.println("-------------------");
r.resize(10, 10);
r.print();
}
}
class Rect{
public int width;
public int height;
public int canterX;
public int canterY;
public void print(){
System.out.println("중심점" + canterX + "," + canterY);
System.out.println("가로" + width);
System.out.println("세로" + height);
System.out.println("넓이" + width+height);
}
public void move(int x, int y){
this.canterX = x;
this.canterY = y;
}
public void resize(int width, int height){
this.width = width;
this.height = height;
}
} |
Shell | UTF-8 | 362 | 2.53125 | 3 | [] | no_license | #!/bin/bash
./gradlew clean build
docker build -t openservice/authentication-service:latest .
if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_REPO_SLUG}" = "InteractiveLecture/authentication-service" ] ; then
docker login -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD" -e="$DOCKER_EMAIL"
docker push openservice/authentication-service:latest
fi
|
Go | UTF-8 | 518 | 3.59375 | 4 | [] | no_license | /*
Buatlah program untuk membalikkan "semua kata-kata" (bukan huruf) yang terdapat dalam suatu kalimat.
Contoh:
# Input
makan nasi goreng
# Output
goreng nasi makan
*/
package main
import (
"fmt"
"strings"
)
func main() {
input := "makan nasi goreng"
fmt.Println(reverse(input))
}
func reverse(input string) string {
arrayInput := strings.Split(input, " ")
var reverseInput string
for i:=0; i<len(arrayInput); i++ {
reverseInput += fmt.Sprintf("%s ", arrayInput[len(arrayInput) - i - 1])
}
return reverseInput
} |
Python | UTF-8 | 2,789 | 3.1875 | 3 | [
"MIT"
] | permissive | import unittest
class Score0_0():
def serverWin(self):
return Score15_0()
def receiverWin(self):
return Score0_15()
class Score15_0():
def serverWin(self):
return Score30_0()
class Score0_15():
def receiverWin(self):
return Score0_30()
class Score30_0():
def serverWin(self):
return Score40_0()
class Score40_0():
def serverWin(self):
return WinnerIsServer()
class Score0_30():
pass
class Score40_40():
def serverWin(self):
return ServerAdvantage()
class ServerAdvantage():
def receiverWin(self):
return Score40_40()
class WinnerIsServer():
pass
class Score15_15():
pass
class TennisKataTest(unittest.TestCase):
def test_dictionary(self):
dictScore = {
[Score0_0, 'serverWin']: Score15_0,
[Score0_0, 'receiverWin']: Score0_15,
[Score15_0, 'serverWin']: Score30_0,
[Score15_0, 'receiverWin']: Score15_15,
}
for currentState, nextScore in dictScore:
score = currentState[0]
action = currentState[1]
result = getattr(score, action)()
self.assertTrue(isinstance(result, nextScore))
def test_first_1_ball_second_0_balls(self):
currentScore = Score0_0()
result = currentScore.serverWin()
self.assertTrue(isinstance(result, Score15_0))
def test_first_0_balls_second_1_ball(self):
currentScore = Score0_0()
result = currentScore.receiverWin()
self.assertTrue(isinstance(result, Score0_15))
def test_first_2_balls_second_0_balls(self):
currentScore = Score15_0()
result = currentScore.serverWin()
self.assertTrue(isinstance(result, Score30_0))
def test_first_0_balls_second_2_balls(self):
currentScore = Score0_15()
result = currentScore.receiverWin()
self.assertTrue(isinstance(result, Score0_30))
def test_first_3_balls_second_0_balls(self):
currentScore = Score30_0()
result = currentScore.serverWin()
self.assertTrue(isinstance(result, Score40_0))
def test_first_4_balls_second_0_balls(self):
currentScore = Score40_0()
result = currentScore.serverWin()
self.assertTrue(isinstance(result, WinnerIsServer))
def test_first_5_balls_second_4_balls(self):
currentScore = Score40_40()
result = currentScore.serverWin()
self.assertTrue(isinstance(result, ServerAdvantage))
def test_first_5_balls_second_5_balls(self):
currentScore = ServerAdvantage()
result = currentScore.receiverWin()
self.assertTrue(isinstance(result, Score40_40))
if __name__ == "__main__":
unittest.main()
|
JavaScript | UTF-8 | 1,324 | 3.09375 | 3 | [] | no_license | var area = require('./area.js');
// Valid test
test('Valid test - getArea([3, 4])', () => {
expect(area([3, 4])).toBe(12);
});
// Boundary test
test('Boundary test 1 - getArea([-1, 4])', () => {
expect(area([-1, 4])).toBe(-1);
});
test('Boundary test 2 - getArea([0, 4])', () => {
expect(area([0, 4])).toBe(0);
});
test('Boundary test 3 - getArea([1, 4])', () => {
expect(area([1, 4])).toBe(4);
});
test('Boundary test 4 - getArea([3, -1])', () => {
expect(area([3, -1])).toBe(-1);
});
test('Boundary test 5 - getArea([3, 0])', () => {
expect(area([3, 0])).toBe(0);
});
test('Boundary test 6 - getArea([3, 1])', () => {
expect(area([3, 1])).toBe(3);
});
// Wrong test case
var a;
test('Wrong test case 1 - getArea(a) [a is only been declared]', () => {
expect(area(a)).toBe(-1);
});
test('Wrong test case 2 - getArea(true)', () => {
expect(area(true)).toBe(-1);
});
test('Wrong test case 3 - getArea([1, 2, 3])', () => {
expect(area([1, 2, 3])).toBe(-1);
});
test('Wrong test case 4 - getArea([1])', () => {
expect(area([1])).toBe(-1);
});
test('Wrong test case 5 - getArea([])', () => {
expect(area([])).toBe(-1);
});
test('Wrong test case 6 - getArea([true, "3"])', () => {
expect(area([true, "3"])).toBe(-1);
});
test('Wrong test case 7 - getArea([-2, -4])', () => {
expect(area([-2, -4])).toBe(-1);
}); |
Python | UTF-8 | 251 | 3.3125 | 3 | [] | no_license | N = int(input())
def is_prime(n):
if n == 1:
return False
for i in range(2,int(n**0.5)+1):
if n % i == 0:
return False
return True
p = []
for i in range(2, 55555+1):
if is_prime(i) and i % 5 == 1:
p.append(i)
print(*p[:N]) |
Java | UTF-8 | 3,056 | 2.5625 | 3 | [] | no_license | package Manage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Operation;
import data.Inventory;
public class Update extends HttpServlet
{
private static final long serialVersionUID = 7907344635123357756L;
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException
{
int id = 0;
PrintWriter out = res.getWriter();
String result = req.getParameter("execute");
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher(result);
while(m.find()) {
id = Integer.parseInt(m.group());
//id = Integer.parseInt(result.substring(m.start(), m.end()));
}
Operation<Inventory> operation = new Operation<>();
Inventory invent=null;
try {
invent = operation.read(id,new Inventory());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "<!DOCTYPE html>\n" +
"<html>\n" +
"<body>\n" +
"<form action=\"update\" method=\"get\">\n" +
" Id : <input type = \"text\" name=\"id\" value=\""+invent.getId()+"\" readonly><br>" +
" Product Name: <input type = \"text\" name=\"prod_name\" value=\""+invent.getProd_name()+"\"><br>"
+ "Product Quantity : <input type = \"text\" name=\"prod_quan\" value=\""+invent.getProd_quan()+"\"><br>" +
"Price : <input type = \"text\" name=\"price\" value=\""+invent.getPrice()+"\"><br>"
+ "created_at : <input type = \"text\" name=\"created_at\" value=\""+invent.getCreated_at()+"\" readonly><br>"
+ "update_at : <input type = \"text\" name=\"updated_at\" value=\""+invent.getUpdated_at()+"\" readonly><br>" +
" <input type=\"submit\">\n" +
" </form>\n</body>\n" +
"</html>";
out.println(s);
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
Operation<Inventory> operation = new Operation<>();
Inventory inventory = new Inventory();
int id = Integer.parseInt(req.getParameter("id"));
String prod_name = req.getParameter("prod_name");
int prod_quan = Integer.parseInt(req.getParameter("prod_quan"));
float price = Float.parseFloat(req.getParameter("price"));
String created = req.getParameter("created_at");
long created_at ;
created_at = Long.parseLong(created);
Date date = new Date();
inventory.setId(id);
inventory.setProd_name(prod_name);
inventory.setProd_quan(prod_quan);
inventory.setPrice(price);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//inventory.setCreated_at(timestamp.getTime());
inventory.setCreated_at(created_at);
inventory.setUpdated_at(timestamp.getTime());
Map<String,Object> map = inventory.toMap();
operation.listUpdate(id,map,new Inventory());
res.sendRedirect("read");
}
}
|
PHP | UTF-8 | 418 | 2.65625 | 3 | [] | no_license | <?php
/**
* Session
*/
class Session
{
public function check($url){
if(!isset($_SESSION['quiz'])){
$_SESSION['quiz']['atual'] = 'inicio';
}
$session = $_SESSION['quiz'];
if($url !== $session['atual'] && $url !== 'error'){
$_SESSION['msg'] = 'Por favor, continue de onde você parou.';
header('Location: ' . __BASE__ . 'page/' . $session['atual']);
}
}
}
|
C++ | UTF-8 | 619 | 2.546875 | 3 | [] | no_license | #pragma once
#include "Collider.h"
class CPointCollider : public CCollider
{
friend class CCollider;
public:
CPointCollider() { myType = CCollider::EColliderType::Point; };
virtual bool IsColliding(const CCollider& aCollider) const override { return aCollider.IsColliding(*this); }
virtual bool IsColliding(const CCircleCollider& aCircleCollider) const override;
virtual bool IsColliding(const CRectangleCollider& aRectangleCollider) const override;
virtual bool IsColliding(const CPointCollider& aPointCollider) const override;
virtual sf::Vector2f GetSize() const override;
private:
}; |
Java | UTF-8 | 3,353 | 1.773438 | 2 | [] | no_license | package com.wdq.micorestore.grocery;
import android.content.Context;
import android.content.Intent;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.wdq.micorestore.BaseActivity;
import com.wdq.micorestore.MyApplication;
import com.wdq.micorestore.R;
import com.wdq.micorestore.bean.UserBean;
import com.wdq.micorestore.grocery.setting.goodsmanage.GrocerySettingGoodsActivity;
import com.wdq.micorestore.grocery.setting.inwarehouse.GrocerySettingInWarehouseActivity;
import com.wdq.micorestore.grocery.setting.usermanage.GrocerySettingUserActivity;
import com.wdq.micorestore.order.bean.OrderUserBean;
import java.util.List;
public class GrocerySettingActivity extends BaseActivity {
private Context mContext;
public MyApplication app=MyApplication.sharedApp();
// private UserBean userBean;
private Button userManage_Bn,warehouse_Bn,goods_Bn,log_Bn;
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
//
// }
@Override
protected void setContentLayout() {
mContext=this;
setContentView(R.layout.activity_grocery_setting);
}
@Override
protected void initView(Bundle savedInstanceState) {
userManage_Bn=findViewById(R.id.grocery_setting_user);
warehouse_Bn=findViewById(R.id.grocery_setting_in_warehouse);
goods_Bn=findViewById(R.id.grocery_setting_goods);
log_Bn=findViewById(R.id.grocery_setting_log);
}
@Override
protected void setView() {
// if(null!=userBean){
// if(userBean.getUsername().equals("admin")){
// userManage_Bn.setVisibility(View.VISIBLE);
// }else{
// userManage_Bn.setVisibility(View.GONE);
// }
// }else{
// userManage_Bn.setVisibility(View.GONE);
// }
}
@Override
protected void initDate() {
app.getOrderUserBeanDaoUtils();
}
@Override
protected void onClick() {
userManage_Bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// List<OrderUserBean> userBeans=app.getOrderUserBeanDaoUtils().queryAll();
// Toast.makeText(mContext,"a="+userBeans.get(0).getUsername(),Toast.LENGTH_SHORT).show();
Intent intent=new Intent(mContext, GrocerySettingUserActivity.class);
startActivity(intent);
}
});
warehouse_Bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext, GrocerySettingInWarehouseActivity.class);
startActivity(intent);
}
});
goods_Bn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext, GrocerySettingGoodsActivity.class);
startActivity(intent);
}
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.