language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 324 | 1.578125 | 2 |
[] |
no_license
|
package com.my.hermes.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ReplyVO {
private int board_num;
private int reply_num;
private String user_id;
private String reply_content;
private String reply_inputdate;
}
|
Ruby
|
UTF-8
| 4,082 | 3.015625 | 3 |
[] |
no_license
|
require "json"
require "cinch"
require "spell"
require_relative "persistent_hash"
$word_list = PersistentHash.new
$annoyed = PersistentHash.new("annoyed")
$spell = Spell::Spell.new($word_list)
$bot = Cinch::Bot.new do
configure do |c|
config = JSON.parse(File.read("settings.json"))
fail "Upgrade to the new 'masters' format" if config["master"]
$masters = config["masters"].map { |x| x.downcase }
c.nick = config["nick"]
c.password = config["password"]
c.server = config["server"]
c.channels = config["channels"]
end
on :message, /^spell: (.+)/ do |m, sentence|
new_sentence = corrected_sentence(sentence, get_nicks(m))
if new_sentence == sentence.strip
m.reply "Looks good to me!"
else
m.reply "#{m.user.nick} meant to say \"#{new_sentence}\""
end
end
on :message, /^!!top(\d)/ do |m, num_top|
words_counts = $word_list.sort_by { |_, count| count }.last(num_top.to_i)
words_counts.reverse!
m.reply(words_counts.map { |set| "#{set.first}: #{set.last}" }.join(", "))
end
on :message, /^!!join (.*)/ do |m, channel_name|
channel_name = channel_name.strip
if master? m.user
channel = m.bot.join(channel_name)
if channel.nil?
m.reply "Could not join channel #{channel_name}"
else
m.reply "Joined #{channel_name}!"
end
else
m.reply "Why don't you join it, eh?"
end
end
on :message, /^!!part/ do |m|
if master? m.user
if m.channel?
m.channel.part("Goodbye, friends")
else
m.reply "How do you expect me to do that?"
end
else
m.reply "How about *you* go take a hike, eh?"
end
end
on :message, /^!!annoying/ do |m|
if master?(m.user) && m.channel?
annoy(m.channel)
m.reply "Now being annoying"
else
m.reply "How about you shut up?"
end
end
on :message, /^!!stop/ do |m|
if master?(m.user) && m.channel
unannoy(m.channel)
m.reply "Alright, OK."
else
m.reply "How about you stop being annoying, eh?"
end
end
on :message, /^!!add ((?:[\p{L}']+\s?)+)/ do |m, words|
if master? m.user
words.split(/\s/).map(&:downcase).each do |word|
if $word_list[word]
m.reply "I already know #{word}!"
else
$word_list[word] = 0
m.reply "Learned #{word}"
end
end
else
m.reply "How about *you* learn some vocabulary, eh?"
end
end
on :message, /^!!count ([\p{L}']+)/ do |m, word|
word = word.downcase
count = $word_list[word] || 0
m.reply "#{word} has been said #{count} times"
end
on :message, /(.*)/ do |m, sentence|
if m.channel && annoying?(m.channel)
unless sentence.match(/^spell:/)
new_sentence = corrected_sentence(sentence, get_nicks(m))
if new_sentence != sentence.strip
m.reply "#{m.user.nick} meant to say \"#{new_sentence}\""
end
end
end
sentence.split(/\s/).each do |given_word|
word = given_word.match(/[\p{L}']+/).to_s.downcase
$word_list[word] += 1 if $spell.spelled_correctly? word
end
end
helpers do
def annoy(channel)
$annoyed[channel] = true
end
def unannoy(channel)
$annoyed[channel] = false
end
def annoying?(channel)
$annoyed[channel] || false
end
def master?(user)
$masters.include? user.nick.downcase
end
def get_nicks(message)
if message.channel?
message.channel.users.keys.map { |user| user.nick }
else
[ message.user.nick ]
end
end
def corrected_sentence(sentence, nicks)
raw_new = sentence.split(/\s/).map do |given_word|
trimmed_word = given_word.match(/[\p{L}']+/).to_s.downcase
if trimmed_word.length < 2 or
$spell.spelled_correctly? trimmed_word or
nicks.map(&:downcase).include? trimmed_word
given_word
else
$spell.best_match(trimmed_word)
end
end
raw_new.join(" ")
end
end
end
|
C++
|
UTF-8
| 5,411 | 2.921875 | 3 |
[] |
no_license
|
#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
string arr[20];
int check[20][20];
int mem;
bool flag;
const int dx[] = { 1,0,-1,0 };
const int dy[] = { 0,1,0,-1 };
void solve(int y, int x, int dir, int count)
{
if (flag)
return;
char c = arr[y][x];
if (0 <= (c - '0') && (c - '0') < 10)
{
mem = (c - '0');
if (!check[y][x])
check[y][x] = mem;
if (x + dx[0] < 20)
solve(y + dy[0], x + dx[0], 0, count + 1);
else
solve(y + dy[0], 0, 0, count + 1);
}
else if (c == '>')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (x + dx[0] < 20)
solve(y + dy[0], x + dx[0], 0, count + 1);
else
solve(y + dy[0], 0, 0, count + 1);
}
else if (c == 'v')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (y + dy[1] < 20)
solve(y + dy[1], x + dx[1], 1, count + 1);
else
solve(0, x + dx[1], 1, count + 1);
}
else if (c == '<')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (x + dx[2] < 0)
solve(y + dy[2], 19, 2, count + 1);
else
solve(y + dy[2], x + dx[2], 2, count + 1);
}
else if (c == '^')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (y + dy[3] < 0)
solve(19, x + dx[3], 3, count + 1);
else
solve(y + dy[3], x + dx[3], 3, count + 1);
}
else if (c == '-')
{
mem--;
if (mem < 0)
mem = 15;
if (0 <= (y + dy[dir]) && (y + dy[dir]) < 20 && 0 <= (x + dx[dir]) && (x + dx[dir]) < 20)
solve(y + dy[dir], x + dx[dir], dir, count + 1);
else if (y + dy[dir] < 0)
solve(19, x + dx[dir], dir, count + 1);
else if (y + dy[dir] > 19)
solve(0, x + dx[dir], dir, count + 1);
else if (x + dx[dir] < 0)
solve(y + dy[dir], 19, dir, count + 1);
else if (x + dx[dir] > 19)
solve(y + dy[dir], 0, dir, count + 1);
}
else if (c == '+')
{
mem++;
if (mem > 15)
mem = 0;
if (0 <= (y + dy[dir]) && (y + dy[dir]) < 20 && 0 <= (x + dx[dir]) && (x + dx[dir]) < 20)
solve(y + dy[dir], x + dx[dir], dir, count + 1);
else if (y + dy[dir] < 0)
solve(19, x + dx[dir], dir, count + 1);
else if (y + dy[dir] > 19)
solve(0, x + dx[dir], dir, count + 1);
else if (x + dx[dir] < 0)
solve(y + dy[dir], 19, dir, count + 1);
else if (x + dx[dir] > 19)
solve(y + dy[dir], 0, dir, count + 1);
}
else if (c == '_')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (mem == 0)
{
if (x + dx[0] < 20)
solve(y + dy[0], x + dx[0], 0, count + 1);
else
solve(y + dy[0], 0, 0, count + 1);
}
else
{
if (x + dx[2] >= 0)
solve(y + dy[2], x + dx[2], 2, count + 1);
else
solve(y + dy[2], 19, 2, count + 1);
}
}
else if (c == '|')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (mem == 0)
{
if (y + dy[1] < 20)
solve(y + dy[1], x + dx[1], 1, count + 1);
else
solve(0, x + dx[1], 1, count + 1);
}
else
{
if (y + dy[3] >= 0)
solve(y + dy[3], x + dx[3], 3, count + 1);
else
solve(19, x + dx[3], 3, count + 1);
}
}
else if (c == '?')
{
if (check[y][x] == mem && count != 0)
{
flag = false;
return;
}
if (!check[y][x])
check[y][x] = mem;
if (x + dx[0] < 20)
solve(y + dy[0], x + dx[0], 0, count + 1);
else
solve(y + dy[0], 0, 0, count + 1);
if (y + dy[1] < 20)
solve(y + dy[1], x + dx[1], 1, count + 1);
else
solve(0, x + dx[1], 1, count + 1);
if (x + dx[2] < 0)
solve(y + dy[2], 19, 2, count + 1);
else
solve(y + dy[2], x + dx[2], 2, count + 1);
if (y + dy[3] < 0)
solve(19, x + dx[3], 3, count + 1);
else
solve(y + dy[3], x + dx[3], 3, count + 1);
}
else if (c == '.')
{
if (0 <= (y + dy[dir]) && (y + dy[dir]) < 20 && 0 <= (x + dx[dir]) && (x + dx[dir]) < 20)
solve(y + dy[dir], x + dx[dir], dir, count + 1);
else if (y + dy[dir] < 0)
solve(19, x + dx[dir], dir, count + 1);
else if (y + dy[dir] > 19)
solve(0, x + dx[dir], dir, count + 1);
else if (x + dx[dir] < 0)
solve(y + dy[dir], 19, dir, count + 1);
else if (x + dx[dir] > 19)
solve(y + dy[dir], 0, dir, count + 1);
}
else
{
flag = true;
return;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
freopen("input.txt", "r", stdin);
int T; cin >> T;
for (int cases = 1; cases <= T; ++cases)
{
flag = false;
memset(check, 0, sizeof(check));
mem = 0;
int R, C; cin >> R >> C;
for (int i = 0; i < R; ++i)
{
cin >> arr[i];
}
solve(0, 0, 0, 0);
cout << '#' << cases << ' ';
if (flag)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
return 0;
}
|
Java
|
UTF-8
| 310 | 1.78125 | 2 |
[
"MIT"
] |
permissive
|
package com.puboot.common.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "static")
public class StaticizeProperties {
private String accessPathPattern = "/html/**";
private String folder;
}
|
C++
|
UTF-8
| 909 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
#include "LED.h"
#include "Arduino.h"
#include "adp5350.h"
LED::LED(ADP5350 &adp, int ldo, int loop_speed): _adp(adp) {
_ldo = ldo;
_loop_speed = loop_speed;
_flashing = false;
_speed = 0;
_count = 1;
_status = false;
}
String LED::set(bool val) {
_adp.enableLDO(_ldo, val);
_status = val;
if (_status)
return "LED turned on";
else
return "LED turned off";
}
String LED::flash(bool flashing, float speed) {
_flashing = flashing;
_speed = speed;
if (!_flashing)
LED::set(false);
if (_flashing)
return "LED flashing started";
else
return "LED flashing stopped";
}
void LED::update() {
if (_flashing) { // flashes LED if necessary
int time_passed = _count * _loop_speed;
if (time_passed % (int)(_speed * 1000) == 0)
LED::set(!_status); // flip LED status
}
_count++;
}
|
Java
|
UTF-8
| 1,904 | 3.21875 | 3 |
[] |
no_license
|
package io.egen.rentalflix;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Service implementing IFlix interface
* You can use any Java collection type to store movies
*/
public class MovieService implements IFlix {
private ArrayList<Movie> list;
private HashMap<Integer, String> rentMovie;
public MovieService() {
list = new ArrayList<Movie>();
list.add(new Movie(1, 2008,"Batman Begins","English"));
list.add(new Movie(2, 2010,"The Dark Knight","English"));
list.add(new Movie(3, 2012,"The Dark Knight Rises","English"));
list.add(new Movie(4, 2016,"Batman vs Superman","English"));
list.add(new Movie(5, 2012,"Taare Zameen Par","Hindi"));
rentMovie = new HashMap<Integer,String>();
rentMovie.put(1,"SSHM");
}
@Override
public List<Movie> findAll() {
return list;
}
@Override
public List<Movie> findByName(String name) {
ArrayList<Movie> nameList = new ArrayList<Movie>();
for(int i=0; i<list.size();i++)
if(list.get(i).getTitle().equals(name))
nameList.add(list.get(i));
return nameList;
}
@Override
public Movie create(Movie movie) {
list.add(movie);
return movie;
}
@Override
public Movie update(Movie movie) {
for(int i=0; i<list.size();i++)
if(list.get(i).getId()==movie.getId())
{
list.set(i, movie);
return list.get(i);
}
throw new IllegalArgumentException();
}
@Override
public Movie delete(int id) {
for(int i=0; i<list.size();i++)
if(list.get(i).getId()==id)
{
Movie deletedMovie = list.get(i);
list.remove(i);
return deletedMovie;
}
throw new IllegalArgumentException();
}
@Override
public boolean rentMovie(int movieId, String user) {
if(rentMovie.containsKey(new Integer(movieId)))
{
throw new IllegalArgumentException();
}
rentMovie.put(new Integer(movieId), "User");
return true;
}
}
|
Markdown
|
UTF-8
| 5,174 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: 10,000 Words for 2021
category: "Rovani in C♯"
tags:
- writing
- goals
---
As the new year starts, so does a good time for a new set of goals. Having recently transferred from the delivery side of BlueBolt to the sales side (in a Sales Engineering capacity), I bring into the new year an ability to focus a lot more on my personal brand. It seems that year after year, I strive to write more; and damnit, this year I'm going to!
I have learned a lot after each attempt on what I need to set myself up for success. As with most anything I set my sights on, I need goals and a plan. 10,000 words is too broad of a goal to achieve on its own, but if I break it down into smaller posts, it comes across as manageable. The goal breaks down to at least 417 words per post, twice a month. Counting the words in this post, I am already {{ page.content | number_of_words | divided_by: 100.0 | round: 2 }}% of the way to my goal for the year!
Knowing how long each post is makes filling my quota feel achievable. The hardest part isn't in hitting word counts, though. If fact, I was a little surprised when I typed out a [stream of conscience]({% post_url 2017/2017-12-30-500-words %}) in 2017 that hitting 500 words is easily achievable. Figuring out _what_ to write is the hardest part for me. It's like cooking. I'm plenty good at creating food ad-hoc, but it'll be my go-to favorites. My culinary skills really shine when I have a recipe from which I can gain inspiration, modify to my audience's tastes, and plate a delicious meal. To have something to write about, I am going to focus on two different projects that I have been rattling around, trying to find a good reason to actually execute on my vision.
## Shopify App For Managing Webhooks
The stock UI to manage webhooks in Shopify is terrible. It's just a simple modal that lets you specify the topic, the URL to submit to, and the API version to use. There is a button to test the endpoint, but all it does is submit a test record - one that is incomplete and completely unreflective of content the store has. There are no options to pause or suspend the broadcast, only delete the entry. There is no logging of whether the call succeeded or failed, only that it was broadcast.
Since the Shopify Admin API allows for [managing webhooks](https://shopify.dev/docs/admin-api/rest/reference/events/webhook), an app can tap into a lot of information that the Shopify Admin doesn't surface. I wasn't able to find any apps already in the store that provide for this functionality, so I think I am onto something unique. I have a rough outline of the steps I want to take to have this reach its full functionality. Or if not fully functional, at least an MVP.
## Project Estimator, Possibly in Episerver CMS
BlueBolt's practices are split into roughly five different offerings: Shopify, Episerver CMS, Epi Commerce, Bravo Squared search solution, and an amalgamation of smaller projects - DNN, Salesforce, BigCommerce, Insite, etc. I have pretty well solidified my knowledge of what the backend of Shopify can do, what creative things we can massage out of the platform, and BlueBolt has some great talent for working with the front-end of Shopify. We also have world-class talent for Episerver; but this is a platform that I have been reticent to dedicate real time learning. In retrospect, I think mostly it has been because every Epi project seems to start completely from scratch... lots of stuff that has to be recreated, with slight tweaks for each and every project. I haven't been able to really find the enthusiasm to dive into the product because I haven't known what to build.
Related to this is that at BlueBolt, we piece together our estimates using a complex spreadsheet. Talking with my peers, this seems to be the way almost every agency does it. The spreadsheet gets more complex the larger and older the agency gets, until it reaches a point where no one knows who created it or why certain "features" are included. Explanations of _The Spreadsheet_ seems to include a lot of "but we don't use that" or "I don't ever change this". It is a fascinating peek into the odd bureaucracy that sneaks into the sales/estimation process.
So what if I take the spreadsheet and give it a similar UI, but store everything into a database? There is a laundry list of features that a spreadsheet inherently includes which would need to be added, but I think a basic, useful intro should be a great place to start. Of course, "starting" the project is going to back itself way the hell up into trying to find a better way to actual _start_ a project. More on that in the future.
## Timeline
Twice a month, I am going to publish a blog post. That's means two weeks per post. The first week will be for outline, research, proof-of-concept, and initial draft. The second week will be for editing, replaying the steps taken, and publishing. To keep myself interested, I think I will be alternating posts between the two projects or one post a month for project work and one post about running/family/non-coding topics.
Wish me luck, and please return often - hopefully once a fortnight!
|
JavaScript
|
UTF-8
| 8,804 | 2.953125 | 3 |
[] |
no_license
|
/* Рахівник калорійності страв 2.0
Визначити які функції знадобляться
*/
//При завантаженні сторінки або оновлені - заповнювати поля останнім рецептом.
//vars
const container = document.querySelector('.container');
const linesLive = document.getElementsByClassName('line');
const results = document.getElementById('results');
const resultsData = results.dataset;
const cookedWeightInput = document.querySelector('.cookedWeight');
const lineDiv = function() {
let div = document.createElement('div');
div.innerHTML =
`<div class="line" data-ts="${Date.now()}">
<input class="productName" />
<input class="calsFor100g" />
<input class="carbsFor100g" />
<input class="weight" />
<div class="totalCarbs"></div>
<div class="totalCals"></div>
<button class="removeLine"><i class="material-icons mi-clear">clear</i></button>
</div>`;
return div.firstElementChild.cloneNode(true);
};
let currentRecipe = {};
function loadLastFromStorage() {
currentRecipe = JSON.parse(localStorage.getItem('ccLastRecipe'));
}
function pagedataToRecipe() {
let lines = document.querySelectorAll('.line');
currentRecipe.cookedWt = cookedWeightInput.value;
let arr = [];
lines.forEach((line) => {
arr.push(lineToObject(line));
});
currentRecipe.lines = arr;
}
function lineToObject(line) {
let ln = {};
ln.nm = line.querySelector('.productName').value;
ln.kc = line.querySelector('.calsFor100g').value;
ln.cb = line.querySelector('.carbsFor100g').value;
ln.wt = line.querySelector('.weight').value;
return ln;
}
function loadRecipeFromStorage(recipeTS) {
console.log('from loadRecipeFromStorage');
if (typeof recipeTS == 'object'){
recipeTS = 'lastRecipe';
}
let recipe = localStorage.getItem(recipeTS);
let lines = JSON.parse(recipe);
lines.splice(0, 1);
recipe = fromStorageJSONtoObject(recipe);
//заповнюємо датасет на сторінці потрібною інфою.
Object.keys(recipe.info).forEach(key => resultsData[key.toLowerCase()] = recipe.info[key]);
lines.forEach(line => {
let div = arrayToLine(line);
addNewLineOnPage(div);
});
fromDatasetToFields();
changeOnPageHandler();
console.log(recipe);
}
function fromDatasetToFields() {
results.querySelector('.cookedWeight').value = results.dataset.cookedweight;
}
function saveLastRecipeToStorage() {
let lastRecipe;
lastRecipe = importantFieldsFromPage();
console.log(lastRecipe);
lastRecipe = fromObjectToJSONstorage(lastRecipe);
localStorage.setItem('lastRecipe', lastRecipe);
}
function fromStorageJSONtoObject(json) {
let ccLastRecipe = {
cookedWt: '',
rows: [{
nm: '',
kc: '',
cb: '',
wt: '',
},],
};
let recipeObject = {info:{}};
let array = JSON.parse(json);
recipeObject.info.timestamp = array[0][0] || '';
recipeObject.info.recipeName = array[0][1] || '';
recipeObject.info.cookedWeight = array[0][2] || '';
recipeObject.info.usageCounter = array[0][3] || '';
recipeObject.info.lastUsage = array[0][4] || '';
recipeObject.info.recipeText = array[0][5] || '';
recipeObject.info.calsFor100g = array[0][6] || '';
recipeObject.info.carbsFor100g = array[0][7] || '';
array.splice(0, 1);
array.forEach((line, index) => recipeObject[index] = line);
return recipeObject;
}
function fromObjectToJSONstorage(recipeObject) {
let json = [[]];
//не можемо просто запушити всі існуючі на resultsData елементи, бо нам потрібен чіткий порядок в масиві
json[0][0] = recipeObject.info.timestamp || '';
json[0][1] = recipeObject.info.recipeName || '';
json[0][2] = recipeObject.info.cookedWeight || '';
json[0][3] = recipeObject.info.usageCounter || '';
json[0][4] = recipeObject.info.lastUsage || '';
json[0][5] = recipeObject.info.recipeText || '';
json[0][6] = recipeObject.info.calsFor100g || '';
json[0][7] = recipeObject.info.carbsFor100g || '';
delete recipeObject.info;
for (let line in recipeObject) {
json.push(recipeObject[line]);
}
return JSON.stringify(json);
}
function recipeObjectToPage(recipeObject) {
//Заповнює всі потрібні форми з поля інфо, сортує лінії по номеру і ітерує по ним.
}
// function pageToRecipeObject() {
// let recipeObject = {};
// // Створюєм об"єкт, заносимо туди всі важливі поля і масиви, вертаємо.
// //forEach(lineToArray(div))
// console.log(linesLive);
// }
function importantFieldsFromPage() {
let object = {
info: {
timestamp: resultsData.timestamp || '',
cookedWeight: resultsData.cookedweight || '',
// recipeName: document.querySelector('.recipeName').value || '',
// usageCounter: document.querySelector('.usageCounter').value || '',
// lastUsage: document.querySelector('.lastUsage').value || '',
// recipeText: document.querySelector('.recipeText').value || '',
// calsFor100g: document.querySelector('.calsFor100g').value || '',
// carbsFor100g: document.querySelector('.carbsFor100g').value || '',
},
};
Array.from(linesLive).forEach((line, index) => object[index] = lineToArray(line));
return object;
}
function lineToArray(div) {
let array = [
// div.dataset.number,
div.querySelector('.productName').value,
div.querySelector('.calsFor100g').value,
div.querySelector('.carbsFor100g').value,
div.querySelector('.weight').value
];
return array;
}
function arrayToLine(array, div = lineDiv()) {
// div.dataset.number = array[0];
div.querySelector('.productName').value = array[0];
div.querySelector('.calsFor100g').value = array[1];
div.querySelector('.carbsFor100g').value = array[2];
div.querySelector('.weight').value = array[3];
return div;
}
function loadHistoryRecipies() {
}
//Зберігання рецепту в localStorage.
function saveRecipeToLocalStorage() {
}
//Додавання нової стоки в рецепті на сторінку.
function addNewLineOnPage(div = lineDiv()) {
container.appendChild(div.cloneNode(true));
}
function removeLineFromPage(div) {
div.remove();
}
function clickOnPageHandler(e) {
let classList = e.target.classList;
if (classList.contains('new-line')) {
let ts = +new Date();
let newDiv = lineDiv();
newDiv.dataset.number = ts;
addNewLineOnPage(newDiv);
changeOnPageHandler();
} else if (classList.contains('removeLine') || e.target.parentNode.classList.contains('removeLine')) {
removeLineFromPage(e.target.closest('.line'));
} else if (classList.contains('btn')) {
}
}
function changeOnPageHandler(e) {
let recipeObject = {info:{}};
let allWeight = 0;
let allCals = 0;
let allCarbs = 0;
Array.from(linesLive).forEach((lineDiv, index) => {
let array = countUpdateLine(lineDiv);
allWeight += +array[3];
allCarbs += +array[4];
allCals += +array[5];
recipeObject[index] = array;
});
recipeObject.info.allWeight = allWeight.toFixed(1);
recipeObject.info.allCarbs = allCarbs.toFixed(1);
recipeObject.info.allCals = allCals.toFixed(1);
document.querySelector('.allWeight').textContent = allWeight.toFixed(1);
document.querySelector('.allCarbs').textContent = allCarbs.toFixed(1);
document.querySelector('.allCals').textContent = allCals.toFixed(1);
saveLastRecipeToStorage();
}
function countUpdateLine(lineDiv) {
let productName = lineDiv.querySelector('.productName').value || '';
let calsFor100g = +lineDiv.querySelector('.calsFor100g').value || '';
let carbsFor100g = +lineDiv.querySelector('.carbsFor100g').value || '';
let weight = +lineDiv.querySelector('.weight').value || '';
let totalCarbs = lineDiv.querySelector('.totalCarbs').value || '';
let totalCals = lineDiv.querySelector('.totalCals').value || '';
totalCarbs = +(carbsFor100g * (weight / 100)).toFixed(1);
totalCals = +(calsFor100g * (weight / 100)).toFixed(1);
lineDiv.querySelector('.totalCarbs').textContent = totalCarbs;
lineDiv.querySelector('.totalCals').textContent = totalCals;
let array = [productName, calsFor100g, carbsFor100g, weight, totalCarbs, totalCals];
return array;
}
//eventListeners
// document.querySelector('.new-line').addEventListener('click', addNewLineOnPageHelper);
document.body.addEventListener('click', clickOnPageHandler);
document.body.addEventListener('input', changeOnPageHandler);
// document.body.addEventListener('input', saveLastRecipeToStorage);
document.addEventListener('DOMContentLoaded', loadRecipeFromStorage);
// document.body.addEventListener('load', loadLastRecipeFromStorage);
|
Java
|
UTF-8
| 2,992 | 1.945313 | 2 |
[] |
no_license
|
package obj_repository.inv_mngt;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class PickEditObj {
WebDriver webdriver;
By TxtBoxIDLocator = By.xpath(".//input[starts-with(@id, 'ContentPlaceHolder1_gv_EntitiesConfirm_gv_InvItems_0_txtBoxID_')]");
By TxtQtyLocator = By.xpath(".//input[starts-with(@id, 'ContentPlaceHolder1_gv_EntitiesConfirm_gv_InvItems_0_txtPickQTY_')]");
By TblSearchResultLocator = By.xpath(".//table[@id='ContentPlaceHolder1_gv_EntitiesConfirm_gv_InvItems_0']/tbody");
By TblPickingAreaSearchResultLocator = By.xpath(".//table[@id='ContentPlaceHolder1_gv_EntitiesConfirm']/tbody");
By BtnSaveLocator = By.xpath(".//input[@id='ContentPlaceHolder1_btnSave']");
By BtnYesLocator = By.xpath(".//input[@id='ContentPlaceHolder1_confirmDialogForPrintBox_cmdYes']");
By BtnNoLocator = By.xpath(".//input[@id='ContentPlaceHolder1_confirmDialogForPrintBox_cmdNo']");
By LblSuccessLocator = By.xpath(".//span[@id='ContentPlaceHolder1_lblSuccess']");
By ImageShowhideLocator = By.xpath(".//img[starts-with(@id, 'imgdiv')]");
public PickEditObj(WebDriver driver) {
super();
this.webdriver = driver;
}
public WebElement getBtnNo() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(BtnNoLocator);
return retEle;
}
public WebElement getImageShowhideLocation() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(ImageShowhideLocator);
return retEle;
}
public WebElement getLblSuccessLocation() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(LblSuccessLocator);
return retEle;
}
public WebElement getBtnYesLocation() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(BtnYesLocator);
return retEle;
}
public WebElement getTblPickingAreaSearchResultLocation() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(TblPickingAreaSearchResultLocator);
return retEle;
}
public List<WebElement> getTxtBoxIDs() throws NoSuchElementException {
List<WebElement> retEle = null;
retEle = webdriver.findElements(TxtBoxIDLocator);
return retEle;
}
public List<WebElement> getTxtQtys() throws NoSuchElementException {
List<WebElement> retEle = null;
retEle = webdriver.findElements(TxtQtyLocator);
return retEle;
}
public WebElement getTblSearchResultLocation() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(TblSearchResultLocator);
return retEle;
}
public WebElement getBtnSearchLocation() throws NoSuchElementException {
WebElement retEle = null;
retEle = webdriver.findElement(BtnSaveLocator);
return retEle;
}
public By getLblSuccessLocator() {
return LblSuccessLocator;
}
}
|
Ruby
|
UTF-8
| 288 | 3.515625 | 4 |
[] |
no_license
|
def hashes(name, option = {})
if option.empty?
puts "Hi, my name is #{name}"
else
puts "Hi, my name is #{name} and I'm #{option[:age]}" +
" years old and I live in #{option[:city]}."
end
end
hashes("Balaji")
hashes("Bala", {age: 23, city: "Virdhunagar"})
|
C
|
ISO-8859-2
| 979 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#include <stdlib.h>
/*
Suponha que um caixa disponha apenas de cdulas de R$ 100, 10 e 1. Escreva um programa para ler o
valor de uma conta e o valor fornecido pelo usurio para pagar essa conta, e calcule e troco.
Calcular e mostrar a quantidade de cada tipo de cdula que o caixa deve fornecer como troco.
Mostrar, tambm o valor da compra e do troco.
*/
int main (void)
{
long int Nota100, Nota10, Nota1, Conta, ValorF, Troco;
printf("Informe o valor da conta a ser paga: ");
scanf("%li",&Conta);
printf("Informe o valor pago pelo devedor: ");
scanf("%li",&ValorF);
Troco = ValorF-Conta;
Nota100 = Troco/100;
Nota10 = (int)Troco%100/10;
Nota1 = (int)Troco%100%10;
printf("O valor total de troco e de: %li\n",Troco);
printf("Total de notas de 100 reais: %li\n",Nota100);
printf("Total de notas de 10 reais: %li\n",Nota10);
printf("Total de notas de 1 real: %li\n",Nota1);
system("pause");
}
|
Shell
|
UTF-8
| 613 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
export PACKET_PROJECT_ID=746ea6dd-1e0a-4126-89d6-728784671fbf
export DEVICE_HOSTNAME=osie-test-{{plan | replace("_", "-") | replace(".", "-")}}-{{os | replace("_", "-")}}
export DEVICE_PLAN={{plan}}
export DEVICE_FACILITY={{facility}}
export DEVICE_IPXE_SCRIPT_URL=http://blob1-nrt1.packet.net/osie-testing/{{v}}/{{plan}}-{{os}}.ipxe
sleep_secs=$(((RANDOM % 7)*5))
echo "$DEVICE_HOSTNAME: sleeping for $sleep_secs"
sleep $sleep_secs
date | sed "s|^|$DEVICE_HOSTNAME: |"
if python2 ../../ci/drone/tester.py; then
touch test-{{plan}}-{{os}}.success
else
touch test-{{plan}}-{{os}}.failed
fi
|
Java
|
UTF-8
| 2,427 | 2.328125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package myBean;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
/**
*
* @author my pc
*/
@Named(value = "job")
@SessionScoped
public class job implements Serializable {
private String title,keywords,description;
private int id,payment,jobstatus,providerId,freelancerId;
// BEANS MUST HAVE AN EMPTY CONSTRUCTOR WITH NO PARAMETERS
public job(int id,String title,String keywords,String description,int payment,int jobstatus,int providerId, int freelancerId){
this.title=title;
this.keywords=keywords;
this.description=description;
this.id=id;
this.payment=payment;
this.jobstatus=jobstatus;
this.providerId=providerId;
this.freelancerId=freelancerId;
}
public job(){
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String openGig()
{
return "gig";
}
//Getters
public int getId(){
return id;
}
public String getTitle(){
return title;
}
public String getKeywords(){
return keywords;
}
public String getDescript(){
return description;
}
public int getPayment(){
return payment;
}
public int getJobstatus(){
return jobstatus;
}
public int getProviderId(){
return providerId;
}
// //Setters
public void setTitle(String title) {
this.title = title;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public void setId(int id) {
this.id = id;
}
public void setPayment(int payment) {
this.payment = payment;
}
public void setJobstatus(int jobstatus) {
this.jobstatus = jobstatus;
}
public void setProviderId(int providerId) {
this.providerId = providerId;
}
public void setFreelancerId(int freelancerId) {
this.freelancerId = freelancerId;
}
public int getFreelancerId(){
return freelancerId;
}
}
|
PHP
|
UTF-8
| 1,506 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cache;
/**
* Class PaymentStatus
* Model Table Referencing payment_status
*/
define('CACHE_PARAM_PAYMENT_STATUS', 'payment_status');
class PayStatus extends Model
{
protected $table = 'payment_status';
public $timestamps = false;
/**
* Get USer Status
*/
public static function status($key = '')
{
$payment_statuses = Cache::get(CACHE_PARAM_PAYMENT_STATUS, null);
if (is_null($payment_statuses)) {
$payment_status = self::all();
$payment_statuses = [];
foreach ($payment_status as $status) {
$payment_statuses[strtoupper($status->name)] = $status->id;
}
Cache::put(CACHE_PARAM_PAYMENT_STATUS, $payment_statuses, 43200);
}
return empty($key) ? $payment_statuses : $payment_statuses[$key];
}
/**
* Active User Status
*/
public static function PENDING()
{
return self::status('PENDING');
}
/**
* Inactive User Status
*/
public static function SUCCESS()
{
return self::status('SUCCESS');
}
/**
* Pending User Status
*/
public static function FAILURE()
{
return self::status('FAILURE');
}
}
|
Python
|
UTF-8
| 9,756 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# Copyright (c) 2014-2016 Adrian Rossiter <adrian@antiprism.com>
# 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.
'''
Twist polygons, of the same type, placed on certain fixed axes and
joined by vertices.
'''
import argparse
import sys
import os
import math
import anti_lib
from anti_lib import Vec, Mat
epsilon = 1e-13
def make_arc(v0, v1, num_segs, start_idx):
axis = Vec.cross(v0, v1).unit()
ang = anti_lib.angle_around_axis(v0, v1, axis)
points = [v0]
faces = []
mat = Mat.rot_axis_ang(axis, ang/num_segs)
for i in range(num_segs):
# accumulated error
points.append(mat * points[-1])
faces.append([start_idx + i, start_idx + i+1])
return points, faces
def make_frame(frame_elems, pgon, axis_angle, num_segs):
points = []
faces = []
if frame_elems:
v0 = Vec(0, 0, 1)
v1 = Vec(-math.sin(axis_angle), 0, math.cos(axis_angle))
v2 = v1.rot_z(pgon.angle()/2)
v2[2] *= -1
if 'r' in frame_elems:
ps, fs = make_arc(v0, v1, num_segs, 0)
points += ps
faces += fs
ps, fs = make_arc(v1, v2, num_segs, num_segs+1)
points += ps
faces += fs
if 'a' in frame_elems:
faces += [[len(points)+i, len(points)+i+1] for i in range(0, 6, 2)]
points += [v0, -v0, v1, -v1, v2, -v2]
rad = calc_polygons(pgon, 0, axis_angle, -1)[0][0].mag()
points = [rad * p for p in points]
faces += [[i] for i in range(len(points))]
return points, faces
def calc_polygons(pgon, ang, angle_between_axes, sign_flag=1):
# rotate initial vertex of first polygon by ang. Common
# point lies on a line through vertex in the direction
# of first axis (z-axis). Common point lies on a cylinder
# with the circumradius for radius and second axis for axis.
# rotate model so axis1 is on z-axis, to simplify the
# calculation of the intersection
rot = Mat.rot_axis_ang(Vec(0, 1, 0), angle_between_axes)
R = pgon.circumradius()
V = Vec(R, 0, 0).rot_z(ang) # initial vertex turned on axis
Q = rot * V # vertex in rotated model
u = rot * Vec(0, 0, 1) # direction of line in rotated model
# equation of line is P = Q + tu for components x y z and parameter t
# equation of cylinder at z=0 is x^2 + y^2 = r1^2
a = u[0]**2 + u[1]**2
b = 2*(Q[0]*u[0] + Q[1]*u[1])
c = Q[0]**2 + Q[1]**2 - R**2
disc = b**2 - 4*a*c
if disc < -epsilon:
raise Exception("model is not geometrically constructible")
elif disc < 0:
disc = 0
# The sign flag, which changes for the range 90 to 270 degrees, allows
# the model to reverse, otherwise the model breaks apart in this range.
t = (-b + sign_flag*math.sqrt(disc))/(2*a)
P = V + Vec(0, 0, t) # the common point
points = pgon.get_points(P)
faces = pgon.get_faces()
Q = rot * P
rot_inv = Mat.rot_axis_ang(Vec(0, 1, 0), -angle_between_axes)
points += [rot_inv*p for p in pgon.get_points(Q)]
faces += pgon.get_faces(pgon.N*pgon.parts)
return points, faces
def rot_reflect_pair(points, pgon, d, rev=False):
mat0 = Mat.rot_axis_ang(Vec(0, 0, 1), (d+0.5)*pgon.angle())
pts = [mat0 * Vec(p[0], p[1], -p[2]) for p in points]
mat1 = Mat.rot_axis_ang(Vec(0, 0, 1), d*pgon.angle())
if rev:
return [mat1 * p for p in points]+pts
else:
return pts + [mat1 * p for p in points]
def frame_type(arg):
if arg.strip('ra'):
raise argparse.ArgumentTypeError(
'frame type contains letters other than r, a')
return arg
def read_turn_angle(ang_str):
if ang_str[-1] == 'e':
ang_type = 'e'
ang_str = ang_str[:-1]
elif ang_str[-1] == 'x':
ang_type = 'x'
ang_str = ang_str[:-1]
else:
ang_type = 'd'
try:
ang_val = float(ang_str)
except ValueError as e:
raise argparse.ArgumentTypeError(
'invalid numeric value: ', e.args[0])
return [ang_val, ang_type]
def main():
"""Entry point"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'polygon',
help='number of sides of polygon (default: 7) '
'(or may be a polygon fraction, e.g. 5/2)',
type=anti_lib.read_polygon,
nargs='?',
default='7')
parser.add_argument(
'turn_angle',
help='amount to turn polygon on axis0 in degrees '
'(default (0.0), or a value followed by \'e\', '
'where 1.0e is half the central angle of an edge, '
'which produces an edge-connected model (negative '
'values may have to be specified as, e.g. -a=-1.0e),'
'or a value followed by x, which is like e but with '
'a half turn offset',
type=read_turn_angle,
nargs='?',
default='0')
parser.add_argument(
'-n', '--number-faces',
help='number of faces in output (default: all): '
'0 - none (frame only), '
'2 - cap and adjoining polygon'
'4 - two caps and two adjoining connected polygons',
type=int,
choices=[0, 2, 4],
default=-1)
parser.add_argument(
'-F', '--frame',
help='include frame elements in output, any from: '
'r - rhombic tiling edges, '
'a - rotation axes (default: no elements)',
type=frame_type,
default='')
parser.add_argument(
'-o', '--outfile',
help='output file name (default: standard output)',
type=argparse.FileType('w'),
default=sys.stdout)
args = parser.parse_args()
pgon = args.polygon
N = pgon.N
D = pgon.D
parts = pgon.parts
# if N % 2 == 0:
# parser.error('polygon: %sfraction numerator must be odd' %
# ('reduced ' if parts > 1 else ''))
if D % 2 == 0:
print(os.path.basename(__file__)+': warning: '
'polygon: %sfraction denominator should be odd, '
'model will only connect correctly at certain twist angles' %
('reduced ' if parts > 1 else ''),
file=sys.stderr)
if abs(N/D) < 3/2:
parser.error('polygon: the polygon fraction cannot be less than 3/2 '
'(base rhombic tiling is not constructible)')
axis_angle = math.acos(1/math.tan(
math.pi*D/N)/math.tan(math.pi*(N-D)/(2*N)))
if args.turn_angle[1] == 'e': # units: half edge central angle
turn_angle = args.turn_angle[0] * pgon.angle()/2
elif args.turn_angle[1] == 'x': # units: half edge central angle
turn_angle = math.pi + args.turn_angle[0] * pgon.angle()/2
else: # units: degrees
turn_angle = math.radians(args.turn_angle[0])
turn_angle_test_val = abs(math.fmod(abs(turn_angle), 2*math.pi) - math.pi)
sign_flag = 1 - 2*(turn_angle_test_val > math.pi/2)
try:
(points, faces) = calc_polygons(pgon, turn_angle, axis_angle,
sign_flag)
except Exception as e:
parser.error(e.args[0])
if args.number_faces < 0:
num_twist_faces = (2*N + 2)*parts
else:
num_twist_faces = args.number_faces*parts
num_twist_points = num_twist_faces * N
frame_points, frame_faces = make_frame(args.frame, pgon, axis_angle, 10)
if num_twist_points + len(frame_points) == 0:
parser.error('no output specified, use -f with -n 0 to output a frame')
if D % 2 == 0:
mat = Mat.rot_axis_ang(Vec(0, 0, 1), math.pi/N)
points = [mat * p for p in points]
out = anti_lib.OffFile(args.outfile)
out.print_header(num_twist_points+2*N*len(frame_points),
num_twist_faces+2*N*len(frame_faces))
if args.number_faces == -1:
out.print_verts(rot_reflect_pair(points[:N*parts], pgon, 0, True))
for i in range(N):
out.print_verts(rot_reflect_pair(points[N*parts:], pgon, i))
elif args.number_faces == 2:
out.print_verts(points)
elif args.number_faces == 4:
out.print_verts(rot_reflect_pair(points[:N*parts], pgon, 0, True),)
out.print_verts(rot_reflect_pair(points[N*parts:], pgon, 0))
for i in range(N):
out.print_verts(rot_reflect_pair(frame_points, pgon, i))
for i in range(num_twist_faces):
out.print_face(faces[0], i*N, (i//parts) % 2)
for i in range(N):
cur_num_points = num_twist_points + 2*i*len(frame_points)
for j in [0, len(frame_points)]:
out.print_faces(frame_faces, cur_num_points+j, col=2)
if __name__ == "__main__":
main()
|
Java
|
UTF-8
| 279 | 2.9375 | 3 |
[] |
no_license
|
package com.javaex.practice;
public class Ex08 {
public static void main(String[] args) {
int x, y = 0;
char grade = 'A'; // 작은 따음표 사용
int salary = 2000000; //숫자만 사용
int n = 1000; //128 이상이므로 int 사용
}
}
|
C++
|
UTF-8
| 365 | 2.765625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
int i=0;
char znak;
system("cls");
printf("Podaj litere: ");
scanf("%c",&znak);
if(znak>='a' and znak<='z')
{
printf("%4c\n",znak-32);
}
if(znak>='A' and znak<='Z')
{
printf("%4c\n",znak+32);
}
system("pause");
return 0;
}
|
C#
|
UTF-8
| 2,797 | 2.90625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ActorDemo.ActorSystem {
//两种方式
//一种,类似Unity的Update,一直执行发送,接收事件的方法,内部处理
//一种,就是现在这个,我发消息,对方才执行处理方法,处理完所有消息,就不占用线程资源
public class Dispatcher {
private static Dispatcher instance;
public static Dispatcher Instance {
get { return instance ?? ( instance = new Dispatcher() ); }
}
private Dictionary<string, IActor> actorDict = new Dictionary<string, IActor>();
public bool Register( string name, IActor actor ) {
IActor ac;
if( actorDict.TryGetValue( name, out ac ) ) {
//已存在
return false;
}
actor.Name = name;
actorDict[name] = actor;
return true;
}
public void UnRegister( string name ) {
if( actorDict.ContainsKey( name ) ) {
actorDict.Remove( name );
}
}
//skynet send call
//发消息写到了外面,从Actor里拿出来了
public void Send( MsgData message, string actorName ) {
IActor actor;
if( actorDict.TryGetValue( actorName, out actor ) ) {
if( actor.Exited )
return;
actor.Enqueue( message );
ReadyToExecute( actor );
}
}
private void ReadyToExecute( IActor actor ) {
if( actor.Exited )
return;
//Status和WAITING比较,相等就用EXECUTING替换Status
int status = Interlocked.CompareExchange( ref actor.Context.Status, ActorContext.EXECUTING, ActorContext.WAITING );
if( status == ActorContext.WAITING ) {
//将方法排入队列以便执行,并指定包含该方法所用数据的对象。 此方法在有线程池线程变得可用时执行
ThreadPool.QueueUserWorkItem( Execute, actor );
}
}
private void Execute( object o ) {
IActor actor = (IActor)o;
actor.Dequeue();
if( actor.Exited ) {
Thread.VolatileWrite( ref actor.Context.Status, ActorContext.EXITED );
}
else {
Thread.VolatileWrite( ref actor.Context.Status, ActorContext.WAITING );
if( actor.MessageCount > 0 ) {
ReadyToExecute( actor );
}
}
}
}
}
|
C++
|
UTF-8
| 543 | 2.796875 | 3 |
[] |
no_license
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int k, n;
cin >> k >> n;
long long low = 1;
long long high = 0;
vector<long long> v(k, 0);
for (int i = 0; i < k; ++i) {
cin >> v[i];
high = max(high, v[i]);
}
long long res = 0;
while (low <= high) {
long long mid = (low + high) / 2;
int sum = 0;
for (int num : v) {
sum += num / mid;
}
if (sum >= n) {
res = max(res, mid);
low = mid + 1;
} else {
high = mid - 1;
}
}
cout << res << endl;
return 0;
}
|
Java
|
UTF-8
| 1,123 | 3.15625 | 3 |
[] |
no_license
|
package funtions;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
* Function for showing the image Tiff as an ImageIcon
*
* @author Yolanda
*
*/
public class ShowTiff {
private static int width = 700;
private static int height = 700;
/**
* For showing a tiff image in the interface transform it to an imageicon since
* otherwise it won't appear
*
* @param path The path of the image tiff image to show
* @return an imageIcon with the tiff image
*/
public static ImageIcon showTiffToImageIcon(String path) {
BufferedImage image = null;
try {
File f = new File(path);
image = ImageIO.read(f);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error while trying to show the tiff file", "Error saving",
JOptionPane.ERROR_MESSAGE);
}
ImageIcon imaIco = new ImageIcon(image);
ImageIcon iconoEscala = new ImageIcon(
imaIco.getImage().getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT));
return iconoEscala;
}
}
|
Java
|
UTF-8
| 1,783 | 2.46875 | 2 |
[] |
no_license
|
package HibernateProyect.HibernateProyect.modelo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="C_AUD")
public class Coche {
@Id
@GeneratedValue
@Column(name ="C_ID")
private int idCoche;
@Column(name = "C_MAR",nullable = false, length = 100)
private String marca;
@Column(name = "C_MOD",nullable = false, length = 100)
private String modelo;
@Column(name = "C_COL",nullable = false, length = 150)
private String color;
@Column(name = "C_MAT", nullable = false, length = 50)
private String matricula;
@Column(name = "C_TIP", nullable = false, length = 200)
private String tipo;
@Column(name = "C_EST",nullable = false)
@Enumerated
private EstadoCoche estadoCoche;
public Coche() {
}
public int getIdCoche() {
return idCoche;
}
public void setIdCoche(int idCoche) {
this.idCoche = idCoche;
}
public void setEstadoCoche(EstadoCoche estadoCoche) {
this.estadoCoche = estadoCoche;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public EstadoCoche getEstadoCoche() {
return estadoCoche;
}
}
|
C#
|
UTF-8
| 3,388 | 3 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BP13Exercise2
{
public partial class Form1 : Form
{
bool operatorStatus = false;
double result = 0;
char operation;
public Form1()
{
InitializeComponent();
}
private void NumEvents(object sender, EventArgs e)
{
if (textBox1.Text == "0" || operatorStatus)
textBox1.Clear();
operatorStatus = false;
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void MathOperations(object sender, EventArgs e)
{
operatorStatus = true;
Button btn = (Button)sender;
char newOperation = Char.Parse(btn.Text);
label1.Text = label1.Text + " " + textBox1.Text + " " + newOperation;
switch (operation)
{
case '+': textBox1.Text = (result + Double.Parse(textBox1.Text)).ToString();
break;
case '-':
textBox1.Text = (result - Double.Parse(textBox1.Text)).ToString();
break;
case '*':
textBox1.Text = (result * Double.Parse(textBox1.Text)).ToString();
break;
case '/':
textBox1.Text = (result / Double.Parse(textBox1.Text)).ToString();
break;
}
result = double.Parse(textBox1.Text);
textBox1.Text = result.ToString();
operation = newOperation;
}
private void Button5_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
}
private void Button6_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
label1.Text = "";
operation = ' ';
result = 0;
operatorStatus = false;
}
private void Button11_Click(object sender, EventArgs e)
{
operatorStatus = true;
label1.Text = "";
switch (operation)
{
case '+':
textBox1.Text = (result + Double.Parse(textBox1.Text)).ToString();
break;
case '-':
textBox1.Text = (result - Double.Parse(textBox1.Text)).ToString();
break;
case '*':
textBox1.Text = (result * Double.Parse(textBox1.Text)).ToString();
break;
case '/':
textBox1.Text = (result / Double.Parse(textBox1.Text)).ToString();
break;
}
result = double.Parse(textBox1.Text);
textBox1.Text = result.ToString();
operation = ' ';
}
private void Button13_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
textBox1.Text = "0";
else if (operatorStatus)
textBox1.Text = "0";
if (!textBox1.Text.Contains(","))
textBox1.Text += ".";
operatorStatus = false;
}
}
}
|
C#
|
UTF-8
| 2,529 | 4.03125 | 4 |
[] |
no_license
|
public static class MyExtensions
{
/// <summary>
/// Sets an individual bit inside a byte, based on the bit number.
/// </summary>
/// <param name="aByte">The byte where a bit is to be changed.</param>
/// <param name="bitNumber">The bit number to read (between 0 and 7).</param>
/// <param name="value">The value to set the bit to. 0/False or 1/True.</param>
/// <returns>A byte with the requested bit changed.</returns>
/// <remarks>The bit number must be between 0 and 7, otherwise an ArgumentOutOfRangeException is thrown.</remarks>
public static byte SetBit(this byte aByte, byte bitNumber, bool value)
{
if (bitNumber > 7) { throw new ArgumentOutOfRangeException("bitNumber", "bitNumber was > 7"); }
// create a mask of zeros except for the bit we want to modify
byte mask = 1;
mask = (byte)(mask << bitNumber);
if (value)
{
// use bitwise-inclusive-or operator to make sure the bit equals 1 (and nothing else is changed)
aByte = (byte)(aByte | mask);
}
else
{
// grab the inverse of our original mask (all ones except our bit equals zero)
mask = (byte)(byte.MaxValue - mask);
// use bitwise-and operator to make sure our bit equals 0 (and nothing else is changed)
aByte = (byte)(aByte & mask);
}
return aByte;
}
/// <summary>
/// Returns the value of an individual bit from within a byte.
/// </summary>
/// <param name="aByte">The byte from which to return bit data.</param>
/// <param name="bitNumber">The bit number to read (between 0 and 7).</param>
/// <returns>The value inside the requested bit. 0/False or 1/True.</returns>
/// <remarks>The bit number must be between 0 and 7, otherwise an ArgumentOutOfRangeException is thrown.</remarks>
public static bool GetBit(this byte aByte, byte bitNumber)
{
if (bitNumber > 7) { throw new ArgumentOutOfRangeException("bitNumber", "bitNumber was > 7"); }
// create a mask of zeros except for the bit we want to modify
byte mask = 1;
mask = (byte)(mask << bitNumber);
// use bitwise-and operator with our mask; if we get a 1, our bit must have also been a 1
return (aByte & mask) > 0;
}
}
|
C#
|
UTF-8
| 4,197 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration.Configuration;
namespace ImPinker.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "用户名")]
public string UserName { get; set; }
}
public class ManageUserViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "当前密码")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "新密码")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "确认新密码")]
[Compare("NewPassword", ErrorMessage = "新密码和确认密码不匹配。")]
public string ConfirmPassword { get; set; }
}
public class LoginViewModel
{
[Required]
[Display(Name = "用户名")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Password { get; set; }
[Display(Name = "记住我?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[Display(Name = "用户名")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
public string ConfirmPassword { get; set; }
[Required]
[StringLength(11, ErrorMessage = "{0} 长度不符合规范。", MinimumLength = 11)]
[DataType(DataType.PhoneNumber)]
[Display(Name = "手机号")]
public string PhoneNum { get; set; }
[Required]
[Display(Name = "验证码")]
public string CheckNum { get; set; }
}
/// <summary>
/// 注册时手机验证码验证
/// </summary>
public class CheckNumModel
{
/// <summary>
/// 手机号
/// </summary>
public string PhoneNum { get; set; }
/// <summary>
/// 验证码
/// </summary>
public string CheckNum { get; set; }
/// <summary>
/// 验证码发送时间
/// </summary>
public DateTime SendTime { get; set; }
/// <summary>
/// 用户请求的ip地址。防止恶意注册
/// </summary>
public string IpAddress { get; set; }
}
/// <summary>
/// 找回密码vm
/// </summary>
public class FindPassWordViewModel
{
[Required]
[StringLength(11, ErrorMessage = "{0} 长度不符合规范。", MinimumLength = 11)]
[DataType(DataType.PhoneNumber)]
[Display(Name = "手机号")]
public string PhoneNum { get; set; }
[Required]
[Display(Name = "验证码")]
public string CheckNum { get; set; }
}
/// <summary>
/// 找回密码vm
/// </summary>
public class FindPassWordNewPassViewModel
{
[Required]
[StringLength(11, ErrorMessage = "{0} 长度不符合规范。", MinimumLength = 11)]
[DataType(DataType.PhoneNumber)]
[Display(Name = "手机号")]
public string PhoneNum { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "新密码")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
public string ConfirmPassword { get; set; }
}
}
|
PHP
|
UTF-8
| 389 | 3.40625 | 3 |
[] |
no_license
|
<?php
// Produtos
$omega_3 = 58;
$dipirona = 2;
$sacolas = 5;
echo "Valor sem desconto: ".$total = ($omega_3 + $dipirona + $sacolas);
echo "<br>";
if(($total > 50) and ($total < 60))
{
$discount = 20;
$total = $total * (100 - $discount) / 100;
}elseif ($total > 60) {
$discount = 30;
$total = $total * (100 - $discount) / 100;
}
echo "Total com desconto: ".$total;
|
Markdown
|
UTF-8
| 2,588 | 2.921875 | 3 |
[] |
no_license
|
Quattor Web Site
================
The site is hosted through GitHub pages and can be modified by cloning this
repository, making changes, and pushing the changes back into the repository.
Generally, you should only add new articles to the \_posts subdirectory or one
of the documentation category (directory starting by \_ with an explicit name
matching one of the documnetation category in the Documentation page. All the
changes to the web site must be submitted as a pull request to allow a peer
review of the changes. No change must be merged by the author.
Guidelines for Content
----------------------
The naming scheme for the items in the __posts subdirectory is the date,
followed by the category (`news` or `documentation`), followed by a short
title. The content of the post should be done in [markdown
format](http://daringfireball.net/projects/markdown/) preceeded by a small
amount of metadata. Use the existing posts as guidelines for the metadata.
(There is another category, "review", that is supported; see below for how to
use this category.)
**News**: This is intended for short announcements that would interest users,
such as release announcements and invitations to meetings of general interest.
**Documentation**: This category contains short articles documenting the
features of the Quattor toolkit, for example, a getting started guide or
high-level documentation of the architecture. Comprehensive documentation for
a core tool should be provided in a separate document, ideally generated from
DocBook as part of the build process. Links to the longer documents should be
available in the shorter articles here.
Note: All of the content should also be reasonably formatted in the source
markdown file. This allows the content to be easily reused in other
distribution channels. For example, the news items posted here will likely be
automatically forwarded to the general Quattor mailing list.
Local Testing of Content
------------------------
GitHub pages uses Jekyll to generate the website after each pushed change. You
can install Jekyll locally to see how the site will look with your changes
and/or contributions. Many editors, such as TextMate on the Mac, can render
markdown documents. This may be an easier solution than installing Jekyll if
you are only adding content.
To generate the site locally use the following command:
```bash
jekyll --base-url=file:///`pwd`/_site/
```
for old versions of Jekyll, or
```bash
jekyll build
```
for newer versions of Jekyll.
With this command all of the links on the site will function correctly.
|
PHP
|
UTF-8
| 3,980 | 2.984375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class API extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url'));
$this->load->database();
$this->load->model(array('data_model'));//database handler
}
public function index()
{
//get json object
$input=(json_decode(file_get_contents("php://input")));
//get the right form of my json object "{action:"",data:""}"
try
{
if(empty($input->action))
{throw new Exception('json object error');}
}
catch (Exception $e)
{
print_r($e->getMessage());
die();
}
//switching between the types of the apis
switch ($input->action){
//login
case 'login':
$response=$this->login($input->data);
break;
//logout
case 'logout':
$member_id=$this->check_API_key();
$response=$this->logout($member_id);
break;
//user_list
case 'user_list':
$member_id=$this->check_API_key();
$response=$this->user_list();
break;
//user_get
case 'user_get':
$member_id=$this->check_API_key();
$response=$this->user_get($input->data);
break;
default:
$e=new Exception('so such action error');
print_r($e->getMessage());
die();
}
//return the result of the api request
//print_r($response);// dumping the data in the array view for debugging
print_r(json_encode($response));//send the api result in json form
die();
}
//login logic
function login($data)
{
try
{
if(empty($data->email)||empty($data->password))
{throw new Exception('email or password error');}
}
catch (Exception $e)
{
print_r($e->getMessage());
die();
}
$api_key=$this->data_model->login($data);
$result['response']="success";
$result['data']['API_key']=$api_key;
return $result;
}
//logout logic
function logout($member_id)
{
$this->data_model->logout($member_id);
$result['response']="success";
$result['data']="";
return $result;
}
//check api key from the header
function check_API_key()
{
try
{
if(empty(getallheaders()['API_key']))
{throw new Exception('API key error');}
}
catch (Exception $e)
{
print_r($e->getMessage());
die();
}
// get the member id if the key is true
$member_id=$this->data_model->get_member_id(getallheaders()['API_key']);
return $member_id;
}
//get all the users
function user_list()
{
$data=$this->data_model->get_all_members();
return $data;
}
//get single user
function user_get($data)
{
try
{
if(empty($data->member_id))
{throw new Exception('please select a user');}
}
catch (Exception $e)
{
print_r($e->getMessage());
die();
}
$single_member=$this->data_model->get_member_data_by_id($data->member_id);
$result['response']="success";
$result['data']=$single_member;
return $result;
}
}
/*
login json
{
"action":"login",
"data":{
"email":"admin@admin.com",
"password":"admin"
}
}
logout json
api key in the header
{
"action":"logout"
}
get all members json
api key in the header
{
"action":"user_list"
}
get single member data json
api key in the header
{
"action":"user_get",
"data":{
"member_id":"1"
}
}
*/
|
PHP
|
UTF-8
| 2,228 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers\Site;
use App\Category;
use App\Contracts\ObjectRepository;
use App\Http\Controllers\Base\BaseController;
use App\Post;
use App\Services\BaseService;
use App\Tag;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Auth;
class PostsController extends BaseController
{
/**
* @return Post
*/
protected function getModel()
{
return new Post();
}
/**
* @param Request $request
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @throws \App\Exceptions\ViewNotFound
*/
public function viewPostAction(Request $request, $id)
{
$post = $this->objectManager->findOne($id);
if (!Auth::check()) {
$post->timestamps = false;
$post->count_views++;
$post->save();
}
return view($this->getView('post'), [
'post' => $post,
]);
}
public function getByCategoryAction(Request $request, $categoryId)
{
$objects = $this->objectManager
->getBuilder()
->where('category_id', '=', $categoryId)
->paginate();
return view($this->getView('list'), [
'objects' => $objects,
]);
}
public function getByCategoryAndSubcategoryAction(Request $request, $categoryId, $subcategoryId)
{
$objects = $this->objectManager
->getBuilder()
->where('category_id', '=', $categoryId)
->where('subcategory_id', '=', $subcategoryId)
->paginate();
return view($this->getView('list'), [
'objects' => $objects,
]);
}
public function getByTagAction(Request $request, $slug)
{
$objects = $this->objectManager
->getBuilder()
->join('post_tags', 'post_tags.post_id' , '=', 'posts.id')
->join('tags', 'post_tags.tag_id', '=', 'tags.id')
->where('tags.slug', '=', $slug)
->select('posts.*', 'tags.name', 'tags.slug')
->paginate();
return view($this->getView('list'), [
'objects' => $objects,
]);
}
}
|
JavaScript
|
UTF-8
| 28,804 | 3.015625 | 3 |
[] |
no_license
|
//built at Sat 28 Mar 2015 10:01:26 PM EDT
var game = function(){
this.width=window.innerWidth||800;
this.height = window.innerHeight||600;
this.container = document;
this.contexts = {};
this.screens={};
this.events = {};
this.proto={};
this.objects={}
this.keys={
"left1":37,
"right1":39,
"left2":65,
"right2":68
};
this.keysDown={
"left1":false,
"right1":false,
"left2":false,
"right2":false
};
this.directions = {
"right" :0,
"down":Math.PI/2,
"left":Math.PI,
"up":Math.PI/2*3
};
//
this.data= {
sound:{},
sprite:{},
level:{},
units:{},
loading:0
};
this.dataLoaded = false;
//Loop Vars
this.shouldLoop = true;
this.lastLoopAt =0;
this.loopCount=0;
this.loopHandle=null;
//input vars
this.mouse={x:0,y:0};
this.keysPressed ={};
this.lastKeys =[];
//game vars
this.paused =false;
this.activeScreen ="loading";
this.fontSize = 16;
this.font ="monospace";
this.level =null;
this.init = function(){
console.log("game.init");
this.compatability();
//replace all screens with instances.
this.initScreens();
};
this.start = function(gamedata){
console.log("game.start");
this.initDom();
///binds game events
this.initEvents(this.events);
///draw loading screen
this.raiseEvent("draw");
//start drawing now
this.startLoop();
//do any final preporcessing we need on teh data.
this.prepareData(gamedata);
};
//reads the game.event object and binds all of them to the dom and relevant functions
this.initEvents = function(evtObj){
game.container = document.getElementById("container")||document;
var i=0;
for(var event in evtObj){
this.bindEvent(event, evtObj[event], game.container)
i++;
}
}
//binds a single event to a dom element.
this.bindEvent= function(eventName, functionRef, domElement){
if(!eventName && typeOf(functionRef) !="function"){
console.log("cannot bind ", event, functionRef)
return;
}
var container = domElement || document;
if(eventName.indexOf("window") === 0){
//remove the window at the start
if(game.debug){
console.log("eventName starts with window ",
"binding to window instead of container",
eventName);
}
container = window;
eventName = eventName.substring(6)
}
if(!window.addEventListener){
container.attachEvent("on"+eventName, functionRef);
}
else{
container.addEventListener(eventName, functionRef, false);
}
}
//generates a dom event on the container
this.raiseEvent=function(eventName){
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
// if( game.debug ){
// console.log("raising event", eventName);
// }
event.eventName = eventName;
event.args = [];
//loop through arguements and
for(var i = 1; i<arguments.length;i++){
event.args.push(arguments[i])
}
if (document.createEvent) {
game.container.dispatchEvent(event);
} else {
game.container.fireEvent("on" + event.eventType, event);
}
};this.compatability =function(){
if(!console || !console.log){
window.console = {log:function(){}};
}
if(!localStorage){
console.log("WARNING: Your browser does not support saving your game");
}
};
//ensures the Dom is ready
this.initDom =function(){
var canvases =["main"];
for( var i = 0; i < canvases.length ; i++){
var cvs =canvases[i];
var el = document.getElementById(cvs);
if(el.getContext){
game.contexts[cvs] = el.getContext("2d");
el.width = game.width;
el.height= game.height;
}
else{
console.log("ERROR: canvas could not initialize", cvs);
}
}
};
this.initScreens = function(){
for(scr in this.screens){
if(scr != "base"){
this.screens[scr] = new this.screens[scr]();
}
}
}
this.prepareData = function(data){
for(var spr in data.sprite){
game.data.loading++;
game.data.sprite[spr] = new game.sprite(data.sprite[spr]);
}
for(var snd in data.sound){
game.data.loading++;
game.data.sound[snd] = new game.sound(data.sound[snd]);
}
console.log("done adding preloads");
game.dataLoaded = game.data.loading ==0 ;
}
this.loadSuccess = function(e){
game.data.loading--;
if(game.data.loading <=0){
game.dataLoaded =true;
}
}
this.loadFailed = function(e){
console.log("!ERROR:load failed", e);
game.data.loading--;
if(game.data.loading <=0){
game.dataLoaded =true;
}
}
//this function is called to advance teh game
this.loop = function(){
var now = new Date();
var ticks = (now - game.lastLoopAt)/1000 ;
game.lastLoopAt =now;
game.loopCount++;
if(game.shouldLoop){
if(!game.paused){
game.raiseEvent("update",ticks);
}
game.raiseEvent("draw");
}
else{
game.stopLoop();
}
}
//this is called to drop the game loop;
this.stopLoop= function(){
clearInterval(game.loopHandle);
console.log("loop stopped");
};
//this is called to cause the game to start looping again.
this.startLoop = function(){
console.log("loop started");
game.lastLoopAt = new Date();
if(!window.gameLoop){
window.gameLoop = game.loop;
}
game.loopHandle = setInterval(window.gameLoop,33);
console.lo
}
this.math = {
"toDegrees":function(radians){
return radians *(180/Math.PI);
},
"toRadians":function(degrees){
return degrees ( Math.PI/180);
},
"lerp":function(a, b, c){
return (b - a)*c + a;
},
"clamp":function(val, min ,max){
return Math.min(Math.max(val, min),max);
},
"dot":function(a,b){
var acc =0;
if(typeof (a) != typeof (b)){
console.log("cannot dot",a ,b)
return acc;
}
for( i in a){
if(typeof(a[i])=="number"
&& typeof(b[i])=="number"){
acc+= a[i] *b[i];
}
}
return acc;
},
"tau":Math.PI*2
};
this.sprite = function(json){
this.file =""
this.tiles =[];
this.animations ={};
this.image=null;
this.info = {};
this.width = null;
this.height = null;
this.drawAnimation =function(context, x,y,w,h, animationName, index){
var i = this.animations[animationName][index];
var coords = this.coordsFromIdx(i);
context.drawImage(this.image, coords.x, coords.y, coords.w, coords.h,
x,y,w,h)
};
this.coordsFromIdx = function(i){
var x = i % this.info.perLine;
var y = Math.floor(i/this.info.perLine);
return {
x:this.info.offsetX + x * this.info.width,
y:this.info.offsetY + y * this.info.height,
w:this.info.width,
h:this.info.height
}
}
this.init = function(json){
this.file = json.file;
this.info =json.info;
this.animations = json.animations;
this.image = new Image();
this.image.onload = game.loadSuccess;
this.image.onerror = game.loadFailed;
this.image.src = "media/"+this.file;
}
this.init(json);
};
this.sound = function(json){
this.file ="";
this.sound= null;
this.play =function(){
this.sound.play();
}
this.stop = function(){
this.sound.pause();
this.sound.fastSeek(0);
}
this.seek = function(time){
this.sound.fastSeek(time);
}
this.init = function(json){
this.file = json.file;
this.sound = new Audio();
this.sound.onloadeddata = game.loadSuccess;
this.sound.onerror = game.loadFailed;
this.sound.src = "media/"+this.file;
}
this.init(json);
};
this.events.bounce = function(e){
asteroid = e.args[0];
shield = e.args[1];
asteroid.a = shield.reflectAngle(asteroid.x, asteroid.y, asteroid.a);
asteroid.speed = asteroid.speed *1.2;
if(shield.type != "shield"){
asteroid.speed = game.math.clamp( 0, 256, asteroid.speed *1.2);
shield.speed = shield.speed * 1.2;
shield.a = asteroid.reflectAngle(shield.x, shield.y, shield.a);
}
else{
game.data.sound.blip.play();
}
asteroid.move(asteroid.a, asteroid.speed ,0.1);
//TODO create sprite on bounce
}
this.events.collision = function(e){
asteroid = e.args[0];
planet = e.args[1];
asteroid.onCollide(planet);
planet.onCollide(asteroid);
//TODO playsound on explosion show spreite.
};
this.events.gameOver =function(e){
planet = e.args[0];
game.level.lost.push( planet);
//TODO Play a sound at game end.
};
this.events.windowkeydown = function(event){
for(keyname in game.keys){
if(event.keyCode == game.keys[keyname]){
game.keysDown[keyname] =true;
event.preventDefault();
}
}
if(game.screens[game.activeScreen].keydown){
game.screens[game.activeScreen].keydown(event);
}
};
this.events.windowkeyup = function(event){
for(keyname in game.keys){
if(event.keyCode == game.keys[keyname]){
game.keysDown[keyname] =false;
event.preventDefault();
}
}
if(game.screens[game.activeScreen].keyup){
game.screens[game.activeScreen].keyup(event);
}
};
this.events.draw =function(e){
if(game.screens[game.activeScreen] &&
game.screens[game.activeScreen].draw){
game.screens[game.activeScreen].draw(e);
}
};
this.events.update =function(e){
if(game.screens[game.activeScreen] &&
game.screens[game.activeScreen].update){
game.screens[game.activeScreen].update(e.args[0]||0);
}
};
this.events.mousemove = function(evt){
var rect = game.container.getBoundingClientRect();
game.mouse.x = evt.pageX - rect.left - game.container.scrollLeft + window.pageXOffset
game.mouse.y = evt.pageY - rect.top - game.container.scrollTop + window.pageYOffset;
};
this.events.click=function(evt,x,y){
if(game.screens[game.activeScreen] &&
game.screens[game.activeScreen].click){
game.screens[game.activeScreen].click(evt,x,y);
}
};
this.events.screenChange=function(event){
var from = event.args[0],
to = event.args[1],
transition = event.args[2]|| false;
console.log("screen changed",from, to, transition);
game.screens[from].close();
if(transition){
game.screens[transition].open(from,to);
game.activeScreen = transition;
}
else{
game.screens[to].open();
game.activeScreen = to;
}
};//stop the loop on blur
this.events.windowblur=function(evt){
game.shouldLoop =false;
};
//restart the loop on fucs
this.events.windowfocus=function(evt){
game.shouldLoop = true;
game.startLoop();
};
this.events.windowresize = function(evt){
//TODO resize support;
};
this.screens.base = function(){
this.elements=[];
//called at load time once
this.init =function(){
};
//called when made active
this.open = function(){
};
//called upon leaving
this.close =function(){
}
this.draw =function(){
};
this.update =function(){
};
this.click = function(e,x,y){
var _x = x||game.mouse.x;
var _y = y||game.mouse.y;
for(var i =0; i <this.elements.length;i++){
if(this.elements[i].x < _x
&& this.elements[i].x + this.elements[i].w > _x
&& this.elements[i].y < _y
&& this.elements[i].y + this.elements[i].h > _y){
this.elements[i].click(evt,
_x- this.elements[i].x,
_y- this.elements[i].y);
}
}
}
};
this.screens.attract = function(){
this.elements=[];
this.timeSinceOpen =0;
this.zoomTime = 3;
this.r = 0;
this.open = function(){
this.timeSinceOpen =0;
game.contexts.main.font =game.fontSize+"px "+ game.font;
console.log("agg");
};
this.draw =function(){
game.contexts.main.clearRect(0,0,game.width,game.height);
game.contexts.main.fillStyle ="#fff";
game.contexts.main.fillText("WELCOME TO PLANETARY ORBITAL NERD GARRISON",32,game.width/4);
game.contexts.main.fillText("KEYS: [LEFT, RIGHT] [A, B]",32,game.width/4+64);
game.contexts.main.fillText("STANDING ORDERS: TRY NOT TO KILL EVERYONE!",32,game.width/4+96);
game.contexts.main.fillText("CLICK TO BEGIN",32,game.width/4+128);
//TODO Pretty up atttract screeen
};
this.update =function(ticks){
this.timeSinceOpen+=ticks;
if(this.timeSinceOpen < this.zoomTime){
this.r = (this.r +.05 )%(Math.PI*2)
}
};
this.click =function(){
game.raiseEvent("screenChange","attract","inGame","fade");
}
}
this.screens.attract.prototype = new this.screens.base();
this.screens.fade =function(){
this.count = 10;
this.next = null;
this.open =function(from, to){
this.count = 10;
this.next = to;
}
this.draw = function(){
game.contexts.main.fillStyle="rgba(0,0,0,0.5)";
game.contexts.main.fillRect(0,0,game.width, game.height);
}
this.update=function(){
this.count--;
if(this.count <-1 && this.next){
game.raiseEvent("screenChange", "fade", this.next);
}
}
}
this.screens.fade.prototype = new this.screens.base();
this.screens.inGame =function(){
this.loseTime = 5;
this.open =function(){
this.loseTime = 5;
game.level =new game.objects.level();
}
this.draw = function(){
game.contexts.main.clearRect(0,0,game.width, game.height);
game.level.draw(game.contexts.main);
game.level.drawShadow(game.contexts.main);
}
this.update=function(ticks){
if(game.level.lost.length < game.level.numPlanets -1){
game.level.update(ticks);
}
else{
this.loseTime -= ticks;
if(this.loseTime <= 0 ){
game.raiseEvent("screenChange", "inGame", "attract", "fade");
}
}
}
this.click = function(){
var p = new game.objects.projectile(game.mouse.x -game.width/2,
game.mouse.y - game.height/2,
game.directions.up);
game.level.addObject(p);
}
}
this.screens.inGame.prototype = new this.screens.base();
this.screens.loading = function(){
this.draw =function(){
game.contexts.main.font =game.fontSize+"px "+ game.font;
var ctx =game.contexts.main;
ctx.clearRect(0,0,game.width, game.height);
ctx.fillStyle= "#fff";
ctx.fillRect(game.width/4, game.height/2,
(game.width/2) * (game.loopCount%16/16),game.fontSize);
ctx.fillText(game.data.loading+ " remaining", game.width/4, game.height/2+game.fontSize*2);
}
this.update=function(ticks){
if(game.dataLoaded){
game.raiseEvent("screenChange", "loading", "attract","fade");
}
else{
console.log("...")
}
}
}
this.screens.loading.prototype = new this.screens.base();
this.proto.base = function(){
//expect teh following to be overridden but im including them for joy
this.castShadow =true;
this.hasLights= false;
this.x = 0;
this.y = 0;
this.r = 0; //radius
this.a = 0; //objects angle;
this.shadowColor = "rgba(0,0,0,0.2)";
this.mass =1;
this.init=function(){
};
this.move =function(direction, speed, ticks){
this.x += Math.cos(direction)*speed *ticks;
this.y += Math.sin(direction)*speed *ticks
};
this.inside = function(x,y,r){
r = r ||0;
return Math.sqrt(Math.pow(this.x - x,2) + Math.pow(this.y-y,2)) < this.r +r;
}
this.dist = function(x,y){
return Math.sqrt(Math.pow(this.x - x,2) + Math.pow(this.y-y,2))
}
this.distSq = function(x,y){
return Math.pow(this.x - x,2) + Math.pow(this.y-y,2);
}
this.draw =function(context){
context.beginPath()
context.arc(this.x, this.y, this.r, 0, Math.PI *2);
context.fill();
};
this.drawShadow = function(context, lightx, lighty){
if( !this.castShadow){
return;
}
var sun = null;
if(game.level && game.level.orbitalObjects){
var sun = game.level.orbitalObjects[0];
}
else{
sun = {x:lightx||game.width/3*2,
y:lighty||game.width/3*2,
r: 5};
}
//find two points perpendicular to the light source on the radius.
var a = Math.atan2(sun.y-this.y, sun.x - this.x);
var x1 = this.x + Math.cos(a+Math.PI/2) *this.r;
var y1 = this.y + Math.sin(a+Math.PI/2) *this.r;
var x2 = this.x + Math.cos(a-Math.PI/2) *this.r;
var y2 = this.y + Math.sin(a-Math.PI/2) *this.r;
var sx1 = sun.x + Math.cos(a+Math.PI/2) *sun.r;
var sy1 = sun.y + Math.sin(a+Math.PI/2) *sun.r;
var sx2 = sun.x + Math.cos(a-Math.PI/2) *sun.r;
var sy2 = sun.y + Math.sin(a-Math.PI/2) *sun.r;
var r = this.r/ sun.r *-1;
var l = this.dist(sun.x, sun.y)/r;
var cx = this.x + Math.cos(a) *l;
var cy = this.y + Math.sin(a) *l;
//generate a polygon between the edge of teh screen and the cone from the sun.
context.fillStyle = this.shadowColor;
context.beginPath();
context.moveTo(x1,y1);
context.lineTo(cx,cy);
context.lineTo(x2,y2);
context.fill();
};
this.drawLights =function(context){
if(!this.hasLights){
return;
}
}
this.update = function(ticks){
};
this.shouldRemove =function(){
return false;
};
this.onCollide =function(orbitalObject){
this.hasCollided = true;
}
this.addForce =function(angle, speed){
};
this.reflectAngle = function(x,y,inAngle){
var a = Math.atan2(this.x-x, this.y-y);
var plane = a + Math.PI/2;
var incidence = (inAngle - plane)%game.math.tau;
var reflectAngle = (plane - incidence)%game.math.tau;
if(reflectAngle - a > Math.PI/2){
reflectAngle+=Math.PI
}
return reflectAngle;
};
};
this.proto.planet=function(){
this.rotationalVelocity = 0.0;
this.castsShadow =true;
this.hasLights = true;
this.atmosphereDepth =32;
this.mass = 100;
this.x = 0;
this.y = 0;
this.r = 0;
this.shield = null;
this.bgColor = "#0f0";
this.atmoColor = "rgba(1,64,128,0.2)";
this.orbitX =0;
this.orbitY =0;
this.points =10;
this.init =function(x,y,r){
this.x = x||this.x;
this.y = y||this.y;
this.r = r||this.r;
this.atmosphereDepth = game.math.clamp(this.r/5, 8 ,32);
//this.mass = this.r *10;
this.shield = new game.objects.shield(this);
}
this.draw =function(context){
context.save();
context.translate(this.x,this.y);
context.rotate(this.a);
//the the planet
context.fillStyle = this.bgColor;
context.beginPath()
context.arc(0, 0, this.r, 0, Math.PI *2);
context.fill();
//the cities
for(var i = 0 ;i< this.cities/length;i++){
this.cities[i].draw(context);
}
//draw teh atmosphere
context.strokeStyle = this.atmoColor
context.beginPath()
context.lineWidth = this.atmosphereDepth;
context.arc(0, 0, this.r+ this.atmosphereDepth/2, 0, Math.PI *2);
context.stroke();
if(this.shield){
this.shield.draw(context);
}
context.restore();
context.fillStyle = "#fff";
context.textAlign ="center";
context.fillText(this.points,this.x, this.y+game.fontSize/2);
};
this.update = function(ticks ,j ){
//this.a = (this.a + this.rotationalVelocity) % game.math.tau;
if(this.shield){
this.shield.update(ticks, this , j);
}
for(var i=0; i < this.cities.length;i++){
this.cities[i].update(ticks);
}
//move around the sun, circlewise
var a1 = Math.atan2( this.y - this.orbitY, this.x - this.orbitX);
this.move(a1 + (Math.PI/2),this.rotationalVelocity, ticks)
};
this.inAtmosphere = function(x,y){
return this.dist(x,y) < this.r + this.atmosphereDepth;
};
this.setOrbitalCenter =function(x,y){
this.orbitX = x ||0;
this.orbitY = y ||0;
};
this.onCollide= function(){
this.points--;
// TODO destroy a city
//TODO show sprite.
game.data.sound.crash.play();
if(this.points ==0){
game.raiseEvent("gameOver", this);
}
}
};
this.proto.planet.prototype = new this.proto.base();
this.proto.shield = function(){
this.castShadow =true;
this.hasLights= false;
this.x = 0;
this.y = 0;
this.r = 0; //radius
this.a = 0; //objects angle;
this.d = 64;// the thickness;
this.length = Math.PI/6
this.rotateSpeed = 3;
this.color ="#fff";
this.planet= null;
this.init =function(planet){
this.x = planet.x;
this.y = planet.y;
this.planet = planet;
this.r = planet.r+ planet.atmosphereDepth *4 ;
this.a = Math.random() *game.math.tau -Math.PI;
this.d = planet.atmosphereDepth *2;
}
this.draw = function(context){
context.strokeStyle = this.color
context.beginPath()
context.lineWidth = this.d;
context.arc(0, 0, this.r + this.d/2, this.a - this.length/2, this.a + this.length/2);
context.stroke();
}
this.update= function(ticks, planet, index){
if(game.keysDown["left"+index]){
this.a -= this.rotateSpeed *ticks;
}
if(game.keysDown["right"+index]){
this.a += this.rotateSpeed *ticks;
}
if(this.a > Math.PI){
this.a -= game.math.tau;
}
if(this.a < Math.PI *-1){
this.a += game.math.tau;
}
}
this.contains =function(x,y,r){
var dist = this.planet.dist(x,y);
if(dist >= this.r && dist<= this.r + this.d +r){
var angle =Math.atan2(y-this.planet.y,x-this.planet.x);
return (angle >= this.a - this.length/2 &&
angle <= this.a + this.length/2);
}
return false;
};
this.reflectAngle = function(x,y,inAngle){
var a = Math.atan2(this.planet.x-x, this.planet.y-y);
var plane = a + Math.PI/2;
var incidence = (inAngle -plane) % game.math.tau;
var reflectAngle = (plane - incidence)%game.math.tau;
if(Math.abs(reflectAngle - a)%game.math.tau > Math.PI/2*3){
reflectAngle+=Math.PI
}
return reflectAngle;
};
};
this.proto.shield.prototype = new this.proto.base();
this.proto.level = function(){
//expect teh following to be overridden but im including them for joy
this.castShadow =true;
this.hasLights= false;
this.x = 0;
this.y = 0;
this.r = 0; //radius
this.a = 0; //objects angle;
this.shadowColor = "rgba(0,0,0,0.2)";
this.orbitalObjects =[];
this.starField =[];
this.lost=[];
this.numPlanets = 0;
////
this.init = function(numPlanets){
this.w = game.width;
this.h = game.height;
this.x = this.w/2;
this.y = this.h/2;
numPlanets =2;
this.numPlanets = 2;
var slice = Math.min(this.w, this.h)/2/(2+numPlanets);
//create a sun or more
var s = new game.objects.sun(slice/2);
this.addObject(s);
for(var i = 0 ;i < numPlanets;i++){
var a = Math.random() * Math.PI ;
var r = Math.ceil(slice/2 * Math.random() + slice/4);
var p = new game.objects.planet(0,0, r/2);
p.rotationalVelocity = Math.floor(Math.random() * 10) +5;
if(i %2){
p.rotationalVelocity = p.rotationalVelocity *-1
a = a *-1
}
p.move(a, slice * (i+2) , 1);
//p.setOrbitalCenter(this.x,this.y);
//Try not to create a collision
this.addObject(p);
}
}
this.draw =function(context){
context.save();
context.translate(this.x, this.y);
this.drawStarField();
for(var i =0; i < this.orbitalObjects.length;i++){
this.orbitalObjects[i].draw(context);
}
for (var l = 0; l< this.lost.length; l++){
context.fillStyle = "#f00";
context.save();
context.translate(this.lost[l].x, this.lost[l].y+ game.fontSize/2);
context.fillText("LOST", 0,game.fontSize);
context.scale(7,7);
context.fillText("X", 0,0);
context.restore();
}
context.restore();
}
this.drawShadow =function(context){
context.save();
context.translate(this.x, this.y);
for(var i =0; i < this.orbitalObjects.length;i++){
this.orbitalObjects[i].drawShadow(context);
}
context.restore();
}
this.drawStarField =function(context){
}
this.update =function(ticks){
if(this.orbitalObjects.length < 128 &&
game.loopCount %3 ==0 &&
Math.random() > .25){
this.addObject(this.generateAsteroid());
}
for(var i =0; i < this.orbitalObjects.length;i++){
this.orbitalObjects[i].update(ticks, i);
if(this.orbitalObjects[i].shouldRemove()){
this.orbitalObjects.splice(i,1);
i--;
}
}
}
this.addObject = function(o){
this.orbitalObjects.push(o);
}
this.generateAsteroid = function(){
var a = Math.random() * game.math.tau;
var p = new game.objects.projectile(
Math.sin(a) *game.width/2,
Math.cos(a) *game.height/2,
a +Math.PI + (Math.random() *0.2 - 0.1));
p.speed = p.speed *Math.random() +p.speed;
return p;
}
}
this.proto.level.prototype= new this.proto.base();
this.proto.projectile = function(){
this.castShadow =true;
this.hasLights= false;
this.x = 0;
this.y = 0;
this.r = 16; //radius
this.a =0; //objects angle;
this.speed = 0;
this.hasCollided =false;
this.movedAway = false;
this.update =function(ticks , index){
if(this.shouldRemove()){
return;
}
var tests =[this.x, this.y];
var destX = this.x + Math.cos(this.a)* this.speed *ticks;
var destY = this.y += Math.sin(this.a)*this.speed *ticks;
for (var i = 0 ; i *2 < this.speed *ticks; i++){
var pct = i*2 /this.speed *ticks;
var x = game.math.lerp(this.x, destX, pct);
var y = game.math.lerp(this.y, destY, pct);
tests.push(x);
tests.push(y);
}
tests.push(destX);
tests.push(destY);
var obj;
for(j = 0 ;j < tests.length; j+=2){
var x = tests[j];
var y = tests[j+1];
this.x = x;
this.y = y;
for(var i = 0 ; i < game.level.orbitalObjects.length; i++){
obj = game.level.orbitalObjects[i];
//colisions checks
if(obj.type == "planet"|| obj.type =="sun"){
if(obj.inside(x, y, this.r)){
i = game.level.orbitalObjects.length;
j = tests.length;
game.raiseEvent("collision", this, obj);
}
else{
if(obj.shield && obj.shield.contains(x, y, this.r)){
i = game.level.orbitalObjects.length;
j = tests.length;
game.raiseEvent("bounce", this, obj.shield);
}
}
}
else{
if(index != i && obj.inside(x, y, this.r)){
i = game.level.orbitalObjects.length;
j = tests.length;
game.raiseEvent("bounce", this, obj);
}
}
}
}
if( Math.abs(this.x) > game.width || Math.abs(this.y)> game.height ){
this.movedAway =true;
}
if(this.speed > game.height){
console.log("obver limit" );
this.movedAway =true;
}
}
this.draw = function(context){
context.fillStyle="#999";
context.beginPath()
context.arc(this.x, this.y, this.r, 0, Math.PI *2);
context.fill();
}
this.shouldRemove = function(){
return this.hasCollided || this.movedAway;
}
this.collisionCheck =function(x,y){
}
}
this.proto.projectile.prototype = new this.proto.base();
this.proto.sun = function(r){
this.rotationalVelocity = 0.0;
this.castsShadow =true;
this.hasLights = true;
this.atmosphereDepth =32;
this.mass = 100;
this.x = 0;
this.y = 0;
this.r = 64;
this.shield = null;
this.bgColor = "#ff0";
this.atmoColor = "rgba(128,96,32,0.2)";
this.orbitX =0;
this.orbitY =0;;
this.init = function(r){
this.r = r||this.r;
this.atmosphereDepth = Math.min(this.r/3);
}
this.update =function(ticks){
this.a = (this.a + this.rotationalVelocity) % game.math.tau;
}
this.draw =function(context){
context.save();
context.translate(this.x,this.y);
context.rotate(this.a);
//draw teh atmosphere
context.strokeStyle = this.atmoColor
context.beginPath()
context.lineWidth = this.atmosphereDepth;
context.arc(0, 0, this.r+ this.atmosphereDepth/2 *Math.abs( Math.sin(game.loopCount/10)), 0, Math.PI *2);
context.stroke();
//the the planet
context.fillStyle = this.bgColor;
context.beginPath()
context.arc(0, 0, this.r, 0, Math.PI *2);
context.fill();
context.restore();
};
this.onCollide = function(){
//TODO play Sizzle Sound.
};
}
this.proto.sun.prototype = new this.proto.planet();
this.objects.level = function(numPlanets){
this.castShadow =false;
this.hasLights= false;
this.x = 0;
this.y = 0;
this.r = 0; //radius
this.a = 0; //objects angle;
this.shadowColor = "rgba(0,0,0,0.2)";
this.orbitalObjects =[];
this.starField =[];
this.lost =[];
this.type= "level";
var slice =25;
this.numPlanets = 0;
this.init(numPlanets);
}
this.objects.level.prototype = new this.proto.level();
this.objects.planet = function(x,y,r){
this.a = 0; //objects angle;
this.rotationalVelocity = 0.0;
this.castsShadow =true;
this.hasLights = true;
this.atmosphereDepth =32;
this.mass = 2000;
this.x = x||0;
this.y = y||0;
this.r = r||0;
this.bgColor = "#0f0";
this.atmoColor = "rgba(32,64,128,0.2)";
this.points =10;
this.shield = null;
this.cities = [];
this.orbitX =0;
this.orbitY =0;;
this.type= "planet";
this.init(x,y,r);
}
this.objects.planet.prototype = new this.proto.planet();
this.objects.projectile = function(x,y,a){
this.castShadow =true;
this.hasLights= false;
this.x = x||0;
this.y = y||0;
this.r = 8; //radius
this.a =a||0; //objects angle;
this.speed = 64;
this.type= "projectile";
this.hasCollided =false;
this.movedAway = false;
this.init();
}
this.objects.projectile.prototype = new this.proto.projectile();
this.objects.shield =function(planet){
this.castShadow =true;
this.hasLights= false;
this.x = 0;
this.y = 0;
this.r = 0; //radius
this.a = 0; //objects angle;
this.d = 16;// the thickness;
this.length = Math.PI/2
this.rotateSpeed = 7;
this.color ="#fff";
this.type= "shield";
this.planet=null;
this.init(planet);
}
this.objects.shield.prototype = new this.proto.shield();
this.objects.sun = function(r){
this.rotationalVelocity = 0.0;
this.castsShadow =false;
this.hasLights = true;
this.atmosphereDepth =32;
this.mass = 2000;
this.x = 0;
this.y = 0;
this.r = 64;
this.shield = null;
this.bgColor = "#ff0";
this.atmoColor = "rgba(128,96,32,0.2)";
this.type= "sun";
this.init(r);
};
this.objects.sun.prototype = new this.proto.sun();
//setup the game object
this.init();
}
//end
|
Markdown
|
UTF-8
| 809 | 2.5625 | 3 |
[] |
no_license
|
# DangCatFeeder
Dang Family Automated Cat Feeder, spins servo motor / send and recieves emails
Credited functions to storiknow.com / Sam Storino!
I started this project to solve a problem, our cat was gaining too much weight.
We fed him too much, so I suggested we try to feed him in smaller doses at
more time periods. That failed because of our lack of consistency.
Voila!
This spawned the idea of an automated cat feeder. I finished the project after
2 months and decided to make my own revisions! I added in some functions that
would use an email system as a means of a 'subject line function call' for
the actual code. Now the RaspberryPi Module 3 will tell you with a timestamp
when the cats were specifically fed.
(Now we use this when we go out of town...) :)
Thanks for viewing my project!
Christopher Dang
|
C++
|
UTF-8
| 2,842 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#ifndef GLOBALS_H
#include"globals.h"
#endif
static int WINWIDTH = 700;
static int WINHEIGHT = 500;
static int LOOPCOUNT = 1000000;
//Arbitrary value
static quint32 INITIALSTATE = 0x0A1B2C3D;
class MaxTaps;
// This program creates a list of 4 taps which produce a maximal length
// output for a 32-bit linear feedback shift register. The results are
// saved in a text file.
// Fromhttps://en.wikipedia.org/wiki/Linear_feedback_shift_register:
// The LFSR is maximal-length if and only if the corresponding feedback polynomial is primitive.
// This means that the following conditions are necessary (but not sufficient):
// 1. The number of taps should be even.
// 2. The set of taps – taken all together, not pairwise (i.e. as pairs of elements) – must be
// relatively prime. In other words, there must be no divisor other than 1 common to all taps.
// The taps are labeled for 1 to 32
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Since tap 32 is present in all 4-tap constructs, and it is pow(2,5), the only condition
// which is exempt from the "relatively prime" condition is if all 4 taps are even. If there
// is one or more of the taps which are odd, then the configuration POSSIBLY produces a
// maximal output.
//========== class MainWindow ==========
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
void sizeAndCenterWidget (QWidget* widget, int width, int height);
void paintEvent(QPaintEvent*);
void shiftTheRegister();
void moveToNextTagConfig(QPainter* p);
void drawTheBoxes(QPainter* p);
void appendAMaximal(quint32 theTaps[4]);
bool started;
bool masterSw;
bool finished;
quint32 theNumber;
quint32 tapsArray[4];
QPushButton* startButt;
QPushButton* stopButt;
QPushButton* resumeButt;
QPushButton* saveButt;
quint64 counter;
quint32 two_pow32_minus1;
QColor boxColor, maxColor, useColor;
quint32 lastTaps[4];
quint32 lastCount;
bool lastIsMaximal;
quint32 lastLastTaps[4];
quint32 lastLastCount;
bool lastLastIsMaximal;
bool isMaximal;
bool savingBool;
bool drawBool;
bool noMaximals;
MaxTaps* maximalsList = NULL;
QString maximalsStr = "\n";
private slots:
void startButtClicked();
void stopButtClicked();
void resumeButtClicked();
void saveButtClicked();
};
//========== class MaxTaps ==========
class MaxTaps : public QObject
{
Q_OBJECT
public:
MaxTaps(QObject *parent = 0);
~MaxTaps();
MaxTaps* nextTaps;
quint32 maxray[4];
static int num;
};
#endif // MAINWINDOW_H
|
Python
|
UTF-8
| 3,842 | 3.328125 | 3 |
[] |
no_license
|
#!/usr/bin/python3
"""Module for testing the Base class"""
import unittest
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
import json
class TestBaseClass(unittest.TestCase):
"""Tests the Base class"""
def setUp(self):
"""Resets the base class to prevent interference"""
Base._Base__nb_objects = 0
def test_init(self):
"""Tests proper initialization"""
a = Base()
self.assertEqual(type(a), Base)
b = Base(47)
self.assertEqual(type(b), Base)
def test_id(self):
"""Tests that the correct IDs are being assigned"""
a = Base()
self.assertEqual(a.id, 1)
b = Base(47)
self.assertEqual(b.id, 47)
c = Base()
self.assertEqual(c.id, 2)
def test_to_JSON(self):
"""Tests the dictionary to JSON conversion"""
s1 = Square(3)
r1 = Rectangle(4, 5, 1, 2, 47)
ld = []
ld.append(s1.to_dictionary())
ld.append(r1.to_dictionary())
ld_json = r1.to_json_string(ld)
expected = [{"id":1, "size":3, "x":0, "y":0},
{"id":47, "width":4, "height":5, "x":1, "y":2}]
expected_json = json.dumps(expected)
self.assertEqual(ld_json, expected_json)
self.assertEqual(s1.to_json_string(None), "[]")
self.assertEqual(s1.to_json_string([]), "[]")
def test_to_file(self):
"""Tests that the JSON of an object can be written to a file"""
lo = []
lo.append(Rectangle(10, 7, 2, 8))
lo.append(Rectangle(2, 4))
Base.save_to_file(lo)
with open("Base.json") as f:
self.assertEqual(json.loads(f.read()),
[x.to_dictionary() for x in lo])
Rectangle.save_to_file(None)
with open("Rectangle.json") as f:
self.assertEqual(f.read(), "[]")
Square.save_to_file([])
with open("Square.json") as f:
self.assertEqual(f.read(), "[]")
def test_from_json_to_dict(self):
"""Tests the static method converting a json string to a dictionary"""
s1 = Square(3)
self.assertEqual([s1.to_dictionary()],
s1.from_json_string(
s1.to_json_string([s1.to_dictionary()])))
self.assertEqual(Base.from_json_string(""), [])
self.assertEqual(Base.from_json_string("[]"), [])
self.assertEqual(Base.from_json_string(None), [])
def test_from_dict_to_instance(self):
"""Tests the class method to convert a dictionary to an instance"""
s1 = Square(3)
s1_dict = s1.to_dictionary()
s2 = Square.create(**s1_dict)
self.assertEqual(str(s1), str(s2))
self.assertIsNot(s1, s2)
self.assertNotEqual(s1, s2)
r1 = Rectangle(3, 4)
r1_dict = r1.to_dictionary()
r2 = Rectangle.create(**r1_dict)
self.assertEqual(str(r1), str(r2))
self.assertIsNot(r1, r2)
self.assertNotEqual(r1, r2)
def test_from_file(self):
"""Tests that a list of objects can be loaded from a file"""
r1 = Rectangle(10, 7, 2, 8)
r2 = Rectangle(2, 4)
list_rects = [r1, r2]
Rectangle.save_to_file(list_rects)
new_rects = Rectangle.load_from_file()
self.assertEqual(str(r1), str(new_rects[0]))
self.assertEqual(str(r2), str(new_rects[1]))
def test_csv_save(self):
"""Tests that an instance can be saved as CSV"""
r1 = Rectangle(3, 4, 2, 2, 99)
r2 = Rectangle(2, 9)
r_list = [r1, r2]
Rectangle.save_to_file_csv(r_list)
new_rects = Rectangle.load_from_file_csv()
self.assertEqual(str(r1), str(new_rects[0]))
self.assertEqual(str(r2), str(new_rects[1]))
|
Markdown
|
UTF-8
| 4,502 | 3.15625 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
title: Organization Actions
---
<!--[[ preview('org-accounts') ]]-->
# Operations
This section describes the actions that can be performed
within an organization account.
!!! note
All actions assume an authorized user has logged into their account.
## Organization actions
#### Create an organization
*Actor: Any PyPI user*
* Click on **Your organization** in the left menu or the right drop down menu
* Enter the organization details under **Create new organization**
* Choose if the organization is a private organization or a community project
* Click on **Create**
If the organization being created is a corporate organization,
a billing page will appear. Enter the billing details.
Once the organization has been created, it will have to be
approved by the PyPI admin.
This usually takes <<TODO>> days.
Once the account request has been approved,
the user who created the account becomes the Owner of the organization.
The Owner will be able to manage the organization once it has been approved.
A user can create any number of organizations.
---
#### Add member to an organization
*Actor: Owner*
* Click on **Your organizatio**n
* Click on **Manage** for a specific organization
* Click on **People**
* Enter the username and assign the role for the user
The invited user will receive an email and will see an invitation
banner when they log into their account. The user will automatically
appear as a member in the organization if they accept the invitation.
The owners of the organization will receive an email notification
if the user declined the invitation.
The invited user should have an account in PyPI.
Invitations can be sent via username and not by email address.
There is no limit to the number of members within an organization.
---
#### Cancel user invitation
*Actor: Owner*
* Click on **Your organization**
* Click on **Manage** for a specific organization
* Click on **People**
* Click on **Revoke invite**
* Click on **Revoke invite** again
The user will receive an email that the invitation has been revoked.
---
#### Remove member from an organization
*Actor: Owner*
* Click on **Your organization**
* Click on **Manage** for a specific organization
* Click on **People**
* Click on **Remove** for a specific user
* Enter the username of the user and click on **Remove**
---
#### Assign a user role
*Actor: Owner*
* Click on **Your organizations**
* Click on **Manage** for a specific organization
* Click on **People**
* Assign a new role to a user who is a member of the organization.
The new role can be owner, manager, billing manager or member.
* Click on **Save**
A user can have only one role at any given time.
There can be multiple users with the same role.
---
#### Accept/Reject an invitation to join an organization
*Actor: Any user*
* Click on **Your organizations**
* Under Pending invitations, click on **Accept** or **Decline**
If the invitation has been accepted,
the organization will appear under Your organizations.
If the invitation has been declined, the Owners of the organization
will be notified by email.
---
#### Rename an organization account
*Actor: Owner*
* Click on **Your organizations**
* Click on **Manage** for a specific organization
* Click on **Settings**
* Scroll to the bottom of the page and click on
**Change organization account name**
* Enter the **New organization account name** and
**Current organization account name**
* Click on **Change organization account name**
The new name will be assigned only if there are no
other organizations with the same name.
---
#### Leave an organization
*Actor: Any member of the organization*
* Click on **Your organizations**
* Click on **Manage** for a specific organization
* Click on **People**
* Click on **Remove** next to your username in the list of users
* Enter your username and click on **Remove**
The Owners of the organization will receive an email notification.
The last Owner of the organization cannot leave the organization.
They will have to delete the organization.
---
#### Delete an organization account
*Actor: Owner*
* Click on **Your organizations**
* Click on **Manage** for a specific organization
* Click on **Settings**
* Scroll to the bottom of the page and click on **Delete organization**
* Enter the organization name and click on **Delete organization**
This action can be performed only if all the projects within an organization
have been assigned to a user.
The project history will be maintained.
|
Java
|
UTF-8
| 704 | 2.765625 | 3 |
[] |
no_license
|
package fr.anzymus.spellcast.core.gestures;
public enum Gesture {
fingers("F"), //
palm("P"), //
wave("W"), //
snap("S"), //
digit_pointing("D"), //
clap("C"), //
nothing(" "), //
stab("stab"),
anything("anything", false);
private String description;
private boolean playable = true;
private Gesture(String description) {
this.description = description;
}
private Gesture(String description, boolean playable) {
this(description);
this.playable = playable;
}
public String getDescription() {
return description;
}
public boolean isPlayable() {
return playable;
}
}
|
Java
|
UTF-8
| 561 | 2.0625 | 2 |
[] |
no_license
|
package com.example.accountback.repository;
import com.example.accountback.entity.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import java.util.Optional;
import static javax.persistence.LockModeType.PESSIMISTIC_READ;
public interface AccountRepository extends JpaRepository<Account, Long> {
@Lock(PESSIMISTIC_READ)
@Query("SELECT a FROM Account a WHERE a.no = ?1")
Optional<Account> findByNoLocked(Long id);
}
|
Java
|
UTF-8
| 2,916 | 1.898438 | 2 |
[] |
no_license
|
package br.gov.pbh.prodabel.hubsmsa.endpoint.impl;
import java.util.List;
import javax.ejb.EJB;
import javax.ws.rs.core.Response;
import br.gov.pbh.prodabel.hubsmsa.dto.EntityDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.PaginacaoPublicaDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.ResponseDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.SelecaoDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.historico.HistoricoAlteracaoDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.historico.HistoricoAlteracaoDetalheDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.tipodepara.FiltroPesquisaLogTipoDeParaDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.tipodepara.FiltroPesquisaTipoDeParaDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.tipodepara.TipoDeParaDTO;
import br.gov.pbh.prodabel.hubsmsa.dto.tipodepara.VisualizarTipoDeParaDTO;
import br.gov.pbh.prodabel.hubsmsa.endpoint.TipoDeParaEndPoint;
import br.gov.pbh.prodabel.hubsmsa.service.TipoDeParaService;
public class TipoDeParaEndPointImpl implements TipoDeParaEndPoint {
@EJB
private TipoDeParaService tipoDeParaService;
@Override
public PaginacaoPublicaDTO<VisualizarTipoDeParaDTO> consultarTipoDePara(
FiltroPesquisaTipoDeParaDTO pesquisarTipoDePara) {
return tipoDeParaService.consultarTiposDePara(pesquisarTipoDePara);
}
@Override
public ResponseDTO<EntityDTO> cadastrarTipoDePara(TipoDeParaDTO tipoDeParaDTO) {
return tipoDeParaService.cadastrarTipoDePara(tipoDeParaDTO);
}
@Override
public ResponseDTO<EntityDTO> editarTipoDePara(Long id, TipoDeParaDTO editarTipoDeParaDTO) {
return tipoDeParaService.editarTipoDePara(id, editarTipoDeParaDTO);
}
@Override
public VisualizarTipoDeParaDTO consultarTipoDePara(Long id) {
return tipoDeParaService.consultarTipoDePara(id);
}
@Override
public ResponseDTO<EntityDTO> excluirTipoDePara(Long id) {
return tipoDeParaService.excluirTipoDePara(id);
}
@Override
public List<SelecaoDTO> consultarSelecao() {
return tipoDeParaService.consultarSelecao();
}
@Override
public Response gerarExcel(FiltroPesquisaTipoDeParaDTO filtroTipoDePara) {
return tipoDeParaService.gerarExcel(filtroTipoDePara);
}
@Override
public Response gerarCsv(FiltroPesquisaTipoDeParaDTO filtroTipoDePara) {
return tipoDeParaService.gerarCsv(filtroTipoDePara);
}
@Override
public PaginacaoPublicaDTO<HistoricoAlteracaoDTO> consultarLogTipoDePara(
FiltroPesquisaLogTipoDeParaDTO revisaoDTO) {
return tipoDeParaService.consultarLogTipoDePara(revisaoDTO);
}
@Override
public HistoricoAlteracaoDetalheDTO consultarDetalheRevisao(Long id) {
return tipoDeParaService.consultarDetalheRevisao(id);
}
@Override
public Response gerarLogCsv(FiltroPesquisaLogTipoDeParaDTO filtro) {
return tipoDeParaService.gerarLogCsv(filtro);
}
@Override
public Response gerarLogExcel(FiltroPesquisaLogTipoDeParaDTO filtro) {
return tipoDeParaService.gerarLogExcel(filtro);
}
}
|
Java
|
UTF-8
| 1,829 | 2.46875 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package records;
import reservationPortalSystem.Payment;
import java.util.Date;
import java.util.HashMap;
/**
*
* @author ahmed
*/
public class CreditCard implements Payment
{
private int cardNumber;
private Date expireDate;
private String billingAddress;
public CreditCard()
{
cardNumber = 0;
expireDate = new Date();
billingAddress = "";
}
public CreditCard(int cardNumber, Date expireDate, String billingAddress)
{
this.cardNumber = cardNumber;
this.expireDate = expireDate;
this.billingAddress = billingAddress;
}
public String getBillingAddress()
{
return billingAddress;
}
public void setBillingAddress(String billingAddress)
{
this.billingAddress = billingAddress;
}
public int getCardNumber()
{
return cardNumber;
}
public void setCardNumber(int cardNumber)
{
this.cardNumber = cardNumber;
}
public Date getExpireDate()
{
return expireDate;
}
public void setExpireDate(Date expireDate)
{
this.expireDate = expireDate;
}
public HashMap getIformation()
{
HashMap<String, Object> fields = new HashMap<String, Object>(); //the hash map containig the fields of the object
fields.put("cardNumber", cardNumber);
fields.put("expireDate", expireDate);
fields.put("billingAddress", billingAddress);
return fields;
}
public void setInformation(HashMap fields)
{
cardNumber = (Integer) fields.get("cardNumber");
expireDate = (Date) fields.get("expireDate");
billingAddress = (String) fields.get("billingAddress");
}
}
|
C#
|
UTF-8
| 1,657 | 2.640625 | 3 |
[] |
no_license
|
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Bg_Fishing.Data;
using Bg_Fishing.Models;
using Bg_Fishing.Services.Contracts;
using Bg_Fishing.Utils;
using Bg_Fishing.Services.Models;
namespace Bg_Fishing.Services
{
public class NewsService : INewsService
{
private IDatabaseContext dbContext;
public NewsService(IDatabaseContext dbContext)
{
Validator.ValidateForNull(dbContext, paramName: "dbContext");
this.dbContext = dbContext;
}
public void Add(News news)
{
this.dbContext.News.Add(news);
}
public News FindById(string id)
{
var news = this.dbContext.News.Find(id);
return news;
}
public NewsModel GetNewsById(string id)
{
var news = this.dbContext.News.Find(id);
return NewsModel.Cast(news);
}
public IEnumerable<NewsModel> GetNews(int skip, int take)
{
var news = this.dbContext.News.Include(n => n.Comments)
.OrderByDescending(n => n.PostedOn)
.Skip(skip)
.Take(take);
if (news != null)
{
return news.Select(NewsModel.Cast);
}
return Enumerable.Empty<NewsModel>();
}
public int GetNewsCount()
{
return this.dbContext.News.Count();
}
public int Save()
{
return this.dbContext.Save();
}
}
}
|
Java
|
UTF-8
| 1,124 | 3.234375 | 3 |
[] |
no_license
|
package practice1;
public class mergebyarray {
public static void main(String args[]){
String A = "abcd";
String B = "acde";
String C ="";
String m = "aabccdde";
//System.out.print(merge(A,B,C));
System.out.print(merge(A,B,m));
}
public static boolean merge(String A,String B,String m){
if(A.length() + B.length() != m.length()){
return false;
}
int lenA = A.length();
int lenB = B.length();
boolean[][] dp = new boolean[lenA + 1][lenB + 1];
dp[0][0] = true;
for(int i = 1; i < lenA+1;i++){
if(A.charAt(i-1) == m.charAt(i-1)){
if(dp[0][i-1]){
dp[0][i] = true;
}
}
}
for(int p = 1; p < lenA+1;p++){
if(B.charAt(p-1) == m.charAt(p-1)){
if(dp[p-1][0]){
dp[p][0] = true;
}
}
}
for(int n = 1;n <= lenA;n++){
for(int q = 1;q <= lenB;q++){
if(B.charAt(q-1) ==m.charAt(n+q-1) || A.charAt(n-1) ==m.charAt(n+q-1))
if(dp[n-1][q] ||dp[n][q-1]){
dp[n][q] = true;
}
}
}
for(int l = 0;l <= lenA;l++){
for(int u = 0 ;u <= lenB;u++){
System.out.print(dp[l][u]);
}
System.out.println("");
}
return dp[lenA][lenB];
}
}
|
C++
|
UTF-8
| 460 | 3.65625 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
class MultiStream {
public:
MultiStream& add(std::ostream& s)
{
streams.push_back(&s);
return *this;
}
template<typename T> MultiStream& operator<<(const T& item)
{
for (std::ostream* s : streams)
{
*s << item;
}
return *this;
}
private:
std::vector<std::ostream*> streams;
};
int main()
{
MultiStream ms;
ms.add(std::cout).add(std::cerr);
ms << "Hello!\n";
return 0;
}
|
Java
|
UTF-8
| 1,387 | 3.046875 | 3 |
[] |
no_license
|
package com.billsplit.billsplit_app;
import java.util.ArrayList;
import com.billsplit.billsplit_app.Menu.*;
public class Billsplitter {
private Bill bill;
private ArrayList<Menu> menuList = new ArrayList<Menu>();
private int numMenus;
private Menu curMenu = null;
Billsplitter() {
bill = new Bill();
initializeMenuMap();
}
public void initializeMenuMap() {
menuList.add(new AddEntryMenu(bill));
menuList.add(new AddParticipantMenu(bill));
menuList.add(new RemoveParticipantMenu(bill));
menuList.add(new DisplayParticipantsMenu(bill));
menuList.add(new EnterTaxRateMenu(bill));
menuList.add(new EnterTipRateMenu(bill));
menuList.add(new EnterBillTotalMenu(bill));
menuList.add(new PrintIndividualBills(bill));
menuList.add(new ClearBillMenu(bill));
menuList.add(new ExitMenu());
numMenus = menuList.size();
}
public Bill getBill() {
return bill;
}
public void displayMainMenu() {
System.out.println("Welcome to Billsplit.");
while(true) {
displayChoiceMenu();
int choice = Input.getValidInt(0, numMenus - 1);
curMenu = menuList.get(choice);
curMenu.displayMenu();
}
}
void displayChoiceMenu() {
System.out.print("Select an option:\n");
for (int index = 0; index < menuList.size(); index++) {
Menu curMenu = menuList.get(index);
System.out.println(index + ") " + curMenu.choiceString());
}
}
}
|
Python
|
UTF-8
| 218 | 3.578125 | 4 |
[] |
no_license
|
def is_same(string1, string2):
s1 = list(string1)
s2 = list(string2)
if sorted(s1) == sorted(s2):
return True
else:
return False
print(is_same("yes", "sey"))
print(is_same("uy", "ui"))
|
Markdown
|
UTF-8
| 823 | 2.765625 | 3 |
[] |
no_license
|
# So Pekocko
Sixth project of the new web developer course at Openclassrooms.
**So-Pekocko** wants to develop an app for evaluating its hot sauces, called "**Piquante**".
The goal is to create an API with **NodeJS**, **Express** and **MongoDB** that will deliver all the functionalities to the frontend already in place.
---
📙 **Warning !**
I am aware that some critical data like the URI of the database are present in the repository. This is imposed by the training establishment for the validation of the project by the jury.
## Installation
**For both folders, the npm dependencies must be installed in order to start their server.**
1. In the frontend folder
npm install
npm start
2. In the backend folder
npm install
npm start
**And it's done!**
|
Java
|
UTF-8
| 6,191 | 1.960938 | 2 |
[] |
no_license
|
package com.sendmethen;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.support.v7.widget.Toolbar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.sendmethen.adapters.PublicMessagesAdapter;
import com.sendmethen.models.PublicMessages;
import com.sendmethen.retrofit.RestService;
import com.sendmethen.retrofitmodels.SendTextMsg;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class TextSendActivity extends AppCompatActivity {
private static final String ROOT_URL ="http://sendmethen.feturtles.com/" ;
private Button datePickerbtn;
private EditText futureDateinp;
private Toolbar toolbar;
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;
private int year, month, day;
private EditText msgSubject,msgEmail,msgText;
private Boolean isPublic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_send);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
futureDateinp=(EditText) findViewById(R.id.futureDateinp);
datePickerbtn= (Button) findViewById(R.id.datePickerbtn);
futureDateinp= (EditText) findViewById(R.id.futureDateinp);
radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radioButton1) {
isPublic = true;
} else if(checkedId == R.id.radioButton2) {
isPublic = false;
}
}
});
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
datePickerbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setDate();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.sendmethen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
// Something else
case R.id.doneBtn:
Log.w("My app","Submitted");
sendTextMsg();
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void sendTextMsg() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
RestService api = adapter.create(RestService.class);
SendTextMsg textmsg= new SendTextMsg();
msgText=(EditText) findViewById(R.id.msgText);
msgEmail=(EditText) findViewById(R.id.msgEmail);
msgSubject=(EditText) findViewById(R.id.msgSubject);
textmsg.type="text";
textmsg.text=msgText.getText().toString();
textmsg.subject=msgSubject.getText().toString();
textmsg.email=msgEmail.getText().toString();
textmsg.is_public=isPublic;
api.sendTextMsg(textmsg,new Callback<HashMap>() {
int return_obj;
@Override
public void success(HashMap responseVar, Response response) {
Log.w("My app succeded",new Gson().toJson(responseVar));
// return_obj=1;
}
@Override
public void failure(RetrofitError error) {
Log.w("My APp","App could not post the data");
error.printStackTrace();
}
});
}
@SuppressWarnings("deprecation")
public void setDate() {
showDialog(999);
// Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT).show();
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int i, int day) {
futureDateinp.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
|
Go
|
UTF-8
| 396 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
package gitbot
import "fmt"
// PayloadFork when someone forks a repo
type PayloadFork struct {
Forkee *Repository `json:"forkee"` // The created repository.
Repo *Repository `json:"repository"` // Repo
Sender *User `json:"sender"` // Sender
}
func (s PayloadFork) String() string {
return fmt.Sprintf("[%s] %s has forked the repository (%s)", s.Repo, s.Sender, s.Forkee)
}
|
C++
|
UTF-8
| 736 | 2.5625 | 3 |
[] |
no_license
|
#ifndef NAMED_PIPE_HPP_
#define NAMED_PIPE_HPP_
#include "FileDescriptorCommunicable.hpp"
class NamedPipe : public FileDescriptorCommunicable
{
public:
NamedPipe();
virtual ~NamedPipe();
virtual bool write(IMessage const &) const;
virtual bool read(IMessage &);
virtual void configureClient();
virtual void configureHost();
private:
static constexpr size_t buffSize = 4096;
static std::int32_t ndx;
static std::string const fifoIn;
static std::string const fifoOut;
enum
{
PIPE_READ = 0,
PIPE_WRITE,
NB_PIPES
};
int m_pipesIn[NB_PIPES];
int m_pipesOut[NB_PIPES];
bool m_isHost;
std::string m_fifoIn;
std::string m_fifoOut;
};
#endif // !NAMED_PIPE_HPP_
|
PHP
|
UTF-8
| 629 | 4.5 | 4 |
[] |
no_license
|
<?php
class Pessoa {
private $dados = array();
public function __set($nome, $valor) {
$this->dados[$nome] = $valor;
}
public function __get($nome) {
return $this->dados[$nome];
}
public function __toString() {
return "Tentei imprimir o objeto!";
}
public function __invoke() {
return "Objeto como função!";
}
}
$pessoa = new Pessoa();
$pessoa->nome = "Rafael";
$pessoa->idade = 17;
$pessoa->sexo = "M";
echo $pessoa->nome . "<br />";
echo $pessoa->idade . "<br />";
echo $pessoa->sexo . "<br />";
echo $pessoa . "<br />";
echo $pessoa();
|
Python
|
UTF-8
| 316 | 2.78125 | 3 |
[] |
no_license
|
from npy_balltree import BallTree
import numpy as np
import cPickle as pickle
X = np.random.random((10,3))
ball_tree = BallTree(X, 2)
ind, dist = ball_tree.query(X[0], 3)
print ind
print dist
s = pickle.dumps(ball_tree)
ball_tree2 = pickle.loads(s)
ind2, dist2 = ball_tree2.query(X[0], 3)
print ind2
print dist2
|
Java
|
UTF-8
| 2,243 | 4.25 | 4 |
[] |
no_license
|
package com.nola;
public class MathClass {
public static void mathClass(String[] args) {
//Math.round()
int result = Math.round(1.1F);
System.out.println("Round " + result);
// output will be : 1
//Math.ceil() - returns smallest integer
// that is greater or equal than number passed - round to top
int resultCiel = (int)Math.ceil(1.1F); // we need to cast it into integer
System.out.println("Ciel " + resultCiel);
//output will be : 2
// Math.floor() - round to bottom
int resultFloor = (int)Math.floor(1.1F);
System.out.println("Floor " + resultFloor);
// Math.max() - returns greater of 2 values passed
int maxResult = Math.max(1,467);
System.out.println("Max " + maxResult);
// result will be 467
// Math.min() - returns smaller of 2 values passed
int minResult = Math.min(1,467);
System.out.println("Min " + minResult);
// result will be 467
// Math.random() // generates random value between 0 and 1
//this method returns the DOUBLE!
double randomResult = Math.random();
System.out.println("Random " + randomResult);
// result will be something like this but always different number>>
// 0.0039055099539678784
// Generate random whole number from 1 to 100
// we use math random to generate random numbers
// to do this to get the number without decimal
//1 solutions : cast number into integer or use Math.round()
//1. solution
double randomRound = Math.round(Math.random()* 100);
System.out.println("Round to get random number " + randomRound);
// result will be randomNumber.0
// to remove 0 we need to cast it into integer.
int randomInteger = (int)Math.round(Math.random()* 100); // we need to cast it!
System.out.println("Round to get random number casting " + randomRound);
//we can even remove Math.round
int randomInteger2 = (int)(Math.random() * 100); // we need to add () for Math.random * 100
System.out.println("Round to get random number casting two " + randomInteger2);
}
}
|
C#
|
UTF-8
| 2,661 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Fredrick.src
{
[Serializable]
public class RectangleF : Transform
{
protected Vector2 _currentPosition;//current position of collider to be tested
protected float _width;
protected float _height;
public Vector2[] Corners { get; set; } = new Vector2[4];
public float Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public float Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
public Vector2 CurrentPosition
{
get
{
return _currentPosition;
}
set
{
_currentPosition = value;
}
}
public RectangleF()
{
}
public RectangleF(Vector2 position, float width, float height)
{
Position = position;
_width = width;
_height = height;
Corners = new Vector2[4];
Corners[0] = new Vector2(-width / 2, height / 2);
Corners[1] = new Vector2(width / 2, height / 2);
Corners[2] = new Vector2(width / 2, -height / 2);
Corners[3] = new Vector2(-width / 2, -height / 2);
}
public RectangleF(RectangleF original)
{
Position = new Vector2(original.Position.X, original.Position.Y);
_width = original.Width;
_height = original.Height;
Corners = new Vector2[4];
Corners[0] = new Vector2(-_width / 2, _height / 2);
Corners[1] = new Vector2(_width / 2, _height / 2);
Corners[2] = new Vector2(_width / 2, -_height / 2);
Corners[3] = new Vector2(-_width / 2, -_height / 2);
}
public void UpdatePosition(Vector2 currentPosition)
{
_currentPosition = currentPosition + Position;
}
public bool Intersect(RectangleF other)
{
if (_currentPosition.X + (Width / 2) < other.CurrentPosition.X - (other.Width / 2)) return false; // a is left of b
if (_currentPosition.X - (Width / 2) > other.CurrentPosition.X + (other.Width / 2)) return false; // a is right of b
if (_currentPosition.Y + (Height / 2) < other.CurrentPosition.Y - (other.Height / 2)) return false; // a is above b
if (_currentPosition.Y - (Height / 2) > other.CurrentPosition.Y + (other.Height / 2)) return false; // a is below b
return true; // boxes overlap
}
public bool Intersect(Vector2 other)
{
if (other.X > _currentPosition.X + (Width / 2)) return false;
if (other.X < _currentPosition.X - (Width / 2)) return false;
if (other.Y > _currentPosition.Y + (Height / 2)) return false;
if (other.Y < _currentPosition.Y - (Height / 2)) return false;
return true;
}
}
}
|
JavaScript
|
UTF-8
| 742 | 4.09375 | 4 |
[] |
no_license
|
// ************************************************************ STRING METHODS
let name = ' Cesar Jimenez ';
// Length property
console.log(name.length);
// Convert to upper case
console.log(name.toUpperCase());
// Convert to lower case
console.log(name.toLowerCase());
// Includes method
let password = 'abc123password098';
console.log(password.includes('password'));
console.log(password.includes('past'));
// Trim
console.log(name.trim());
// Challenge
let isValidPassword = function(password) {
return password.length >= 8 && !password.includes('password');
};
console.log(isValidPassword('asdpf')); // false
console.log(isValidPassword('abc123!@#$%^&')); // true
console.log(isValidPassword('abc123!password@#$%^&')); // false
|
Java
|
UTF-8
| 1,041 | 1.75 | 2 |
[] |
no_license
|
/*
* Copyright 2014 Alex Curran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amlcurran.messages.ui.image;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;
public interface CookieCutter {
void updateCircleRect(RectF circleRectF);
void updateBorderRect(RectF borderRectF);
void draw(Canvas canvas);
void updateImage(Bitmap bitmap);
void updateViewBounds(int height, int width);
void preDraw();
void drawWithSelector(Canvas canvas);
}
|
Java
|
UTF-8
| 401 | 3.15625 | 3 |
[] |
no_license
|
package helloworld;
/**
* @author Luke Hodinka
*/
public class HelloWorld
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
//Print to the screen
System.out.print("Hello World, my GitHub account name is MaddLu\n");
System.out.print("MaddLu is also my youtuber name. Just a fun fact.\n");
}
}
|
Markdown
|
UTF-8
| 1,934 | 2.625 | 3 |
[] |
no_license
|
---
layout: blog_by_tag_sketchnotes
category: sketchnotes
title: IWMW17
homepage: true
tag: iwmw17
meta: IWMW17 Blog Post and Sketchnotes
image: /iwmw17/iwmw17-intro-thumb.png
homepage: true
---
### Round up
The conference was excellent again this year - given the challenges of Brexit, and broader changes to the HE sector it was more upbeat than might have been expected. It seemed that there wasn’t much doom and gloom - instead people seemed to be confident in their abilities to meet the challenges. Mainly by building relationships and collaborating with people across the various organisations
For me, some major take aways -
The Service Design Manual at St Andrews was a practical tool to bring others across the organisation into to help spread good standards and practice. It’s likely that nit everyone needs something as extensive, but stating the teams’ opinions and decision so clearly in the open can only be good.
More broadly, thinking of threats as opportunities has been covered many times over the years, but the current climate really puts that to the test. Being optimistic at the start of what might be pretty difficult years ahead seems to me to be crucial.
I had so many good conversations with people in other Universities, seeing that we are ahead in some areas, behind in others. It’s been discussed before that the current state of HE might lead to some kind of contraction of the community around University Web teams, as people seek to gain some kind competitive advantage by discovering some killer technique or idea and not sharing it. This conference confirms to me what a wrong headed idea that would be.
Digital transformation was again on the agenda, but with people at very different stages and different approaches to make it work for them, neatly summarised by Stratos from Edinburgh -
> Anyone can copy your strategy, but nobody can copy your culture
*[HE]: Higher Education
|
Python
|
UTF-8
| 585 | 2.96875 | 3 |
[] |
no_license
|
import sys
class Responder:
def __init__(self):
#hello words to check
self.helloWords = ["ciao", "salve"]
self.aboutWords = ["chi sei", "che fai"]
def get_message (self, text):
for hw in self.helloWords:
if hw in text.lower():
return "Ciao sfigato!"
for aw in self.aboutWords:
if aw in text.lower():
return "Sono merdit e ti tengo aggiornato sui ritardi dei treni"
return "Che vuoi? So solo dirti se un treno sta in ritardo. Mandami il numero"
|
JavaScript
|
UTF-8
| 2,314 | 2.546875 | 3 |
[] |
no_license
|
#!/usr/bin/env node
import * as yargs from "yargs";
yargs
.scriptName("Bottom translator [JavaScript] 0.3.0")
.version("0.3.0")
.usage("$0 <cmd> [args]")
.command(
"$0",
"Nadir <chowdhurynadir0@outlook.com>\nFantastic (maybe) CLI for translating between bottom and human-readable text",
(yargs) => {
yargs
.option("bottomify", {
type: "boolean",
default: false,
description: "Translate text to bottom",
alias: "b",
})
.option("regress", {
type: "boolean",
default: false,
description: "Translate bottom to human-readable text (futile)",
alias: "r",
})
.positional("input", {
type: "string",
default: "",
description: "Input file [Default: stdin]",
alias: "i",
})
.positional("output", {
type: "string",
default: "",
description: "Output file [Default: stdout]",
alias: "o",
})
.check((argv) => {
if (
(!argv._.length && !argv.input) ||
(argv._.length && argv.input)
) {
throw new Error(
"Error: Either input text or the --input options must be provided."
);
}
if (argv.bottomify && argv.regress) {
throw new Error(
"Error: must not pass more than one of the following: --bottomify --regress"
);
}
return true;
});
},
function (argv) {
var bottomify = require("./bottomify");
var fs = require("fs");
function getText(): string {
if (argv._.length) {
return argv._[0].toString();
}
if (argv.input) {
return fs.readFileSync(argv.input, "utf8").toString();
}
}
function write(text: string) {
if (argv.output) {
fs.writeFileSync(argv.output, Buffer.from(text));
} else {
console.log(text);
}
}
if (argv.bottomify) {
write(bottomify.encode(getText()));
} else if (argv.regress) {
try {
write(bottomify.decode(getText()));
} catch (err) {
console.error(err.toString());
}
}
}
)
.help().argv;
|
Java
|
UTF-8
| 4,243 | 1.992188 | 2 |
[] |
no_license
|
package smartphone_specs.restuibu.com.smartphone_specs.activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.ButterKnife;
import smartphone_specs.restuibu.com.smartphone_specs.R;
import smartphone_specs.restuibu.com.smartphone_specs.adapter.ProductAdapter;
import smartphone_specs.restuibu.com.smartphone_specs.model.PurchaseItem;
import smartphone_specs.restuibu.com.smartphone_specs.util.Constant;
import smartphone_specs.restuibu.com.smartphone_specs.util.MyAlert;
import smartphone_specs.restuibu.com.smartphone_specs.util_billing.IabHelper;
import smartphone_specs.restuibu.com.smartphone_specs.util_billing.IabResult;
import smartphone_specs.restuibu.com.smartphone_specs.util_billing.Inventory;
import smartphone_specs.restuibu.com.smartphone_specs.util_billing.Purchase;
public class ProductsActivity extends AppCompatActivity {
//List<String> additionalSkuList = Arrays.asList("plafon_buy_50k");
private ListView listProduct;
public static IabHelper mHelper;
private ProductAdapter productAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
init();
}
private void init() {
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Choose Product");
listProduct = (ListView) findViewById(R.id.listView1);
ButterKnife.bind(ProductsActivity.this);
mHelper = new IabHelper(ProductsActivity.this, Constant.base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Toast.makeText(ProductsActivity.this, "Problem setting up In-app Billing: " + result, Toast.LENGTH_LONG).show();
} else {
loadProducts();
}
}
});
}
private void loadProducts() {
try {
mHelper.queryInventoryAsync(true, Constant.additionalSkuList, null, new IabHelper.QueryInventoryFinishedListener() {
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
ArrayList<PurchaseItem> items = new ArrayList<>();
for (String s : Constant.additionalSkuList) {
Purchase p = inv.getPurchase(s);
PurchaseItem item = new PurchaseItem();
item.setTitle(inv.getSkuDetails(s).getTitle());
item.setDescription(inv.getSkuDetails(s).getDescription());
item.setPrice(inv.getSkuDetails(s).getPrice());
item.setId(inv.getSkuDetails(s).getSku());
items.add(item);
}
productAdapter = new ProductAdapter(ProductsActivity.this, items);
listProduct.setAdapter(productAdapter);
}
});
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Toast.makeText(ProductsActivity.this, "onActivityResult(" + requestCode + "," + resultCode + "," + data, Toast.LENGTH_LONG).show();
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
super.onActivityResult(requestCode, resultCode, data);
} else {
Log.d(Constant.TAG, "onActivityResult handled by IABUtil.");
}
}
}
|
Java
|
UTF-8
| 385 | 2.015625 | 2 |
[
"MIT"
] |
permissive
|
package stories.deleteselectedprofile;
import framework.ModelContext;
public class DeleteSelectedProfileModelContext extends ModelContext {
private final String profileName;
public DeleteSelectedProfileModelContext(String profileName) {
super();
this.profileName = profileName;
}
public String getProfileName() {
return profileName;
}
}
|
Java
|
UTF-8
| 1,510 | 2.484375 | 2 |
[] |
no_license
|
package hr.fer.rassus.firsthomework.client;
import hr.fer.rassus.firsthomework.client.model.Measurement;
import hr.fer.rassus.firsthomework.client.model.SensorDescription;
import hr.fer.rassus.firsthomework.client.model.UserAddress;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class RestTemplateImplementation implements RestInterface {
private String baseURL;
private RestTemplate restTemplate;
public RestTemplateImplementation(String url) {
this.baseURL = url;
restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
}
@Override
public ResponseEntity<String> register(SensorDescription description) {
ResponseEntity<String> response = restTemplate.postForEntity(baseURL + "/register", description, String.class);
return response;
}
@Override
public UserAddress searchNeighbour(String username) {
UserAddress neighbourAddress = restTemplate.getForObject(baseURL + "/searchNeighbour/" + username, UserAddress.class);
return neighbourAddress;
}
@Override
public ResponseEntity<String> storeMeasurement(Measurement measurement) {
ResponseEntity<String> response = restTemplate.postForEntity(baseURL + "/storeMeasurement", measurement, String.class);
return response;
}
}
|
PHP
|
UTF-8
| 1,158 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Elections extends Model
{
use HasFactory;
protected $fillable = [
'tittle',
'start_dt',
'finish_dt',
];
public static function findLastElectionId($tittle,$start_dt,$finish_dt ) {
return DB::table('elections')
->where('tittle', '=', $tittle)
->where( 'start_dt', '=', $start_dt)
->where( 'finish_dt', '=', $finish_dt)
->select('id')->first();
}
public static function checkActivity($start_dt,$finish_dt ) {
$isActive = false;
date_default_timezone_set('Europe/Kiev');
$dateCurrent = Carbon::parse(date('Y/m/d h:i:s ', time()))->format('Y-m-d\TH:i');
$electionDateStart = Carbon::parse($start_dt)->format('Y-m-d\TH:i');
$electionDateFinish = Carbon::parse($finish_dt)->format('Y-m-d\TH:i');
if($dateCurrent>$electionDateStart && $dateCurrent<$electionDateFinish)$isActive = true;
return $isActive;
}
}
|
PHP
|
UTF-8
| 2,719 | 3.21875 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: standard
* Date: 4/26/18
* Time: 2:36 PM
*/
namespace App\Sorter;
class NewsSorter
{
/**
* News Entities to sort
*/
private $news;
/**
* Field to sort by
*/
private $criterion;
/**
* Direction to sort
*/
private $direction;
/**
* skip sorting if already done
*/
private $sorted = false;
/**
* Setup Sorter
*/
public function __construct($news=[], $criterion='date', $direction='ASC')
{
$this->news = $news;
$this->criterion = $criterion;
$this->direction = $direction;
}
/**
* @param mixed $news
*/
public function setNews($news): void
{
$this->news = $news;
$this->sorted = false;
}
/**
* @param string $criterion
*/
public function setCriterion(string $criterion): void
{
$this->criterion = $criterion;
$this->sorted = false;
}
/**
* @param string $direction
*/
public function setDirection(string $direction): void
{
$this->direction = $direction;
$this->sorted = false;
}
/**
* Quicksort algorithm
*
* @param $left
* @param $right
* @return array
*/
private function quicksort($left=null, $right=null): array
{
if (is_null($left)) $left = 0;
if (is_null($right)) $right = count($this->news);
if (!$this->sorted) {
$divisor = $this->divide($left, $right);
$this->quicksort($left, $divisor);
$this->quicksort($divisor, $right);
$this->sorted = true;
}
return $this->news;
}
/**
* Quicksort algorithm
*
* @param $left
* @param $right
* @return int
*/
private function divide($left, $right): int
{
$i = $left;
$j = $right -1;
$pivot = $this->news[rechts];
do {
while (
$this->news[$i]->lt($pivot, $this->criterion, $this->direction) and $i < $right - 1
) $i += 1;
while (
$this->news[$i]->gte($pivot, $this->criterion, $this->direction) and $i < $right - 1
) $j -= 1;
if ($i < $j) {
$temp = $this->news[$i];
$this->news[$i] = $this->news[$j];
$this->news[$j] = $temp;
}
} while ($i < $j);
if($this->news[$i]->gt($pivot, $this->criterion, $this->direction)) {
$temp = $this->news[$i];
$this->news[$i] = $this->news[$right];
$this->news[$right] = $temp;
}
return $i;
}
}
|
Ruby
|
UTF-8
| 32 | 2.578125 | 3 |
[] |
no_license
|
puts 'Hello, world!'
puts 1 + 2
|
Java
|
UTF-8
| 2,934 | 2.4375 | 2 |
[] |
no_license
|
package com.other;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import com.structure.PaperStructure;
public class paperAddSpecialUnit {
public static class paperAddSpecialUnitMap extends Mapper<Object, Text, Text, Text> {
Text keyOut = new Text();
Text valueOut = new Text();
@Override
protected void map(Object key, Text value, Mapper<Object, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
// TODO Auto-generated method stub
String[] infos = value.toString().split("\t");
if (infos.length == 10) {
keyOut.set(infos[0]);
context.write(keyOut, value);
}
if (infos.length == PaperStructure.fourth_author_f + 1) {
keyOut.set(infos[PaperStructure.PAPER_ID]);
context.write(keyOut, value);
}
}
}
public static class paperAddSpecialUnitReduce extends Reducer<Text, Text, Text, NullWritable> {
Text keyOut = new Text();
@Override
protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, NullWritable>.Context context)
throws IOException, InterruptedException {
// TODO Auto-generated method stub
String[] changeItem = null;
List<String[]> resultList = new ArrayList<String[]>();
for (Text value : values) {
String[] infos = value.toString().split("\t");
if (infos.length == 10) {
changeItem = infos;
}
if (infos.length == PaperStructure.fourth_author_f + 1) {
resultList.add(infos);
}
}
if (!resultList.isEmpty()) {
if (changeItem != null) {
for (String[] infos : resultList) {
if (infos[PaperStructure.unit].equals("null")) {
System.out.println(infos[PaperStructure.PAPER_ID] + ":" + infos[PaperStructure.unit]
+ "---->" + changeItem[2]);
infos[PaperStructure.first_organization] = changeItem[1];
infos[PaperStructure.organization] = changeItem[1];
infos[PaperStructure.unit] = changeItem[2];
infos[PaperStructure.unit_type] = changeItem[3];
infos[PaperStructure.unit_f] = changeItem[4];
infos[PaperStructure.type_code_f] = changeItem[5];
infos[PaperStructure.province_code_f] = changeItem[6];
infos[PaperStructure.unit_code_f] = changeItem[7];
infos[PaperStructure.rank_code_f] = changeItem[8];
infos[PaperStructure.city_f] = changeItem[9];
keyOut.set(StringUtils.join(Arrays.copyOf(infos, infos.length - 4), "\t"));
context.write(keyOut, NullWritable.get());
}
}
} else {
for (String[] infos : resultList) {
keyOut.set(StringUtils.join(Arrays.copyOf(infos, infos.length - 4), "\t"));
context.write(keyOut, NullWritable.get());
}
}
}
}
}
}
|
Markdown
|
UTF-8
| 1,596 | 3.328125 | 3 |
[] |
no_license
|
# Diabetic-Retinopathy
# Code
DR.py is a python script that tries to automatically detect and grade the severity of Diabetic Retinopathy from Fundus images. I am using images from the publicly available kaggle dataset. Please click on the link to download the dataset:
https://www.kaggle.com/c/diabetic-retinopathy-detection/data
As the dataset is huge (~80 to 90 thousand images), I am trying to train a deep network on a subset of 20000 images. The images from the dataset correspond to one of the five classes. However, the distribution of data is very skewed with class four and five having very few examples. Hence to balance the data distribution, I have appropriately weighted the data in each class before training.
Prior to training, I have also done additional preprocessing. Here are the steps:
1) As the size of the images is not the same, I resized all the images to a spatial dimension of 256x256.
2) Different images were acquired under different acquisition conditions. This has resulted in different illumination and lighting for different images. Hence, to counter these effects I have added an additional color normalization step where I divide each color image by the respective sum of individual channel images.
This is still work under progress.
Things to do:
1) Explore new ways to reduce the influence of illumination and color.
2) Investigating different network architectures.
3) Train on all the examples.
4) I am currently loading the full training data onto a numpy array. I plan to investigate more memory efficient strategies to read the training data.
|
Python
|
UTF-8
| 381 | 4.34375 | 4 |
[] |
no_license
|
# exercise 1
first_last_letter=input("Enter the first and last letters of you name please: ")
print("Your name starts with {} and ends with {}.".format(first_last_letter[0],first_last_letter[1]))
# exercise 2
txt="Dear {}, Your current balance is {}$"
name=input("Enter your full name please: ")
balance=float(input("Enter your balance please: "))
print(txt.format(name,balance))
|
Java
|
UTF-8
| 8,810 | 2.046875 | 2 |
[
"MIT"
] |
permissive
|
package com.mmadu.registration.documentation;
import com.mmadu.registration.entities.FieldType;
import com.mmadu.registration.providers.RegistrationProfileFormFieldsManager;
import com.mmadu.registration.repositories.FieldTypeRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.restdocs.request.ParameterDescriptor;
import java.util.Collections;
import java.util.List;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class FieldTypesDocumentation extends AbstractDocumentation {
@Autowired
private FieldTypeRepository fieldTypeRepository;
@MockBean
private RegistrationProfileFormFieldsManager registrationProfileFormFieldsManager;
@Test
void createFieldTypes() throws Exception {
FieldType fieldType = createNewFieldType();
mockMvc.perform(
post("/repo/fieldTypes")
.header(HttpHeaders.AUTHORIZATION, authorization("a.global.field_type.create"))
.content(objectMapper.writeValueAsString(fieldType))
).andExpect(status().isCreated())
.andDo(
document(DOCUMENTATION_NAME, requestFields(
fieldTypeFields()
))
);
}
private static List<FieldDescriptor> fieldTypeFields() {
return asList(
fieldWithPath("id").type("string").optional().description("Field Type ID"),
fieldWithPath("fieldTypePattern").description("Allowed string pattern for field type"),
fieldWithPath("min").description("Minimum value for field type"),
fieldWithPath("max").description("Maximum value for field type"),
fieldWithPath("style").description("Style applied to all fields of the type"),
fieldWithPath("type").description("Data type of to field type " +
"(integer, date, time, datetime, string, decimal)"),
fieldWithPath("css").description("css for all fields with this type (can be overriden by field css)"),
fieldWithPath("script").description("Script for field"),
fieldWithPath("classes").description("css classes for field"),
fieldWithPath("markup").description("HTML markup for field type"),
fieldWithPath("name").description("The field type name"),
fieldWithPath("enclosingElement").description("The element enclosing the field")
);
}
private FieldType createNewFieldType() {
FieldType fieldType = new FieldType();
fieldType.setId("1");
fieldType.setMin("10");
fieldType.setMax("100");
fieldType.setType("integer");
fieldType.setCss("");
fieldType.setScript("");
fieldType.setClasses(Collections.singletonList("form-control"));
fieldType.setFieldTypePattern("");
fieldType.setMarkup("<label for='$field.name' class='sr-only'>$field.label</label>" +
"<input type='number' id='$field.name' name='$field.name' class='form-control' " +
"placeholder='$field.placeholder' $maxValue $minValue autofocus " +
"$required $inputField $inputStyle $errorStyle >$errorDisplay");
fieldType.setName("Age");
fieldType.setEnclosingElement("div");
return fieldType;
}
@Test
void getFieldTypeById() throws Exception {
FieldType fieldType = fieldTypeRepository.save(createNewFieldType());
mockMvc.perform(
RestDocumentationRequestBuilders.get("/repo/fieldTypes/{fieldTypeId}",
fieldType.getId())
.header(HttpHeaders.AUTHORIZATION, authorization("a.global.field_type.read"))
).andExpect(status().isOk())
.andDo(
document(DOCUMENTATION_NAME, pathParameters(
fieldTypeIdParameters()
), relaxedResponseFields(
fieldTypeFields()
))
);
}
private ParameterDescriptor fieldTypeIdParameters() {
return parameterWithName("fieldTypeId").description("The field type ID");
}
@Test
void getAllFieldTypes() throws Exception {
fieldTypeRepository.save(createNewFieldType());
mockMvc.perform(
RestDocumentationRequestBuilders.get("/repo/fieldTypes")
.header(HttpHeaders.AUTHORIZATION, authorization("a.global.field_type.read"))
).andExpect(status().isOk())
.andDo(
document(DOCUMENTATION_NAME, relaxedResponseFields(
fieldTypeListFields()
))
);
}
private static List<FieldDescriptor> fieldTypeListFields() {
return asList(
fieldWithPath("_embedded.fieldTypes.[].fieldTypePattern")
.description("Allowed string pattern for field type"),
fieldWithPath("_embedded.fieldTypes.[].min").description("Minimum value for field type"),
fieldWithPath("_embedded.fieldTypes.[].max").description("Maximum value for field type"),
fieldWithPath("_embedded.fieldTypes.[].type").description("Data type of to field type " +
"(integer, date, time, datetime, string, decimal)"),
fieldWithPath("_embedded.fieldTypes.[].css")
.description("css for all fields with this type (can be overriden by field css)"),
fieldWithPath("_embedded.fieldTypes.[].script").description("Script for field"),
fieldWithPath("_embedded.fieldTypes.[].classes").description("css classes for field"),
fieldWithPath("_embedded.fieldTypes.[].markup").description("HTML markup for field type"),
fieldWithPath("_embedded.fieldTypes.[].name").description("The field type name"),
fieldWithPath("_embedded.fieldTypes.[].enclosingElement").description("The element enclosing the field")
);
}
@Test
void updateFieldTypeById() throws Exception {
final String modifiedName = "New Type";
FieldType fieldType = fieldTypeRepository.save(createNewFieldType());
mockMvc.perform(
RestDocumentationRequestBuilders.patch("/repo/fieldTypes/{fieldTypeId}", fieldType.getId())
.header(HttpHeaders.AUTHORIZATION, authorization("a.global.field_type.update"))
.content(
objectMapper.createObjectNode()
.put("name", modifiedName)
.toString()
)
).andExpect(status().isNoContent())
.andDo(
document(DOCUMENTATION_NAME, pathParameters(
fieldTypeIdParameters()
))
);
assertThat(fieldTypeRepository.findById(fieldType.getId()).get().getName(), equalTo(modifiedName));
}
@Test
void deleteFieldTypeById() throws Exception {
FieldType fieldType = fieldTypeRepository.save(createNewFieldType());
mockMvc.perform(
RestDocumentationRequestBuilders.delete("/repo/fieldTypes/{fieldTypeId}", fieldType.getId())
.header(HttpHeaders.AUTHORIZATION, authorization("a.global.field_type.delete"))
).andExpect(status().isNoContent())
.andDo(
document(DOCUMENTATION_NAME, pathParameters(
fieldTypeIdParameters()
))
);
assertThat(fieldTypeRepository.existsById(fieldType.getId()), equalTo(false));
}
}
|
C++
|
UTF-8
| 1,065 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
// Compilation Command: g++ "Simple Socket - Client.cpp" -o "Simple Socket - Client" -lwsock32
#include <iostream>
#include <winsock2.h>
const char* server_address = "127.0.0.1";
const u_short server_port = 8888;
int main()
{
std::cout << "Initialising Winsock...\n";
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa))
{
std::cout << "Initialisation failed with error code: " << WSAGetLastError() << '\n';
return 1;
}
std::cout << "Initialised\n";
SOCKET s;
// Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
std::cout << "Socket creation failed with error code: " << WSAGetLastError() << '\n';
return 1;
}
std::cout << "Socket created\n";
sockaddr_in server;
server.sin_addr.S_un.S_addr = inet_addr(server_address);
server.sin_family = AF_INET;
server.sin_port = htons(server_port);
// Connect to remote server
if (connect(s, (sockaddr *) &server, sizeof(server)) < 0)
{
std::cout << "Connect failed with error code: " << WSAGetLastError() << '\n';
return 1;
}
std::cout << "Connected\n";
}
|
Markdown
|
UTF-8
| 1,140 | 2.5625 | 3 |
[] |
no_license
|
# Article L1221-13
Les conditions dans lesquelles les employeurs sont assujettis à un versement destiné au financement des services de mobilité
sont fixées :
1° Hors de la région Ile-de-France : par les articles L. 2333-64 à L. 2333-71, L. 5722-7 et L. 5722-7-1 du code général des
collectivités territoriales et par l'article 74-1 de la loi n° 99-586 du 12 juillet 1999 relative au renforcement et à la
simplification de la coopération intercommunale ;
2° Pour la région Ile-de-France : par les articles L. 2531-2 à L. 2531-7 du même code.
**Liens relatifs à cet article**
_Cite_:
- Loi n°99-586 du 12 juillet 1999 - art. 74-1
- Code général des collectivités territoriales - art. L2333-64 (V)
- Code général des collectivités territoriales - art. L2531-2
- Code général des collectivités territoriales - art. L5722-7
- Code général des collectivités territoriales - art. L5722-7-1 (V)
_Modifié par_:
- Loi n°2019-1428 du 24 décembre 2019 - art. 13
_Cité par_:
- Code des transports - art. L1512-3 (V)
_Codifié par_:
- Ordonnance n°2010-1307 du 28 octobre 2010 - art. (V)
|
Markdown
|
UTF-8
| 4,918 | 2.796875 | 3 |
[] |
no_license
|
# Trunks-core
Trunks-core is the view part of trunks, its goal is only to add/modify or destroy components according to the JSON Component Declaration it receives.
It also exposes a global object wich is used to receive components specifications and also send the events to the client application.
This package is not enough on its own, the resulting build of trunks core aims to be packaged on the clients that will use the rendering API.
If your goal is to write GUI using Trunks, refer to your clientside package documentation.
If your goal is to write an adapter for anything not supported yet, follow this documentation.
# Roadmap
## Components
- [X] Input
- [X] Text
- [X] Button
- [X] Box
- [X] CheckBoxes
- [ ] Radio
- [X] ProgressBar
- [X] FontAwesome4 Icons
- [ ] Notification
- [ ] ColorPicker
- [\] Image (supported only via URL)
- [ ] Tabs
- [ ] Custom Stylesheet (string and like image)
- [ ] Custom JS (string and like image)
- [ ] Custom fonts (like image)
## Positionning
- [X] Absolute position
- [ ] Bulma Responsive
## Styling
- [X] Bulma colors
- [ ] RGB colors
## Events
- [X] onClick
- [X] onChange
- [ ] onEnter
## TrunksIO
- [X] AddComponent
- [X] EditComponent
- [X] DestroyComponent
- [X] sendEvent
# Developping on the core
### Installation
Install all npm packages with `npm install` and run the UI with `npm run start`.
When you run the Application you will only have a blank page. This is normal.
You can either access the hook via the Dev Tools console to populate a UI but we recommend you use the UI Test.
Launch `npm run uitests`, you will then have a lot of cypress scenarios you can add your own tests.
# Interacting with Trunks
Here is a simple schematics of how Trunks work until the final rendering
- Some code: represents user code written in Lua
- TrunksLua: represents a client that will interface the user code and translate it in the JSON component syntax for Trunks to render
- Trunks: Trunks core, this repository
[]
Events on go on the opposite direction, they will be sent from TrunksIO to TrunksLua and then sent to SomeCode
## Getting TrunksIO and interacting
To communicate with Trunks you need to first find it, we export a `TRUNKS` or `window.TRUNKS` global for interacting with Trunks.
You can either call it from JS or from your language of choice if you can send JS commands to the WebUI currently running Trunks.
### Adding a componenent
To add a component you must use function `TRUNKS.addComponent`, it takes only one parameter with the Component JSON.
Please note that the only actual mandatory field is the `id`. But be carefull, if you do not provide a `component` value, an error might show until you specify it!
You can always specify all orther fields during execution with the update method.
For example:
```javascript
const firstButton =
{
id: "Cypress1",
component: "Button",
text: "Hello world !",
position: {
positionType: "absolute",
posX: 0,
posY: 0
}
};
TRUNKS.addComponent(JSON.stringify(firstButton))
```
Note that the Id is already specified, the id must always be specified before adding the component it is your responsability to set the component id.
Will render a simple button on the top left of the screen:
[Insert button image here]
### Updating a component
To update a component, the only mandatory field is the id.
Every orther field will be merged with the orther fields of the component, this allows simple and atomic updates to fit your API.
For example to update the text displayed on the button:
```javascript
const updatePatch = {
id: "Cypress1",
text: "This is my new text !"
}
TRUNKS.updateComponent(JSON.stringify(updatePatch));
```
Or to change its position:
```javascript
const updatePatch2 = {
id: "Cypress1",
position: {
posX: 90
}
}
TRUNKS.updateComponent(JSON.stringify(updatePatch2));
```
As you can see, you don't need to provide all the values while updating the UI.
### Catching component events
In order to catch all component events you need to subscribe a function hook, this hook is the function that will always be called
when a even happends on an element (onClick, onEnter, etc etc).
```javascript
TRUNKS.setEventHook((event) => {
console.log(event);
});
```
After clicking the button created in the previous chapter it will call the hook with:
```json
{
"eventType": "onClick",
"eventPayload": {
"id": "Cypress1"
}
}
```
It will always return an id and may return the name if user has specified it alongisde the value if the component has one for this event.
The next step for you is to accuratly redirect the event to the corresponding component and update its representation.
# Component declaration syntax
# Events handling
|
JavaScript
|
UTF-8
| 1,285 | 3.140625 | 3 |
[] |
no_license
|
/* Does your browser support geolocation? */
if ("geolocation" in navigator) {
$('.js-geolocation').show();
} else {
$('.js-geolocation').hide();
}
/* Where in the world are you? */
$('.js-geolocation').on('click', function() {
navigator.geolocation.getCurrentPosition(function(position) {
loadWeather(position.coords.latitude+','+position.coords.longitude); //load weather using your lat/lng coordinates
});
});
/*
* Test Locations
* Denver lat/long: 39.740002, -104.991997
* Denver WOEID: 2391279
*/
$(document).ready(function() {
loadWeather('Denver','2391279'); //@params location, woeid
});
function loadWeather(location, woeid) {
$.simpleWeather({
woeid: woeid,
location: location,
unit: 'f',
success: function(weather) {
html = '<div class="location"><span class="city">'+weather.city+'</span><span class="state">'+weather.region+'</span> </div><ul>';
html += '<li></li><li><div id="weathercode">'+weather.code+'</div></li><li>'+weather.temp+'°</li>';
for(var i=0;i<2;i++) {
html += '<li>'+weather.forecast[i].high+'°</li>';
}
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
}
|
C++
|
UTF-8
| 561 | 2.578125 | 3 |
[] |
no_license
|
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N=2222;
int up[N], l[N], r[N];
int main() {
int n, m, k;
cin>>n>>m>>k;
char c;
for(int i=0;i<n;i++) for(int j=0;j<m;j++) {
scanf(" %c ", &c);
if(c == '.' || c == 'D') continue;
if(c == 'U') {
if(i&1) continue;
up[j]++;
}
if(c == 'L') {
if(j-i >= 0) l[j-i]++;
}
if(c == 'R') {
if(j+i < m) r[j+i]++;
}
}
cout << l[0] + r[0] + up[0];
for(int i=1;i<m;i++) cout << " " << l[i] + r[i] + up[i]; cout << endl;
return 0;
}
|
C++
|
UTF-8
| 1,672 | 3.453125 | 3 |
[] |
no_license
|
/**
* 算法训练 拦截导弹
*/
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main()
{
int n, dmax = -1;
vector<int> dp, vec;
/* 获取导弹依次飞来的高度 */
do
{
cin >> n;
vec.push_back(n);
}
while (getchar() != '\n');
/* 初始化 */
for (size_t i = 0; i < vec.size(); ++i)
dp.push_back(1);
/* dp[i]表示飞行高度高于第i + 1枚导弹的其他导弹的数量 */
for (size_t i = 1; i < vec.size(); ++i)
{
/* 接上一条,除此之外还要算上第i + 1枚导弹 */
for (size_t j = 0; j < i; ++j)
{
if (vec[j] >= vec[i])
dp[i] = max(dp[i], dp[j] + 1);
}
}
for (size_t i = 0; i < vec.size(); ++i)
{
if (dp[i] > dmax) dmax = dp[i];
}
cout << dmax << endl;
int sys = 0;
vector< vector<int> > svec;
/* 初始化 */
for (size_t i = 0; i < vec.size(); ++i)
svec.push_back(vector<int>());
for (size_t i = 0; i < vec.size(); ++i)
{
int cnt = 0, smax = 66666;
for (int j = 1; j <= sys; ++j)
{
/* 第j个系统成功拦截vec[i] */
if (svec[j].back() >= vec[i] && svec[j].back() < smax)
{
cnt = j; smax = svec[j].back();
}
}
/* 第sys个系统负责拦截vec[i] */
if (cnt == 0)
{
++sys;
svec[sys].push_back(vec[i]);
} /* 第cnt个系统负责拦截vec[i] */
else
svec[cnt].push_back(vec[i]);
}
cout << sys << endl;
return 0;
}
|
PHP
|
UTF-8
| 1,368 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* Send a message via SendTalk.
*
* @param string $api_key API key from SendTalk.
* @param string $phone Recipient's phone number (must start with country code).
* @param string $message_type The message type ("otp", "text", or "image").
* @param string $body The message body (text message or file URL for image).
* @param string $filename Optional. The name of the file (required for message type "image").
* @param string $caption Optional. The caption, if any (for message type "image").
* @return response
*/
function sendTalkSendMessage($api_key, $phone, $message_type, $body, $filename, $caption) {
$curl = curl_init();
$data = [
'phone' => $phone,
'messageType' => $message_type,
'body' => $body
];
if ($message_type != 'text' && $message_type != 'otp') {
$data['filename'] = $filename;
$data['caption'] = $caption;
}
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://sendtalk-api.taptalk.io/api/v1/message/send_whatsapp',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'API-Key: ' . $api_key,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
|
C++
|
UTF-8
| 3,826 | 2.71875 | 3 |
[] |
no_license
|
/*
Project Title: randomWalker
Description:
©Daniel Buzzo 2020
dan@buzzo.com
http://buzzo.com
https://github.com/danbz
*/
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofEnableAlphaBlending();
ofSetBackgroundColor(0);
//Audio?
int bufferSize = 512;
sampleRate = 44100;
phase = 0;
phaseAdder = 0.0f;
phaseAdderTarget = 0.0f;
volume = 0.1f;
bNoise = false;
lAudio.assign(bufferSize, 0.0);
rAudio.assign(bufferSize, 0.0);
soundStream.printDeviceList();
ofSoundStreamSettings settings;
settings.setOutListener(this);
settings.sampleRate = sampleRate;
settings.numOutputChannels = 2;
settings.numInputChannels = 0;
settings.bufferSize = bufferSize;
soundStream.setup(settings);
}
//--------------------------------------------------------------
void ofApp::update(){
walker.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
ofEnableBlendMode(OF_BLENDMODE_ADD);
walker.draw();
phaseAdderTarget = 1000.0f * (float)(walker.radius[walker.radius.size()-1] % 4); //attempt to change frequency
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
walker::walker(){
xyPoint = ofVec2f(ofGetWidth()/2, ofGetHeight()/2);
// make a first point in the centre of the screen
walk.push_back(xyPoint);
color.b = 200; // draw our dots white with random color and transparency
radius.push_back(5); // dotsize
}
//--------------------------------------------------------------
walker::~walker(){
}
//--------------------------------------------------------------
void walker::update(){
// choose a random direction for the next step
int stepSize = ofRandom(8); // how far is each step from the last step
int random = ofRandom(4);
switch (random) {
case 0: // up
xyPoint += ofVec2f(0, stepSize);
break;
case 1: // down
xyPoint += ofVec2f(0, -stepSize);
break;
case 2: // right
xyPoint += ofVec2f(stepSize, 0);
break;
case 3: // left
xyPoint += ofVec2f(-stepSize, 0);
break;
default:
break;
}
walk.push_back(xyPoint); // add our step into the list of steps
radius.push_back(random); // change the radius, too
}
//--------------------------------------------------------------
void walker::draw(){
ofSetColor( color);
for (int i=0; i<walk.size(); i++){ // loop though all the steps in the walk, drawing a point at each one
ofDrawCircle(walk[i], radius[i]);
}
}
void ofApp::audioOut(ofSoundBuffer & buffer){
//pan = 0.5f;
float leftScale = 1 - pan;
float rightScale = pan;
// sin (n) seems to have trouble when n is very large, so we
// keep phase in the range of 0-TWO_PI like this:
while (phase > TWO_PI){
phase -= TWO_PI;
}
if ( bNoise == true){
// ---------------------- noise --------------
for (size_t i = 0; i < buffer.getNumFrames(); i++){
lAudio[i] = buffer[i*buffer.getNumChannels() ] = ofRandom(0, 1) * volume * leftScale;
rAudio[i] = buffer[i*buffer.getNumChannels() + 1] = ofRandom(0, 1) * volume * rightScale;
}
} else {
phaseAdder = 0.95f * phaseAdder + 0.05f * phaseAdderTarget;
for (size_t i = 0; i < buffer.getNumFrames(); i++){
phase += phaseAdder;
float sample = sin(phase);
lAudio[i] = buffer[i*buffer.getNumChannels() ] = sample * volume * leftScale;
rAudio[i] = buffer[i*buffer.getNumChannels() + 1] = sample * volume * rightScale;
}
}
}
|
Python
|
UTF-8
| 1,966 | 3.421875 | 3 |
[] |
no_license
|
import time
from collections import OrderedDict
from typing import Dict
class Timer(object):
def __init__(self, name, start=False, log=False):
"""
:param str name: The name of the timer
:param bool start: start the timer now?
:param bool log: log time when exiting the context manager?
only applicable when the timer is used as a context manager
"""
self.name = name
self.time = 0.0
self._start_time = None
if start:
self._start_time = time.time()
self._log = log
self._timers = OrderedDict() # type: Dict[str, Timer]
def add_timer(self, name, start=False):
# type: (str, bool) -> Timer
if name not in self._timers:
self._timers[name] = Timer(name, start=start)
return self._timers[name]
def get_timer(self, name):
# type: (str) -> Timer
return self._timers[name]
def start(self, clear=False):
if clear:
self.time = 0.0
elif self._start_time is not None:
self.stop()
self._start_time = time.time()
def stop(self, log=False):
try:
self.time += time.time() - self._start_time
except TypeError:
if self._start_time is not None:
raise
else:
pass
self._start_time = None
if log:
self.log()
def log(self, indent=0):
print '%s%s time: %s' % ('| '*indent, self.name, self.time)
sub_timer_time = 0.0
for timer in self._timers.values():
timer.log(indent=indent+1)
sub_timer_time += timer.time
if self._timers and sub_timer_time < self.time:
print '%s__untracked__ time: %s' % ('| '*(indent+1), self.time-sub_timer_time)
def __enter__(self):
self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop(log=self._log)
|
C
|
UTF-8
| 2,428 | 3.40625 | 3 |
[] |
no_license
|
// Ian Schweer
// 22514022
// Simple implementation of bankers algorithm.
// Program only needs to determine the state of a resource allocation.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int arrayLessThan(int *X, int *Y, int P) {
int i = 0;
for (i = 0; i < P; i++)
if (Y[i] < X[i])
return 0;
return 1;
}
void printWork(int R, int *work) {
int i = 0;
for(; i < R; i++)
printf("%d\t", work[i]);
printf("\n\n");
}
int findI(int P, int R, int need[][R], int *work, int *finished, int *ret) {
int i = 0;
*ret = -1;
for (i = 0; i < P; i++) {
if (finished[i] == 0 && arrayLessThan(need[i], work, R)) {
*ret = i;
printf("Process%d is good\n", i + 1);
break;
}
}
return i != P ? 1 : 0;
}
int safety(int P, int R, int max[][R], int alloc[][R], int *aval, int need[][R]) {
// Assuming Work = Available.
int work[R], totalalloc[R], finished[P], i = 0, j = 0;
memset(finished, 0, sizeof(finished));
memset(work, 0, sizeof(finished));
memset(totalalloc, 0, sizeof(totalalloc));
// calculate the total allocated resources
// onced we finished, read values
// The actual amount of work is equal to the total available resources minus the amount
// already allocated.
for (j = 0; j < R; j++)
for (i = 0; i < P; i++)
totalalloc[j] += alloc[i][j];
for (i = 0; i < R; i++)
work[i] = aval[i] - totalalloc[i];
j = 0;
while (1) {
int val;
if (findI(P, R, need, work, finished, &val)) {
finished[val] = 1;
j++;
printf("------work-------\n");
printWork(R, work);
printf("-----alloc-------\n");
printWork(R, alloc[val]);
for(i = 0; i < R; i++)
work[i] += alloc[val][i];
}
if (val == -1) break;
}
return j == P ? 1 : 0;
}
int main() {
int P = 0, R = 0, i = 0, j = 0;
// read in P, R
scanf("%d", &P);
scanf("%d", &R);
if (P < 0) perror("No process count"), exit(-1);
if (R < 0) perror("No resouce count"), exit(-1);
int max[P][R], alloc[P][R], aval[R], need[P][R];
for (i = 0; i < R; i++)
scanf("%d", &aval[i]);
for (i = 0; i < P; i++)
for (j = 0; j < R; j++)
scanf("%d", &alloc[i][j]);
for (i = 0; i < P; i++)
for (j = 0; j < R; j++)
scanf("%d", &max[i][j]);
for (i=0; i < P; i++)
for (j = 0; j < R; j++)
need[i][j] = max[i][j] - alloc[i][j];
if (safety(P, R, max, alloc, aval, need)) {
printf("The system is in a safe state\n");
} else {
printf("The system is in an unsafe state\n");
}
return 0;
}
|
Python
|
UTF-8
| 670 | 3.734375 | 4 |
[] |
no_license
|
class SnakeNode(object):
def __init__(self,position,direction):
self.position = position
self.direction = direction
self.next()
def turn(self,direction):
self.direction = direction
self.next()
def next(self):
#up
if self.direction == 0:
self.nextPosition = (self.position[0],self.position[1]-1)
#down
if self.direction == 1:
self.nextPosition = (self.position[0],self.position[1]+1)
#left
if self.direction == 2:
self.nextPosition = (self.position[0]-1,self.position[1])
#right
if self.direction == 3:
self.nextPosition = (self.position[0]+1,self.position[1])
def run(self):
self.position = self.nextPosition
self.next()
|
Java
|
UTF-8
| 311 | 2.15625 | 2 |
[] |
no_license
|
package pl.sda.issuers.model;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class IssuerFacade {
private IssuerDetector detector;
public String identifyIssuer(String cardNo) {
return detector.detect(cardNo);
}
}
|
Markdown
|
UTF-8
| 1,463 | 2.609375 | 3 |
[] |
no_license
|
# Floating License Server
**WARNING**: DO NOT USE IN PRODUCTION
> Floating license servers should be stable and reliable. They often require
> manual intervention to restart, so you should avoid using them in a container
The paradigm used here has:
- a single Dockerfile to build many images
- a build arg for `PRODUCT` (one of `rsp`,`ssp`,`rspm`,`connect`,`rstudio`)
- a build arg for `PORT` (to expose the port that you want... just for image
reference later)
- a dynamically mapped "default config file" based on `PRODUCT`
- Note that this could easily be done with a `sed` command, since PORT is
all that changes...
- Further, this file is only read on service up, so we can honestly just
map it in as a mount (no reason to embed in the image)
Check out the [compose file](docker-compose.yml) that builds / starts
these images, using an environment variable to provide the LICENSE variable.
## Options
| PRODUCT | PORT | LICENSE |
|---------|------|-------------------------|
| rsp | 8989 | `RSP_FLOAT_LICENSE` |
| connect | 8999 | `RSC_FLOAT_LICENSE` |
| rspm | 8969 | `RSPM_FLOAT_LICENSE` |
| ssp | 8979 | `SSP_FLOAT_LICENSE` |
| rstudio | 9019 | `RSTUDIO_FLOAT_LICENSE` |
## More Resources
- [Floating License Server Downloads](https://www.rstudio.com/floating-license-servers/)
- [Documentation](https://support.rstudio.com/hc/en-us/articles/115011574507-Floating-Licenses)
|
JavaScript
|
UTF-8
| 1,090 | 3.71875 | 4 |
[] |
no_license
|
const Deque = require('collections/deque');
const string_case_permutations = (str) => {
let permutations = [];
permutations.push(str);
for(let i = 0; i < str.length; i ++) {
if (isNaN(parseInt(str[i], 10))) {
const n = permutations.length;
//Loop through all permutations
for (j = 0; j < n; j++) {
//get current permutation
const str = permutations[j].split('');
if (str[i] === str[i].toLowerCase()) {
str[i] = str[i].toUpperCase();
} else {
str[i] = str[i].toLowerCase();
}
//push new permutation to the list.
//we never pop off the list so it only grows.
permutations.push(str.join(''))
}
}
}
return permutations;
}
console.log(`String permutations are: ${string_case_permutations('ad52')}`);
console.log(`String permutations are: ${string_case_permutations('ab7c')}`);
|
C++
|
UTF-8
| 3,519 | 2.5625 | 3 |
[] |
no_license
|
#include "Globals.h"
#include "Vectors.h"
#include "Memory.h"
#include "Overlay.h"
#include <iostream>
#include <time.h>
#include <Psapi.h>
#include "Helpers.h"
#include "Input.h"
HWND gameWindow = FindWindow(NULL, L"Rainbow Six");
//Defining our globals
namespace Global {
HANDLE GameHandle = 0x0;
LPVOID BaseAddress = NULL;
std::string LocalName = "Name";
Memory Mem = Memory();
Overlay Over = Overlay();
BOOL Box = false;
BOOL Health = false;
BOOL Name = false;
BOOL Head = false;
BOOL Snapline = false;
BOOL Fov = false;
BOOL Aimbot = false;
BOOL Menu = true;
}
DWORD FindProcessId(const std::wstring& processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE)
return 0;
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
void OpenHandle() {
DWORD processID = FindProcessId(L"RainbowSix.exe");
Global::GameHandle = OpenProcess(PROCESS_ALL_ACCESS | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, processID);
}
static const char consoleNameAlphanum[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int consoleNameLength = sizeof(consoleNameAlphanum) - 1;
char genRandomConsoleName()
{
return consoleNameAlphanum[rand() % consoleNameLength];
}
int main()
{
srand(time(0));
std::wstring ConsoleNameStr;
for (unsigned int i = 0; i < 20; ++i)
{
ConsoleNameStr += genRandomConsoleName();
}
SetConsoleTitle(ConsoleNameStr.c_str());
Helpers::Enable("Siege External by Yao");
std::cout << "<------------------->" << std::endl;
if (gameWindow != 0) {
std::cout << "Game window found" << std::endl;
OpenHandle();
std::cout << "Local name: " << std::flush;
std::cin >> Global::LocalName;
Sleep(1000);
if (Global::GameHandle == INVALID_HANDLE_VALUE || Global::GameHandle == NULL || Global::GameHandle == (HANDLE)0x0) {
std::cout << "Invalid handle to R6" << std::endl;
system("pause");
return 1;
}
Global::Mem.SetBaseAddress();
std::cout << "Base address: " << std::hex << Global::Mem.GetBaseAddress() << std::dec << std::endl;
Global::Over.SetupWindow();
std::cout << "Overlay window set" << std::endl;
Input::GetInstance()->StartThread();
//Start the main loop
Global::Over.Loop();
system("pause");
return EXIT_SUCCESS;
return 0;
}
else {
std::cout << "Game must be running to continue." << std::endl;
std::cout << "" << std::endl;
system("pause");
return 0;
}
}
void Global::GetResolution(UINT horizontal, UINT vertical)
{
RECT desktop;
// Get a handle to the desktop window
const HWND hDesktop = FindWindowA(NULL, "Rainbow Six");
// Get the size of screen to the variable desktop
GetWindowRect(hDesktop, &desktop);
// The top left corner will have coordinates (0,0)
// and the bottom right corner will have coordinates
// (horizontal, vertical)
horizontal = desktop.right;
vertical = desktop.bottom;
}
|
JavaScript
|
UTF-8
| 4,485 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
/**
* @classdesc Utilities for re-shaping matrices
* @class matrix/shaping
* @hideconstructor
*/
var u = require('./mUtils');
var matrix = require('../matrix');
function matrix_cat_horizontal(A,B)
{
var M = [];
if(A.length != B.length)
{
throw 'Must have same number of rows'
}
M = u.matrix_copy(A);
for(var i =0; i<M.length;i++) // for rows of M
{
M[i] = M[i].concat(B[i]);
}
return M;
}
function matrix_push(A,B)
{
var aColumns = A[0].length;
var bColumns = B[0].length;
var M = u.matrix_copy(A);
if(aColumns != bColumns)
{
throw 'Column size must be the same';
}
for(var i =0; i < B.length; i++)
{
M.push(B[i]);
}
return M;
}
function matrix_get_columns(A,start,end)
{
var M = [];
var m = A.length;
var startPoint = start;
var length = 1;
if(typeof end != 'undefined')
{
length += end - start;
}
for(var i = 0; i <m; i++)
{
M[i] = [];
for(var j = 0; j < length; j++)
{
M[i][j] = A[i][j+startPoint];
}
}
return M;
}
function matrix_get_rows(A,start,end)
{
var M = [];
var m = A.length;
var startPoint = start;
var length = 1;
if(typeof end != 'undefined')
{
length += end - start;
}
for(i = 0; i < length; i++)
{
M[i] = A[i+start];
}
return M;
}
matrix.prototype.push = function(x)
{
var M = matrix_push(this.value,matrix.make(x).value);
return matrix.make(M);
};
matrix.catVertical = function(A,B)
{
return new matrix(matrix_push(matrix.make(A).value,matrix.make(B).value));
}
matrix.prototype.catVertical = function(x)
{
var M = matrix_push(this.value,matrix.make(x).value);
return matrix.make(M);
};
/**
* Append/concat a matrix vertically
* @function catV
* @returns {matrix}
* @memberof matrix/shaping
* @example
* var M = require('./src/matrix_lib');
* var A = M.range(3);
* console.log(A.catH(A).value) // Show value
* console.log(A.catH(A).size()) // Show size
* // Returns
* //[ [ 0 ], [ 1 ], [ 2 ], [ 0 ], [ 1 ], [ 2 ] ]
* //[ 6, 1 ]
*/
matrix.prototype.catV = function(x)
{
var M = matrix_push(this.value,matrix.make(x).value);
return matrix.make(M);
};
matrix.prototype.catHorizontal = function(x)
{
var M = matrix_cat_horizontal(this.value,matrix.make(x).value);
return matrix.make(M);
};
/**
* Append/concat a matrix horizontally
* @function catH
* @returns {matrix}
* @memberof matrix/shaping
* @example
* var M = require('./src/matrix_lib');
* var A = M.range(3);
* console.log(A.catH(A).value) // Show value
* console.log(A.catH(A).size()) // Show size
* // Returns
* //[ [ 0, 0 ], [ 1, 1 ], [ 2, 2 ] ]
* //[ 3, 2 ]
*/
matrix.prototype.catH = function(x)
{
var M = matrix_cat_horizontal(this.value,matrix.make(x).value);
return matrix.make(M);
};
matrix.catH = function()
{
var M = matrix.make(arguments[0]);
for(var i = 1; i < arguments.length; i++){
M = M.catH(arguments[i]);
}
return M;
}
matrix.prototype.shape = function()
{
return u.matrix_demension(this.value);
};
matrix.shape = function(A)
{
return u.matrix_demension(matrix.make(A).value);
}
matrix.size = matrix.shape;
/**
* Returns the size of a matrix as an array [m,n]
* @function size
* @returns {matrix}
* @memberof matrix/shaping
* @example
* var M = require('./src/matrix_lib');
* M.range(3).size()
* // returns [ 3, 1 ]
*/
matrix.prototype.size = matrix.prototype.shape;
matrix.prototype.columns = function(start,end)
{
return new matrix(matrix_get_columns(this.value,start,end));
}
matrix.columns = function(A,start,end)
{
return new matrix(matrix_get_columns(matrix.make(A).value,start,end));
}
matrix.prototype.column = function(m)
{
return new matrix(matrix_get_columns(this.value,m));
}
matrix.column = function(A,start)
{
return new matrix(matrix_get_columns(matrix.make(A).value,start));
}
matrix.prototype.rows = function(start,end)
{
return new matrix(matrix_get_rows(this.value,start,end));
}
matrix.rows = function(A,start,end)
{
return new matrix(matrix_get_rows(matrix.make(A).value,start,end));
}
matrix.prototype.row = function(start)
{
return new matrix(matrix_get_rows(this.value,start));
}
matrix.row = function(A,start)
{
return new matrix(matrix_get_rows(matrix.make(A).value,start));
}
|
Python
|
UTF-8
| 15,565 | 2.640625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
MAX_SIZE = 18
MAT_FILE = 'gbs_arr.pkl'
#MAT_FILE = 'genbound_arr.pkl'
BG_CUTOFF = 0.01
import argparse, pickle, pathlib, logging
import multiprocessing as mp
from itertools import combinations, accumulate
from operator import mul
import numpy as np
from fatgraph.fatgraph import Fatgraph
def findsheetat(k, mat):
if not np.allclose(mat, mat.T):
raise ValueError('Not a symmetric matrix.')
sheet = [k]
row = mat[k]
if np.count_nonzero(row) > 1:
raise ValueError
elif np.count_nonzero(row) < 1:
return sheet
prevk = k
thisk = np.flatnonzero(row)[0]
thisrow = mat[thisk]
while np.count_nonzero(thisrow) != 1:
if thisk in sheet:
raise BarrelError
sheet.append(thisk)
i, j = np.flatnonzero(thisrow)
if i == prevk:
nextk = j
else:
nextk = i
prevk, thisk = thisk, nextk
thisrow = mat[thisk]
else:
if thisk in sheet:
raise BarrelError
sheet.append(thisk)
return sheet
def findsheets(p_mat):
"Sheets from pairting matrix"
'''
findsheets([[0,0,1,0],
[0,0,1,0],
[0,0,0,0],
[0,0,0,0]])
--> [[0,2,1],[3]]
'''
wmat = np.triu(p_mat,1) + np.triu(p_mat,1).T
edges = [i for i in range(len(wmat))
if np.count_nonzero(wmat[i])<2]
sheets = []
while edges:
e = edges.pop(0)
sheet = findsheetat(e, wmat)
if sheet[0] > sheet[-1]:
sheet = sheet[::-1]
sheets.append(sheet)
if sheet[-1] in edges:
edges.remove(sheet[-1])
return sheets
def makevertices(sheets, o_mat):
"Vertices from sheets and orientation matrix."
'''
[[0,1,2]], [[False, False, False],
[False, False, True],
[False, False, False]]
--> [[(0,1),(11,10),(21,20)]]
'''
omat = np.triu(o_mat, 1) + np.triu(o_mat, 1).T
vertices = []
for sheet in sheets:
oseq = []
for i, j in zip(sheet, sheet[1:]):
if omat[i,j]:
oseq.append(1)
else:
oseq.append(-1)
oseq = list(accumulate(oseq, mul))
vertex = []
i = sheet[0]
vertex.append((i*10, i*10+1))
for i, s in enumerate(sheet[1:]):
if oseq[i]>0:
vertex.append((s*10, s*10+1))
else:
vertex.append((s*10+1, s*10))
first = min(vertex)
if first[0] > first[1]:
vertex = [(s[1],s[0]) for s in vertex]
vertices.append(vertex)
return vertices
def makefatgraph(vertices):
'''
Construct vertices, edges, & internal edges from given vertices.
'''
vdict = {}
for vertex in vertices:
#We want anti-clockwise ordering of half-edges on each vertex
l = [v[0] for v in vertex] + [v[1] for v in vertex][::-1]
r = len(vdict)
for i in range(r, r+len(l)):
vdict[l[i - r]] = i + 1
#Now we find edges
halfedges = sorted([i for vertex in vertices
for v in vertex
for i in v])
edges = [(i, j) for i, j in zip(halfedges, halfedges[1:])]
#edges = [(halfedges[i], halfedges[i+1])
# for i in range(1, len(halfedges)-2, 2)]
#Translate vertices and edges according to vdict
v = []
p = 1
for vertex in vertices:
v.append(tuple(range(p, 2*len(vertex)+p)))
p += 2*len(vertex)
iv = []
iedges = [e for vertex in vertices for e in vertex]
for e in iedges:
iv.append((vdict[e[0]], vdict[e[1]]))
e = []
for d in edges:
edge = (vdict[d[0]], vdict[d[1]])
if edge[0] > edge[1]:
edge = edge[::-1]
if edge not in iv:
e.append(edge)
return set(v), set(e), set(iv)
def compare(tmot, pmot, ori=False):
tpairs = {t[0] for t in tmot}
ppairs = {p[0] for p in pmot}
tlinks = {t for t in tmot}
plinks = {p for p in pmot}
strands = range(max(s for p in tpairs for s in p) + 1)
apairs = set(combinations(strands, 2))
if ori:
l = len(strands)
tmat = mot2mat2(tmot, l)
pmat = mot2mat2(pmot, l)
TP = np.count_nonzero(tmat*pmat)
FP = np.count_nonzero(pmat-tmat>0)
TN = np.count_nonzero(pmat+tmat==0) - l
FN = np.count_nonzero(tmat-pmat>0)
else:
TP = len(tpairs & ppairs)
FP = len(ppairs - tpairs)
TN = len((apairs - tpairs) & (apairs - ppairs))
FN = len(tpairs - ppairs)
c_pairs = set(p for p in pmot if p[0] in tpairs)
c_links = set(p for p in pmot if p in tmot and p[0] in tpairs)
return TP, FP, TN, FN, len(c_pairs), len(c_links)
def write_accepted(results, by_protein, count_proteins):
#vs = [.8, .85, .9, .95, 1]
vs = [.5, .6, .7, .8, .9, 1]
byvar_dic = {3: 'accuracy', 4: 'sensitivity', 5: 'specificity', 6: 'precision'}
byvar = 4 #Index of var to measure the result. 3=accuracy
with open(MAT_FILE, 'rb') as fh:
bg_mat = pickle.load(fh)
dim = bg_mat.ndim
n = MAX_SIZE + 1
nall = len(results)
accepted = [0 for i in range(n)]
rejected = [0 for i in range(n)]
nc = [0 for _ in vs] #number of candidates
ac = [0 for _ in vs] #accepted candidates
if by_protein:
np = [0 for _ in vs] #number of proteins
ap = [0 for _ in vs] #accepted proteins
l = []
hi_acc = 0
hi_rej = 0
n_cand = [[] for i in range(n)]
cand_count = 0
pid = ''
for r in results:
if pid and r[0] != pid:
#Process one pid
l.append(hi_acc >= hi_rej)
hi_acc = 0
hi_rej = 0
n_cand[last_size].append(cand_count)
cand_count = 0
if by_protein: #add np to nc
nc = [x+y for x,y in zip(nc, np)]
ac = [x+y for x,y in zip(ac, ap)]
np = [0 for _ in vs]
ap = [0 for _ in vs]
pid = r[0]
last_size = r[1]
#Highest accuracy among accepted/rejected
if r[2]:
accepted[r[1]] += 1
if r[byvar] > hi_acc:
hi_acc = r[byvar]
else:
rejected[r[1]] += 1
if r[byvar] > hi_rej:
hi_rej = r[byvar]
#Acceptance by minimum accuracy
for i, v in enumerate(vs):
if r[byvar] >= v:
if by_protein:
np[i] = 1
else:
nc[i] += 1
if r[2]:
if by_protein:
ap[i] = 1
else:
ac[i] += 1
#Count candidates
cand_count += 1
#Still need to process last pid
l.append(hi_acc >= hi_rej)
n_cand[r[1]].append(cand_count)
if by_protein:
nc = [x+y for x,y in zip(nc, np)]
ac = [x+y for x,y in zip(ac, ap)]
print('==========================================================')
print('\n')
if count_proteins:
print('Number of proteins')
print('# Strands :' + ''.join(['{:>8}'.format(i) for i in range(n)]))
print('# Proteins :' + ''.join(['{:>8}'.format(len(c)) for c in n_cand]))
print('#cands max.:' + ''.join(['{:>8}'.format(max(c, default=0)) for c in n_cand]))
print('#cands min.:' + ''.join(['{:>8}'.format(min(c, default=0)) for c in n_cand]))
avgs = []
for c in n_cand:
if len(c):
avgs.append(sum(c)/len(c))
else:
avgs.append(0)
print('Avg. cands :' + ''.join(['{:>8.1f}'.format(a) for a in avgs]))
print('\n')
print('Number of candidates accepted at v={} ({}D heatmap filter)'.format(BG_CUTOFF, dim))
print('# of strands:' + ''.join(['{:>8}'.format(i) for i in range(n)]))
print('Accepted :' + ''.join(['{:>8}'.format(accepted[i]) for i in range(n)]))
print('Rejected :' + ''.join(['{:>8}'.format(rejected[i]) for i in range(n)]))
pcts = [0 for i in range(n)]
for i in range(n):
try:
pcts[i] = accepted[i] / (accepted[i] + rejected[i])
except ZeroDivisionError:
pcts[i] = 0
print('Accepted % :' + ''.join(['{:>8.1%}'.format(pcts[i]) for i in range(n)]))
print('\nTotal accepted: {:.2%}'.format(sum(accepted) / (sum(accepted) + sum(rejected)) ))
by_var = byvar_dic[byvar]
print(
'Highest {} accepted: {}/{} ({:.2%})'.format(
by_var, sum(l), len(l), sum(l)/len(l))
)
if by_protein:
c = ' proteins '
nall = len(l)
else:
c = 'candidates'
for i, v in enumerate(vs):
print(
'# of {} at {:>4.0%} {} level: {:>8}/{:>8} ({:>6.2%})'.format(
c, v, by_var, nc[i], nall, nc[i]/nall
)
)
print(
'# of acceptance at {:>4.0%} {} level: {:>8}/{:>8} ({:>6.2%})'.format(
v, by_var, ac[i], nc[i], ac[i]/nc[i]
)
)
print('\n')
def mot2mat(mot, l):
"Make pairing and orientation matrices from motif"
p_mat = np.zeros((l,l), dtype=int)
o_mat = np.zeros((l,l), dtype=bool)
for link in mot:
i, j = link[0]
p_mat[i,j] = 1
o_mat[i,j] = link[1]
return p_mat, o_mat
def mot2mat2(mot, l):
"Make complete pairing matrix from motif"
pmat = np.zeros((l,l), dtype=int)
for link in mot:
i, j = link[0]
if not link[1]:
i, j = j, i
pmat[i,j] = 1
return pmat
def apply_filter(mots, v, size):
global BG_CUTOFF
BG_CUTOFF = v
with open(MAT_FILE, 'rb') as fh:
bg_mat = pickle.load(fh)
cmots = []
for mot in mots:
pmat, omat = mot2mat(mot, size)
sheets = findsheets(pmat)
vertices = makevertices(sheets, omat)
v, e, iv = makefatgraph(vertices)
fg = Fatgraph(v, e)
g = fg.genus
b = len(fg.boundaries)
k = max(len(sheet) for sheet in sheets)
if bg_mat.ndim == 2:
try:
score = bg_mat[g,b] / np.sum(bg_mat)
except IndexError:
score = 0
elif bg_mat.ndim == 3:
try:
score = bg_mat[g,b,k] / np.sum(bg_mat[:,:,k])
except IndexError:
score = 0
cmots.append((mot, score >= BG_CUTOFF))
return cmots
def applyfilter(mot, bg_mat, size):
logger = logging.getLogger()
try:
pmat, omat = mot2mat(mot, size)
except IndexError as e:
logger.info('{} with size {}'.format(mot, size))
raise e
sheets = findsheets(pmat)
vertices = makevertices(sheets, omat)
v, e, iv = makefatgraph(vertices)
fg = Fatgraph(v, e)
g = fg.genus
b = len(fg.boundaries)
k = max(len(sheet) for sheet in sheets)
if bg_mat.ndim == 2:
try:
score = bg_mat[g,b] / np.sum(bg_mat)
except IndexError:
score = 0
elif bg_mat.ndim == 3:
try:
score = bg_mat[g,b,k] / np.sum(bg_mat[:,:,k])
except IndexError:
score = 0
return score >= BG_CUTOFF
def computemany(data, o=False):
logger = logging.getLogger()
output = []
for pid, tmot, cmot in data:
try:
TP, FP, TN, FN, CP, CL = compare(tmot, cmot, o)
except IndexError as e:
print('IndexError in {}'.format(pid))
raise e
accuracy = (TP + TN) / (TP + TN + FP + FN)
sensitivity = TP / (TP + FN)
try:
specificity = TN / (TN + FP)
except ZeroDivisionError as e: #this could happen in 2-strand
specificity = 1.0
try:
precision = TP / (TP + FP)
except ZeroDivisionError as e:
precision = 0.0
size = len(set(e for p, _ in tmot for e in p))
with open(MAT_FILE, 'rb') as fh:
bg_mat = pickle.load(fh)
accepted = applyfilter(cmot, bg_mat, size)
output.append((pid, size, accepted, accuracy,
sensitivity, specificity, precision))
return output
def main(tdir, pdir, v, orientation, cpus, msize, cnt, byprot, raw):
logging.basicConfig(level=logging.INFO)
global BG_CUTOFF
BG_CUTOFF = v
global MAX_SIZE
MAX_SIZE = msize
pdir = pathlib.Path(pdir)
tdir = pathlib.Path(tdir)
cmots = {}
tmots = {}
for mf in pdir.glob('*.pkl'):
with open(tdir / '{}'.format(mf.name), 'rb') as fh:
themot = pickle.load(fh)
if max(e for p, _ in themot for e in p) > MAX_SIZE - 1:
continue
tmot = set()
for link in themot:
pair, ori = link
if pair[0] < pair[1]:
tmot.add(((pair[0], pair[1]), not ori[0]==ori[1]))
else:
tmot.add(((pair[1], pair[0]), not ori[0]==ori[1]))
tmots[mf.stem] = tmot
with open(mf, 'rb') as fh:
mots = pickle.load(fh)
cmots[mf.stem] = mots
i = 0
data = []
chunk = []
for k in cmots:
for mot in cmots[k]:
chunk.append((k, tmots[k], mot))
i += 1
if i == 5000:
data.append(chunk)
i = 0
chunk = []
else:
data.append(chunk)
pool = mp.Pool(processes=cpus)
res_objects = [pool.apply_async(
computemany, args=(chunk, orientation)
) for chunk in data]
pool.close()
pool.join()
results = [item for r in res_objects for item in r.get()]
if raw:
with open(raw, 'wb') as fh:
pickle.dump(results, fh)
else:
write_accepted(results, byprot, cnt)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Assessment of '
'genus-boundary filter for '
'selecting good candidate '
'structures.')
parser.add_argument('true_motif_dir',
help='Directory containing pickle files '
'of true motifs.')
parser.add_argument('pred_motif_dir',
help='Directory containing pickle files '
'of candidate motifs.')
parser.add_argument('-v', '--cutoff', type=float, default=0.01,
help='Cutoff value for heatmap filter')
parser.add_argument('-o', '--orientation', action='store_true',
help='Consider parallel/anti-parallel when '
'computing accuracy.')
parser.add_argument('-c', '--cpus', type=int,
help='Number of cores to use in computation')
parser.add_argument('-m', '--maxsize', type=int,
help='Maximum size of protein to consider')
parser.add_argument('-p', '--count_proteins', action='store_true',
help='Display count of proteins per size')
parser.add_argument('-b', '--by_protein', action='store_true',
help='Produce acceptance results by protein')
parser.add_argument('-r', '--raw_results',
help='Save raw results in this file and exit')
args = parser.parse_args()
main(args.true_motif_dir, args.pred_motif_dir,
args.cutoff, args.orientation, args.cpus, args.maxsize,
args.count_proteins, args.by_protein, args.raw_results)
|
Ruby
|
UTF-8
| 853 | 3.671875 | 4 |
[] |
no_license
|
puts 'Hello, now you can play the game "Rock, paper, scissors"'
print "Choose one of them: "
player_choice = gets.chomp
def random_choice
["rock", "paper", "scissors"].sample
end
pc_choice = random_choice
puts "The PC choice is #{pc_choice}."
if player_choice == pc_choice then puts "It's a tie!" end
if player_choice == "rock" and pc_choice == "scissors" then puts "You win!!!" end
if player_choice == "scissors" and pc_choice == "rock" then puts "You loose!!!" end
if player_choice == "paper" and pc_choice == "rock" then puts "You win!!!" end
if player_choice == "rock" and pc_choice == "paper" then puts "You loose!!!" end
if player_choice == "paper" and pc_choice == "scissors" then puts "You loose!!!" end
if player_choice == "scissors" and pc_choice == "paper" then puts "You win!!!" end
|
Python
|
UTF-8
| 86 | 3.390625 | 3 |
[] |
no_license
|
def silnia(x):
if x==0:
return 1
return x*silnia(x-1)
print(silnia(4))
|
C
|
UTF-8
| 1,546 | 3.6875 | 4 |
[] |
no_license
|
#include <stdio.h>
typedef struct Book{
char author[255];
char title[255];
char code_ISBN[255];
int price;
}Book;
int main(void){
Book bkdata[3];
int i;
for(i=0;i<3;i++){
printf("input author\n");
scanf("%s",bkdata[i].author);
printf("author= %s\n",bkdata[i].author);
printf("input title\n");
scanf("%s",bkdata[i].title);
printf("title= %s\n",bkdata[i].title);
printf("input ISBN\n");
scanf("%s",bkdata[i].code_ISBN);
printf("ISBN= %s\n",bkdata[i].code_ISBN);
printf("input price\n");
scanf("%d",&bkdata[i].price);
printf("price= %d\n",bkdata[i].price);
}
printf("\nBook Data\n");
for(i=0;i<3;i++){
printf("author= %s\n",bkdata[i].author);
printf("title= %s\n",bkdata[i].title);
printf("ISBN= %s\n",bkdata[i].code_ISBN);
printf("price= %d\n",bkdata[i].price);
}
}
/**********************************
input author
aaaa
author= aaaa
input title
aaaaa
title= aaaaa
input ISBN
aaaaaa
ISBN= aaaaaa
input price
1000
price= 1000
input author
bbbb
author= bbbb
input title
bbbbb
title= bbbbb
input ISBN
bbbbbb
ISBN= bbbbbb
input price
2000
price= 2000
input author
cccc
author= cccc
input title
cccc
title= cccc
input ISBN
cccccc
ISBN= cccccc
input price
3000
price= 3000
Book Data
author= aaaa
title= aaaaa
ISBN= aaaaaa
price= 1000
author= bbbb
title= bbbbb
ISBN= bbbbbb
price= 2000
author= cccc
title= cccc
ISBN= cccccc
price= 3000
********************/
|
Java
|
UTF-8
| 9,167 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
package service.entity;
import domain.CustomerOrder;
import domain.enums.EGuarantee;
import dto.*;
import exception.AppException;
import lombok.RequiredArgsConstructor;
import mapper.ModelMapper;
import repository.abstract_repository.entity.*;
import repository.impl.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@RequiredArgsConstructor
public class CustomerOrderService {
private final CustomerOrderRepository customerOrderRepository;
private final CustomerRepository customerRepository;
private final ProductRepository productRepository;
private final PaymentRepository paymentRepository;
public CustomerOrderService() {
this.customerOrderRepository = new CustomerOrderRepositoryImpl();
this.customerRepository = new CustomerRepositoryImpl();
this.productRepository = new ProductRepositoryImpl();
this.paymentRepository = new PaymentRepositoryImpl();
}
private Optional<CustomerOrderDto> addCustomerOrderToDb(CustomerOrderDto customerOrderDto) {
return customerOrderRepository
.addOrUpdate(ModelMapper.mapCustomerOrderDtoToCustomerOrder(customerOrderDto))
.map(ModelMapper::mapCustomerOrderToCustomerOrderDto);
}
private CustomerOrderDto setCustomerOrderComponentsFromDbIfTheyExist(CustomerOrderDto customerOrder) {
return CustomerOrderDto.builder()
.id(customerOrder.getId())
.payment(paymentRepository.findPaymentByEPayment(customerOrder.getPayment().getEpayment()).map(ModelMapper::mapPaymentToPaymentDto).orElse(customerOrder.getPayment()))
.discount(customerOrder.getDiscount())
.date(customerOrder.getDate())
.quantity(customerOrder.getQuantity())
.product(productRepository.findByNameAndCategoryAndProducer(customerOrder.getProduct().getName(),
ModelMapper.mapCategoryDtoToCategory(customerOrder.getProduct().getCategoryDto()),
ModelMapper.mapProducerDtoToProducer(customerOrder.getProduct().getProducerDto()))
.map(ModelMapper::mapProductToProductDto).orElse(customerOrder.getProduct()))
.customer(customerRepository.findByNameAndSurnameAndCountry(customerOrder.getCustomer().getName(),
customerOrder.getCustomer().getSurname(), ModelMapper.mapCountryDtoToCountry(customerOrder.getCustomer().getCountryDto()))
.map(ModelMapper::mapCustomerToCustomerDto).orElse(customerOrder.getCustomer()))
.build();
}
public void addCustomerOrderToDbFromUserInput(CustomerOrderDto customerOrder) {
addCustomerOrderToDb(setCustomerOrderComponentsFromDbIfTheyExist(customerOrder));
}
public Map<CategoryDto, Map<ProductDto, Integer>> getTheMostExpensiveProductsInEachCategoryWithAmountOfProductSales() {
List<CustomerOrderDto> customerOrderDtoList = getAllCustomerOrders();
return customerOrderDtoList.stream().map(customerOrder -> customerOrder.getProduct().getCategoryDto()).distinct()
.collect(Collectors.toMap(
Function.identity(),
category -> {
Map<CategoryDto, Integer> theHighestQuantityOrderInEachCategory = customerOrderDtoList.stream().filter(customerOrder -> customerOrder.getProduct().getCategoryDto().equals(category))
.collect(Collectors.groupingBy(customerOrder -> customerOrder.getProduct().getCategoryDto(),
Collectors.mapping(CustomerOrderDto::getQuantity, Collectors.reducing(0, (v1, v2) -> v1 >= v2 ? v1 : v2))));
return customerOrderDtoList.stream().filter(customerOrderDto -> customerOrderDto.getProduct().getCategoryDto().equals(category))
.collect(Collectors.groupingBy(CustomerOrderDto::getProduct,
Collectors.mapping(CustomerOrderDto::getQuantity, Collectors.filtering(
quantity -> quantity.intValue() == theHighestQuantityOrderInEachCategory.get(category).intValue(),
Collectors.reducing(0, (v1, v2) -> v1 > v2 ? v1 : v2)))));
}));
}
public List<ProductDto> getDistinctProductsOrderedByCustomerFromCountryAndWithAgeWithinRangeAndSortedByPriceDescOrder(String countryName, Integer minAge, Integer maxAge) {
if (countryName == null || minAge == null || maxAge == null) {
throw new AppException(String.format("At least one argument is null (countryName: %s minAge %d maxAge: %d", countryName, minAge, maxAge));
}
if (minAge > maxAge) {
throw new AppException(String.format("Min age: %d is greater than %d", minAge, maxAge));
}
return customerOrderRepository.findProductsOrderedByCustomersFromCountryAndWithAgeWithinRange(countryName, minAge, maxAge)
.stream()
.distinct()
.map(ModelMapper::mapProductToProductDto)
.sorted(Comparator.comparing(ProductDto::getPrice).reversed())
.collect(Collectors.toList());
}
public List<CustomerOrderDto> getOrdersWithinSpecifiedDateRangeAndWithPriceAfterDiscountHigherThan(LocalDate minDate, LocalDate maxDate, BigDecimal minPriceAfterDiscount) {
if (minDate == null || maxDate == null || minPriceAfterDiscount == null) {
throw new AppException(String.format("At least one of the method arguments's not valid: minDate:%s maxDate: %s minPriceAfterDiscount: %s", minDate, maxDate, minPriceAfterDiscount));
}
if (minDate.compareTo(maxDate) > 0) {
throw new AppException("minDate: " + minDate + " is after maxDate: " + maxDate);
}
return customerOrderRepository.
findOrdersOrderedWithinDateRangeAndWithPriceAfterDiscountHigherThan(minDate, maxDate, minPriceAfterDiscount)
.stream()
.map(ModelMapper::mapCustomerOrderToCustomerOrderDto)
.collect(Collectors.toList());
}
public Map<String, List<ProductDto>> getProductsWithActiveWarrantyAndWithSpecifiedGuaranteeComponentsGroupedByCategory(Set<EGuarantee> guaranteeComponents) {
if (guaranteeComponents == null) {
throw new AppException("guaranteeComponents collection object is null");
}
return customerOrderRepository.findProductsWithActiveWarranty()
.stream()
.map(ModelMapper::mapCustomerOrderToCustomerOrderDto)
.filter(customerOrder -> guaranteeComponents.isEmpty() || customerOrder.getProduct().getGuaranteeComponents().stream().anyMatch(guaranteeComponents::contains))
.map(CustomerOrderDto::getProduct)
.collect(Collectors.groupingBy(productDto -> productDto.getCategoryDto().getName()));
}
public Map<ProducerDto, List<ProductDto>> getProductsOrderedByCustomerGroupedByProducer(String customerName, String customerSurname, String countryName) {
if (customerName == null || customerSurname == null || countryName == null) {
throw new AppException("getProductsOrderedByCustomerGroupedByProducer - not valid input data");
}
return customerOrderRepository.findProductsOrderedByCustomer(customerName, customerSurname, countryName)
.stream()
.map(ModelMapper::mapCustomerOrderToCustomerOrderDto)
.collect(Collectors.groupingBy(c ->c.getProduct().getProducerDto(),
Collectors.mapping(CustomerOrderDto::getProduct, Collectors.toList())));
}
public Map<CustomerDto, Long> getCustomersWhoBoughtAtLeastOneProductProducedInHisNationalCountryAndThenFindNumberOfProductsProducedInDifferentCountryAndBoughtByHim() {
List<CustomerOrderDto> allCustomerOrders = getAllCustomerOrders();
return allCustomerOrders.stream().map(CustomerOrderDto::getCustomer).distinct()
.collect(Collectors.collectingAndThen(Collectors.toMap(
Function.identity(),
customer -> (Long) allCustomerOrders.stream().filter(customerOrder -> customerOrder.getCustomer().equals(customer))
.filter(customerOrder -> customerOrder.getProduct().getProducerDto().getCountry().equals(customer.getCountryDto())).map(CustomerOrderDto::getQuantity).count()),
map -> map.entrySet().stream().filter(e -> e.getValue() >= 1).map(Map.Entry::getKey).collect(Collectors.toMap(
Function.identity(),
customer -> (Long) allCustomerOrders.stream().filter(customerOrder -> customerOrder.getCustomer().equals(customer))
.filter(customerOrder -> !customerOrder.getProduct().getProducerDto().getCountry().equals(customer.getCountryDto())).map(CustomerOrderDto::getQuantity).count()))));
}
public void deleteAllCustomerOrders() {
customerOrderRepository.deleteAll();
}
public List<CustomerOrderDto> getAllCustomerOrders() {
return customerOrderRepository.findAll()
.stream()
.map(ModelMapper::mapCustomerOrderToCustomerOrderDto)
.collect(Collectors.toList());
}
}
|
Markdown
|
UTF-8
| 1,385 | 3 | 3 |
[] |
no_license
|
**一、引用aar的好处:**
为了**减少apk体积**和**加快gradle编译速度**,比起依赖module,引用**aar**更为友好。
<br>
**二、如何生成aar?**
**1.** 使用Terminal命令 gradlew 模块名:clean 以及 gradlew 模块名:assemble,会在模块名/build/outputs/aar文件夹下生成aar文件。
**2.** 直接运行一下项目也可以在上述文件夹生成aar文件。
<br>
**三、如何在library模块中正确引用aar?**
**1.** 在**application**所在模块的build.gradle文件中**allprojects**节点加入如下一段:
```
repositories {
flatDir {
dirs "$rootDir/aar"
}
}
```
**2.** 将aar文件复制到library模块下的aar文件夹;
**3.** 然后在library模块的build.gradle文件中还要正确引入:
- 在android节点下添加:
```
repositories {
flatDir {
dirs 'aar'
}
}
```
- dependencies节点:
```
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation(name: 'aar名字', ext: 'aar')
}
```
<font size="3" color="#ee1234" face="宋体">**有一个需要特别注意的地方:</font>
- 引用aar的library模块需要在build.gradle文件添加依赖原aar模块依赖的所有库;
- 引用的aar本身有依赖其他aar,需要复制其他aar文件到library模块的aar文件夹下;
|
Java
|
UTF-8
| 780 | 2.796875 | 3 |
[] |
no_license
|
package helpers;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class Screenshot {
public static void takeScreenshot(File filename, WebDriver driver) {
TakesScreenshot camera = (TakesScreenshot) driver;
byte[] imageBytes = camera.getScreenshotAs(OutputType.BYTES);
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(filename));
bos.write(imageBytes);
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
C++
|
UTF-8
| 1,718 | 2.828125 | 3 |
[] |
no_license
|
#include "serverMapIndex.h"
ServerMapIndex::ServerMapIndex()
{
mServerId = 0;
mRunning = false;
}
ServerMapIndex::~ServerMapIndex()
{
stop();
}
int ServerMapIndex::start(char const* filename)
{
int rc;
printf("TODO: ServerMapIndex::load\n");
mServerId = 0; // Read assigned serverid from file.
ServerMap* serverMap;
// HACK: Make up server id for now.
mServerId = 1;
// For each map defined in file
// serverMap = new ServerMap(getServerId());
// serverMap->load(mapFilename);
// addServerMap(serverMap);
// HACK: Make up a map for now.
MapInstanceId id;
id.mServerId = getServerId();
id.mMapId = 1;
id.mInstanceId = 1;
serverMap = new ServerMap(getServerId());
serverMap->setInstanceId(id);
addServerMap(serverMap);
printf("Loaded %s\n", filename);
printf("%d active maps.\n", getMapCount());
mRunning = true;
return 0;
}
int ServerMapIndex::stop()
{
if(!mRunning)
return 0;
//
// shutdown all ServerMaps
// delete all ServerMaps
for(MapInstanceIdServerMapMap::iterator i=mMaps.begin(); i!=mMaps.end(); ++i)
{
delete i->second;
}
mMaps.clear();
return 0;
}
ServerMap* ServerMapIndex::getServerMap(MapInstanceId const& id)
{
MapInstanceIdServerMapMap::iterator i = mMaps.find(id);
if(i == mMaps.end())
return NULL;
return i->second;
}
void ServerMapIndex::addServerMap(ServerMap* map)
{
mMaps[map->getInstanceId()] = map;
}
uint32_t ServerMapIndex::getServerId() const
{
return mServerId;
}
uint32_t ServerMapIndex::getMapCount() const
{
return mMaps.size();
}
|
Python
|
UTF-8
| 185 | 3.609375 | 4 |
[] |
no_license
|
while True:
number = int(input())
answer = number % 2
print (answer)
if answer == 0:
print("number is even")
if answer == 1:
print("number is odd")
|
Markdown
|
UTF-8
| 1,208 | 2.8125 | 3 |
[] |
no_license
|
# 코루틴
코루틴 자체에 의해서 제어되는 다중 진입점을 갖는 부프로그램
### 코루틴 매커니즘
- 호출과 피호출 부프로그램은 주-종속 관계라기보다는 대등관계
- 대칭적 단위 제어 모델 (symmetric unit control model)
- 다중 진입점을 가지며, 활성화 사이에 상태를 유지하여 두 번째 실행은 처음이 아닌 다른 지점에서 시작 가능
- 코루틴의 시작을 호출이 아닌 리쥼(resume)이라고 부른다.
### 코루틴의 실행
코루틴은 부분적으로 실행되고, 제어를 다른 곳으로 이동
코루틴 리쥼시, 제어를 다른 곳으로 전달한 문자 다음부터 시작한다.
### 코루틴의 의사-동시성 (quasi-concurrency)
- 주어진 시점에서 단 한 개의 코루틴만 실행된다.
- 코루틴들은 인터리브되어 실행되나 동시에 2개 이상 실행되지 않는다.
- 실행중인 코루틴들을 병렬로 실행되는 곳처럼 보인다.
### 루프를 갖는 코루틴 실행순서
코루틴은 흔히 리쥼을 포함하는 루프를 포함한다.

|
C++
|
UTF-8
| 3,372 | 2.765625 | 3 |
[] |
no_license
|
int g_maxValue = 6;
void PrintProbability(int number)
{
if (number < 1)
return;
int maxSum = number * g_maxValue;
int* pProbabilities = new int[maxSum - number + 1];
for (int i = number; i <= maxSum; ++i)
pProbabilities[i - number] = 0;
Probability(number, pProbabilities);
int total = pow((double)g_maxValue, number);
for (int i = number; i <= maxSum; ++i)
{
double ratio = (double)pProbabilities[i - number] / total;
printf("%d: %e\n", i, ratio);
}
delete[] pProbabilities;
}
void Probability(int number, int* pProbabilities)
{
for (int i = 1; i <= g_maxValue; ++i)
Probability(number, number, i, pProbabilities);
}
void Probability(int original, int current, int sum, int* pProbabilities)
{
if (current == 1)
{
pProbabilities[sum - original]++;
}
else
{
for (int i = 1; i <= g_maxValue; ++i)
{
Probability(original, current - 1, i + sum, pProbabilities);
}
}
}
void PrintProbability(int number)
{
if (number < 1)
{
return ;
}
int *pProbabilities[2];
pProbabilities[0] = new int[g_maxValue * number + 1];
pProbabilities[1] = new int[g_maxValue * number + 1];
for (int i = 0; i < g_maxValue; ++i)
{
pProbabilities[0][i] = 0;
pProbabilities[1][i] = 0;
}
int flag = 0;
for (int i = 1; i <= g_maxValue; ++i)
{
pProbabilities[flag][i] = 1;
}
for (int k = 2; k <= number; ++k)
{
for (int i = 0; i < k; ++i)
{
pProbabilities[1 - flag][i] = 0;
}
for (int i = k; i <= g_maxValue * k; ++i)
{
pProbabilities[1 - flag][i] = 0;
for (int j = 1; j <= i && j <= g_maxValue; ++j)
{
pProbabilities[1 - flag][i] += pProbabilities[flag][i - j];
}
}
flag = 1 - flag;
}
double total = pow( (double)g_maxValue, number);
for (int i = number; i <= g_maxValue * number; ++i)
{
double ratio = (double)pProbabilities[flag][i] / total;
printf("%d: %e\n", i, ratio);
}
delete[] pProbabilities[0];
delete[] pProbabilities[1];
}
// dp
class Solution {
public:
/**
* @param n an integer
* @return a list of pair<sum, probability>
*/
vector<pair<int, double>> dicesSum(int n) {
// Write your code here
vector<pair<int, double>> res;
if (n < 1)
return res;
vector<vector<double>> dp(n+1, vector<double>(6*n+1, 0));
for (int i = 1; i < n+1; ++i)
{
for (int j = 1; j < 6*i+1; ++j)
{
if (i == 1 || i == j || 6 * i == j)
{
dp[i][j] = 1;
}
else
{
for (int k = 1; k < 7; ++k)
{
if (i - 1 <= j - k)
dp[i][j] += dp[i - 1][j - k];
}
}
}
}
double total = pow(6.0, n);
for (int i = n; i < 6 * n + 1; ++i)
{
long double ratio = 0;
if (dp[n][i] != 0)
ratio = (long double)dp[n][i] / total;
res.push_back(make_pair(i, ratio));
}
return res;
}
};
|
Java
|
UTF-8
| 5,582 | 2.5 | 2 |
[] |
no_license
|
package com.ipn.mx.controller.servlets.admin;
import com.ipn.mx.model.dao.UsuarioDAO;
import com.ipn.mx.model.entities.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Usuario
*/
public class AlumnosServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String accion = request.getParameter("accion");
if (accion.equals("eliminar")) {
procesarEliminacionAlumno(request, response);
} else if (accion.equals("readAll")) {
procesarLecturaAlumnos(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private void procesarEliminacionAlumno(HttpServletRequest request, HttpServletResponse response) {
long matricula = Long.parseLong(request.getParameter("id"));
UsuarioDAO dao = new UsuarioDAO();
Usuario usuario = new Usuario();
usuario.setMatricula(matricula);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try (PrintWriter out = response.getWriter()) {
JsonObjectBuilder messageBuilder = Json.createObjectBuilder();
Usuario leido = dao.read(usuario);
dao.delete(leido);
messageBuilder.add("Estado", "OK");
out.print(messageBuilder.build());
out.flush();
} catch (IOException ex) {
System.out.println("Error de escritura en buffer de salida: " + ex.toString());
}
}
private void procesarLecturaAlumnos(HttpServletRequest request, HttpServletResponse response) throws IOException {
UsuarioDAO dao = new UsuarioDAO();
List<Object[]> alumnos = new ArrayList<>();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try (PrintWriter out = response.getWriter()) {
JsonObjectBuilder alumnoBuilder = Json.createObjectBuilder();
JsonArrayBuilder arrayAlumnosBuilder = Json.createArrayBuilder();
try {
alumnos = dao.findBytipoUsuario(2);
if (alumnos.isEmpty()) {
alumnoBuilder.add("status", "emptyArray");
} else {
for (Object[] alumno : alumnos) {
JsonObjectBuilder atributosProfesoresBuilder = Json.createObjectBuilder();
atributosProfesoresBuilder.add("ID", ((Usuario)alumno[0]).getMatricula())
.add("nombre", ((Usuario)alumno[0]).getNombreUsuario())
.add("apellidos", ((Usuario)alumno[0]).getPaternoUsuario() + " " + ((Usuario)alumno[0]).getMaternoUsuario())
.add("correo", ((Usuario)alumno[0]).getEmail())
.add("nickUsuario", ((Usuario)alumno[0]).getNickUsuario())
.add("claveUsuario", ((Usuario)alumno[0]).getClaveUsuario());
arrayAlumnosBuilder.add(atributosProfesoresBuilder);
}
alumnoBuilder.add("listaAlumnos", arrayAlumnosBuilder)
.add("status", "full");
}
} catch (NullPointerException nul) {
System.out.println("Error de null: " + nul.toString());
alumnoBuilder.add("status", "error");
}
out.print(alumnoBuilder.build());
out.flush();
}
}
}
|
Java
|
UTF-8
| 1,311 | 3.53125 | 4 |
[
"Apache-2.0"
] |
permissive
|
package com.twu.biblioteca;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Options {
private final Scanner sc;
private final PrintStream os;
private final String prompt;
private final List<String> keys = new ArrayList<>();
private final List<String> options = new ArrayList<>();
Options(Scanner sc, PrintStream os, String prompt) {
this.sc = sc;
this.os = os;
this.prompt = prompt;
}
void addOption(String key, String text) {
this.keys.add(key);
this.options.add(text);
}
private void show() {
this.os.println(this.prompt);
for (int i = 0; i < this.keys.size(); i++) {
// i + 1 so the options are numbered starting from 1
this.os.printf("(%d) %s\n", i + 1, options.get(i));
}
this.os.print("> ");
}
String getChoice() throws InvalidChoiceException {
this.show();
try {
var index = Integer.parseInt(sc.nextLine());
// choice - 1 here to convert it back to a 0-indexed value
return this.keys.get(index - 1);
} catch (NumberFormatException | IndexOutOfBoundsException e) {
throw new InvalidChoiceException();
}
}
}
|
Java
|
UTF-8
| 733 | 1.710938 | 2 |
[] |
no_license
|
package com.zhihu.android.profile.p1838a;
import com.zhihu.android.api.model.People;
import java8.util.p2234b.AbstractC32237i;
/* renamed from: com.zhihu.android.profile.a.-$$Lambda$b$C76oLPL5ZOHJGIN4ADQAgx_z0Po reason: invalid class name */
/* compiled from: lambda */
public final /* synthetic */ class $$Lambda$b$C76oLPL5ZOHJGIN4ADQAgx_z0Po implements AbstractC32237i {
public static final /* synthetic */ $$Lambda$b$C76oLPL5ZOHJGIN4ADQAgx_z0Po INSTANCE = new $$Lambda$b$C76oLPL5ZOHJGIN4ADQAgx_z0Po();
private /* synthetic */ $$Lambda$b$C76oLPL5ZOHJGIN4ADQAgx_z0Po() {
}
@Override // java8.util.p2234b.AbstractC32237i
public final Object apply(Object obj) {
return ((People) obj).vipInfo;
}
}
|
C#
|
UTF-8
| 531 | 2.578125 | 3 |
[] |
no_license
|
namespace LoadBalancer.Domain.Storage.Request
{
/// <summary>
/// A queue for <see cref="Models.Entities.Request"/>.
/// </summary>
public interface IRequestQueue
{
/// <summary>
/// Push to queue.
/// </summary>
void Add(Models.Entities.Request request);
/// <summary>
/// Pop from queue.
/// </summary>
Models.Entities.Request Get();
/// <summary>
/// Purge the queue full.
/// </summary>
void Purge();
}
}
|
Java
|
UTF-8
| 1,129 | 2.96875 | 3 |
[] |
no_license
|
package com.algorithm.loadbalance.polling;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class LBPollingWeight {
private static AtomicInteger index = new AtomicInteger();
public static void main(String[] args) {
Map<String, Integer> serverMap = new HashMap<>();
serverMap.put("192.168.1.1", 2);
serverMap.put("192.168.1.2", 6);
serverMap.put("192.168.1.3", 10);
Set<String> keySet = serverMap.keySet();
Iterator<String> iterator = keySet.iterator();
List<String> serverList = new ArrayList<>();
while (iterator.hasNext()) {
String server = iterator.next();
int weight = serverMap.get(server);
for (int i = 0; i < weight; i++) {
serverList.add(server);
}
}
for (int i = 0; i < 20; i++) {
if (index.get() == serverList.size()) {
index.set(0);
}
String server = serverList.get(index.get());
index.set(index.get() + 1);
System.out.println(server);
}
}
}
|
Shell
|
UTF-8
| 4,462 | 3.359375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/sh
# (C) Copyright 2005- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
# virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
#
. ./include.ctest.sh
label="grib_jpeg_test"
REDIRECT=/dev/null
BLACKLIST="totalLength,section5Length,section7Length,dataRepresentationTemplateNumber,typeOfPacking"
do_tests()
{
infile=${data_dir}/jpeg.grib2
outfile1=$infile.tmp_jpeg.1
outfile2=$infile.tmp_jpeg.2
rm -f $outfile1 $outfile2
# Test dump
${tools_dir}/grib_dump -Da $infile >/dev/null 2>&1
grib_check_key_equals $infile accuracy 14
${tools_dir}/grib_set -s packingType=grid_simple $infile $outfile1
${tools_dir}/grib_compare -P -b $BLACKLIST,typeOfCompressionUsed,targetCompressionRatio $infile $outfile1 > $REDIRECT
${tools_dir}/grib_set -s packingType=grid_jpeg $outfile1 $outfile2
${tools_dir}/grib_compare -P -b $BLACKLIST $outfile1 $outfile2 > $REDIRECT
templateNumber=`${tools_dir}/grib_get -p dataRepresentationTemplateNumber $outfile2`
if [ $templateNumber -ne 40 ]
then
echo dataRepresentationTemplateNumber=$templateNumber
exit 1
fi
rm -f $outfile1 $outfile2
infile=${data_dir}/reduced_latlon_surface.grib2
outfile1=$infile.tmp_jpeg.1
outfile2=$infile.tmp_jpeg.2
${tools_dir}/grib_set -s packingType=grid_jpeg $infile $outfile1
${tools_dir}/grib_compare -P -b $BLACKLIST $infile $outfile1 > $REDIRECT
${tools_dir}/grib_set -s packingType=grid_simple $outfile1 $outfile2
${tools_dir}/grib_compare -P -b $BLACKLIST,typeOfCompressionUsed,targetCompressionRatio $outfile1 $outfile2 > $REDIRECT
res1=`${tools_dir}/grib_get '-F%1.2f' -p min,max,avg $infile`
res2=`${tools_dir}/grib_get '-F%1.2f' -p min,max,avg $outfile1`
res3=`${tools_dir}/grib_get '-F%1.2f' -p min,max,avg $outfile2`
[ "$res1" = "$res2" ]
[ "$res1" = "$res3" ]
rm -f $outfile2
# GRIB-564 nearest 4 neighbours with JPEG packing
res=`${tools_dir}/grib_get -l 0,50 $outfile1`
[ "$res" = "2.47244 2.47244 2.5115 2.51931 " ]
rm -f $outfile1
# ECC-317: Constant JPEG field numberOfValues
# Create a JPEG encoded GRIB message to have all constant values and one more value
# than input GRIB message
infile=${data_dir}/jpeg.grib2
outfile=$infile.temp.const
tempFilter1=temp.grib_jpeg_test1.filt
tempFilter2=temp.grib_jpeg_test2.filt
numberOfValuesOrig=`${tools_dir}/grib_get -p numberOfValues $infile`
# Create a filter to print the values. This will be used to create another filter
echo " print \"set values={[values!1',']};\";" > $tempFilter1
echo " print \"write;\";" >> $tempFilter1
# Run the filter on the input. Change the output to set all values to 1 with an additional entry
# so the output file should have original numberOfValues+1
${tools_dir}/grib_filter $tempFilter1 $infile |\
sed -e 's/[0-9][0-9]*/1/' |\
sed -e 's/set values={1,/set values={1,1,/' > $tempFilter2
# Apply the new filter to create the constant field JPEG file
${tools_dir}/grib_filter -o $outfile $tempFilter2 $infile
[ -f $outfile ]
numberOfValuesNew=`expr $numberOfValuesOrig + 1`
grib_check_key_equals $outfile "numberOfValues" $numberOfValuesNew
rm -f $tempFilter1 $tempFilter2
rm -f $outfile $outfile2
}
# Generic test. Could use jasper or openjpeg depending on build
do_tests
# Specific test in case openjpeg is linked
set +u
# Check HAVE_LIBOPENJPEG is defined and is equal to 1
if [ "x$HAVE_LIBOPENJPEG" != x ]; then
if [ $HAVE_LIBOPENJPEG -eq 1 ]; then
export ECCODES_GRIB_JPEG=openjpeg
do_tests
fi
fi
# ECC-802
# -------
sample2=$ECCODES_SAMPLES_PATH/GRIB2.tmpl
tempFilt=temp.$label.filt
tempGrib=temp.$label.grib
cat > $tempFilt <<EOF
set Ni = 2;
set Nj = 2;
set bitsPerValue = 12;
set packingType = 'grid_jpeg';
set values = {-0.01, 11.99, 56.11, 98.99 };
write;
EOF
${tools_dir}/grib_filter -o $tempGrib $tempFilt $sample2 2>/dev/null
grib_check_key_equals $tempGrib 'packingType,numberOfValues' 'grid_jpeg 4'
stats=`${tools_dir}/grib_get -M -F%.2f -p min,max $tempGrib`
[ "$stats" = "-0.01 98.99" ]
rm -f $tempFilt $tempGrib
|
C
|
UTF-8
| 2,977 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef _VIDEOG_H_
#define _VIDEOG_H_
/** @defgroup videog videog
* @{
*
* Functions for using the video graphics
*/
//CONVERSIONS
#define BYTES_PER_PIXEL(x ) ((x+7)/8)
//useful macros
#define INDEX 0x105
#define DIRECT 0x114
#define MAX_FR_RATE 60
//colors (mode 0x114)
#define BLACK 0x0000
#define LIGHT_BLUE 0x05FF
#define GREEN 0x0F00
#define RED 0xF000
#define PINK 0xF0FF
#define YELLOW 0xFF00
#define GREY 0x7BEF
#define BLUE 0x00FF
#define ORANGE 0xEC00
#define WHITE 0xFFFF
/**
* @brief Paints a certain pixel with a given color.
*
* @param i - Ratio of bits/pixel
* @param x - Coordinate x of pixel
* @param y - Coordinate y of pixel
* @param color2 - Color to paint the pixel
* @return int - Return 0 upon success and non-zero otherwise
*/
int vg_draw_pixel(unsigned int i,uint16_t x,uint16_t y,uint32_t color2);
/**
* @brief Draws a vertical line on the screem
*
* @param x - Coordinate x of the line
* @param y - Coordinate y of the line
* @param len - Length of the line
* @param color - Color of the line
* @return int - Return 0 upon success and non-zero otherwise
*/
int vg_draw_vline(uint16_t x,uint16_t y,uint16_t len, uint32_t color);
/**
* @brief Draws a rectangle composed only by its borders
*
* @param x - Coordinate x of the rectangle
* @param y - Coordinate y of the rectangle
* @param width - Width of the rectangle
* @param height - Height of the rectangle
* @param color - Color of the rectangle
* @return int - Return 0 upon success and non-zero otherwise
*/
int vg_draw_rect_empty(uint16_t x,uint16_t y,uint16_t width,uint16_t height,uint32_t color);
/**
* @brief Draws a rectangle on the screen
*
* @param x - Coordinate x of the rectangle
* @param y - Coordinate y of the rectangle
* @param width - Width of the rectangle
* @param height - Height of the rectangle
* @param color - Color of the rectangle
* @return int - Return 0 upon success and non-zero otherwise
*/
int vg_draw_rectangle(uint16_t x,uint16_t y,uint16_t width,uint16_t height,uint32_t color);
/**
* @brief Gets the vertical resolution
*
* @return uint16_t - Returns the vertical resolution of the video graphics set
*/
uint16_t get_v_res();
/**
* @brief Gets the horizontal resolution
*
* @return uint16_t - Returns the horizontal resolution of the video graphics set
*/
uint16_t get_h_res();
/**
* @brief Gets the video memory buffer
*
* @return char* - Returns a pointer to the video memory
*/
char * get_mem();
/**
* @brief Gets the temporary video buffer
*
* @return char* - Returns a pointer to the temporary buffer
*/
char * get_tmp();
/**
* @brief Gets the vram size
*
* @return unsigned - Returns the vram size
*/
unsigned get_vram_size();
/**
* @brief Cleans the video memory, setting all its content to 0x0000 (Black)
*
*/
void clean_screen();
/**
* @brief Cleans the temporary buffer, setting all its content to 0x0000 (Black)
*
*/
void clean_tmp();
#endif // _VIDEOG_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.