language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 1,715 | 2.640625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoffeeManagement
{
class Invoice
{
private int invoiceID,tableID;
private string employeeUser, status;
private DateTime dateSale;
private double totalPayment;
public Invoice()
{
}
public Invoice(int invoiceID, int tableID, DateTime dateSale, string employeeUser, string status, double totalPayment)
{
this.InvoiceID = invoiceID;
this.TableID = tableID;
this.DateSale = dateSale;
this.EmployeeUser = employeeUser;
this.TotalPayment = totalPayment;
this.Status = status;
}
public int InvoiceID { get => invoiceID; set => invoiceID = value; }
public int TableID { get => tableID; set => tableID = value; }
public DateTime DateSale { get => dateSale; set => dateSale = value; }
public string EmployeeUser { get => employeeUser; set => employeeUser = value; }
public double TotalPayment { get => totalPayment; set => totalPayment = value; }
public string Status { get => status; set => status = value; }
public Invoice(DataRow row)
{
this.invoiceID = (int)row["invoiceId"];
this.tableID = (int)row["tableId"];
this.dateSale = (DateTime)row["dateSale"];
this.totalPayment = (double)row["totalPayment"];
this.employeeUser = (string)row["employeeUser"];
ulong u = (ulong)row["invoiceStatus"];
this.Status = (u == 0) ? "CheckedOut" : "Waiting";
}
}
}
|
C++ | SHIFT_JIS | 1,827 | 2.578125 | 3 | [] | no_license | // gpwb_[t@C
#include"GameL/DrawTexture.h"
#include"GameL/WinInputs.h"
#include"GameL/SceneManager.h"
#include"GameL/DrawFont.h"
#include"GameL/Audio.h"
#include"GameL/UserData.h"
#include"GameHead.h"
void CObjEnding::Init()
{
key_flag = false;
move_flag = false;//Qڂ̃tF[hNp
m_fade_f = false;//1ڂ̃tF[hNp
m_fade = 0.0f;
}
//ANV
void CObjEnding::Action()
{
//tF[hCpN
if (m_fade_f == false)
{
m_fade += 0.01f;//tF[h邭Ă
if (Input::GetConButtons(0, GAMEPAD_A) == true || Input::GetVKey('Z') == true)//tF[hCɃL[Ă
{
;//Ȃ
}
if (m_fade >= 1.0f)//Max܂ŗ
{
m_fade = 1.0f;//lMaxɌŒ肵
m_fade_f = true;//tF[hC~߂
key_flag = true;//L[\ɂ
}
}
if (Input::GetVKey('Z') == true &&key_flag==true && move_flag == false)
{
key_flag = false;
move_flag = true;
}
//ڂ̃tF[h
if (move_flag == true)//NĂ
{
m_fade -= 0.03f;//tF[hAEgĂ
}
if (m_fade <= -0.01f)//Sɐ^ÂɂȂ
{
Scene::SetScene(new CSceneStageSelect);//Xe[WZNgʂɓ]ڂ
}
}
//h[
void CObjEnding::Draw()
{
//`J[
float c[4] = { 1.0f,1.0f,1.0f,m_fade };//
RECT_F src; //`挳ʒu̐ݒ
RECT_F dst; //`\ʒu
//hoge1
src.m_top = 0.0f;
src.m_left = 0.0f;
src.m_right = 1280.0f;
src.m_bottom = 720.0f;
dst.m_top = 0.0f;
dst.m_left = 0.0f;
dst.m_right = 1280.0f;
dst.m_bottom = 720.0f;
Draw::Draw(1, &src, &dst, c, 0.0f);
Draw::Draw(0, &src, &dst, c, 0.0f);
}
|
Python | UTF-8 | 308 | 3.703125 | 4 | [
"Unlicense"
] | permissive | class Car:
def __init__(self, make, petrol_consumption):
self.make = make
self.petrol_consumption = petrol_consumption
def petrol_calculation(self, price = 22.5):
return self.petrol_consumption * price
ford = Car("ford", 10)
money = ford.petrol_calculation()
print(money)
|
Java | UTF-8 | 3,418 | 2.328125 | 2 | [] | no_license | package com.wurmonline.server.creatures;
import com.wurmonline.server.bodys.BodyFactory;
import java.io.IOException;
public class FakeCreatureStatus extends CreatureStatus {
public String savedCreatureName = "UNSET";
public FakeCreatureStatus(Creature creature, float x, float y, float rot, int layer) {
setPosition(new CreaturePos(creature.getWurmId(), x, y, 1, rot, 1, layer, -10, false));
this.template = creature.getTemplate();
statusHolder = creature;
try {
body = BodyFactory.getBody(creature, this.template.getBodyType(), this.template.getCentimetersHigh(), this.template.getCentimetersLong(), this.template.getCentimetersWide());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public void setVehicle(long l, byte b) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void setLoyalty(float v) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
public void load() throws Exception {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
public void savePosition(long l, boolean b, int i, boolean b1) throws IOException {
}
@Override
public boolean save() throws IOException {
return false;
}
@Override
public void setKingdom(byte b) throws IOException {
kingdom = b;
}
@Override
public void setDead(boolean b) throws IOException {
dead = b;
}
@Override
void updateAge(int i) throws IOException {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void setDominator(long l) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
public void setReborn(boolean b) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
public void setLastPolledLoyalty() {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void setOffline(boolean b) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
boolean setStayOnline(boolean b) {
return false;
}
@Override
void setDetectionSecs() {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void setType(byte b) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void updateFat() throws IOException {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void setInheritance(long l, long l1, long l2) throws IOException {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
public void setInventoryId(long l) throws IOException {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void saveCreatureName(String s) throws IOException {
savedCreatureName = s;
}
@Override
void setLastGroomed(long l) {
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
void setDisease(byte b) {
throw new UnsupportedOperationException("Not yet implemented.");
}
}
|
C | UTF-8 | 717 | 2.71875 | 3 | [
"MIT"
] | permissive | #include <assert.h>
#include <stdlib.h>
#include "new.h"
void * new(Class_t class, ...) {
Object_t * p = calloc(1, class->size); // Allocate space needed for object
assert(p);
p->class = class;
if(p->class->constructor) {
va_list ap;
va_start(ap, class);
p = p->class->constructor(p, &ap);
va_end(ap);
}
return p;
}
void delete(void * self) {
Object_t * obj = self;
if(self){
if (obj->class && obj->class->destructor){
self = obj->class->destructor(self);
}
if (obj->vtable){
free(obj->vtable);
}
}
free(self);
}
size_t sizeOf(const void * _self) {
const Object_t * self = _self;
assert(self && self->class);
return self->class->size;
}
|
C++ | UTF-8 | 2,281 | 3.421875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
// Algorithm:
// Step - 1: Preprocess the pattern. Make an array that stores the size of the longest prefix which
// is also a suffix for pattern[0:i]
// Step - 2: Searching
// Start comparison of pat[j] with j = 0 with characters of current window of text
// Keep matching characters txt[i] and pat[j] and keep incrementing i and j while pat[j] and text[i] keep matching
// When mismatch occurs -
// It is known that characters pat[0:j-1] match with text[i-j:i-1]
// preprocess[j-1] will tell us how many positions we can skip to start searching in the new window
void preprocessor(string pattern, int pat_len, int* preprocess) {
int longest_pref_len = 0;
preprocess[0] = 0;
for(int i = 1; i < pat_len;) {
if(pattern[i] == pattern[longest_pref_len]) {
preprocess[i] = ++longest_pref_len;
++i;
}
else {
if(longest_pref_len != 0) {
longest_pref_len = preprocess[longest_pref_len - 1];
}
else {
preprocess[i] = 0;
++i;
}
}
}
}
void search(string text, string pattern) {
int pat_len = pattern.size();
int text_len = text.size();
int preprocess[pat_len];
preprocessor(pattern, pat_len, preprocess);
int j = 0;
for(int i = 0; i < text_len; ) {
if(pattern[j] == text[i]) {
++j;
++i;
}
if(j == pat_len) {
// cout << "Pattern: " << pattern << " found at: " << i << '\n';
j = preprocess[j - 1];
}
else if (i < text_len && pattern[j] != text[i]) {
if (j != 0) {
// cout << j << endl;
j = preprocess[j - 1];
// cout << j << endl;
}
else {
++i;
}
}
}
}
void kmpSearch(string text, vector<string> patterns) {
for (string pattern: patterns) {
search(text, pattern);
}
}
int main() {
string text = "gcatcg";
vector<string> patterns = {"acc", "atc", "cat", "gcg"};
kmpSearch(text, patterns);
return 0;
}
|
Markdown | UTF-8 | 2,081 | 3.203125 | 3 | [] | no_license | # Sprint Review Title (02-12-2019)
## Work Scheduled/Performed
| Action | Brief Description | Completed
|---|---|---|
| Back-End Creation | Create an API that will be our web application back-end | [Yes] |
| Admin Front-End Creation | Create a visual web page which will be used for application adminstrators | [Yes] |
| App Improvement | Improve app design a little bit and rebuild comments system | [Yes] |
| Documentation | Make a document that explains all the work done | [Yes] |
## Burn-down Graph
*Here we need an image reflecting the advances in the Burn-down graph. Complementing the image, we need a small paragraph describing the Scrum Master opinion about the advances.*

During this sprint we've been creating the previous shown burndown graphic which is a lot better than the one we've built during sprint 1. Therefore, this one is really similar to the optimal one (grey line on the image). However, in the next sprint we should achieve a more accurate burndown especially during the initial part of the sprint.
## Burn-up (Velocity) Graph
*Here we need an image reflecting the advances in the Burn-up graph. Complementing the image, we need a small paragraph describing the Scrum Master opinion about the advances.*

As we can see in the previous image, in the second sprint we have a lot more hours but it can be justified.
On one hand, I must say that we've got a week more than in sprint 1.
On the other hand, I will explain you which issue made us do that amount of time. The main issue has been that one of our developers is still learning how to develop in android and , sincerely, we also spend our time on building and connecting the webpage.
To conclude, also stand out that our android developers decided to create the login and to improve the comments system.
## Client Improvements
For the conclusions we need to reflect improvement points reflected by our customer.
| Client Improvement | Description |
|---|---|
| None | - |
|
SQL | UTF-8 | 6,839 | 3.1875 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.5.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: 2016 年 10 月 20 日 19:02
-- サーバのバージョン: 10.1.10-MariaDB
-- PHP Version: 5.6.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cake_skytree`
--
-- --------------------------------------------------------
--
-- テーブルの構造 `addresses`
--
CREATE TABLE `addresses` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`country` text NOT NULL,
`postcode` text NOT NULL,
`state` text NOT NULL,
`city` text NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `addresses`
--
INSERT INTO `addresses` (`id`, `user_id`, `country`, `postcode`, `state`, `city`, `created`, `modified`) VALUES
(1, 3, 'Japan', '1111111', '東京都', '日野市', '2016-10-20 11:19:24', '2016-10-20 11:19:24');
-- --------------------------------------------------------
--
-- テーブルの構造 `card_histories`
--
CREATE TABLE `card_histories` (
`id` int(11) NOT NULL,
`sender` int(11) NOT NULL,
`receiver` int(11) NOT NULL,
`productcode` int(11) NOT NULL,
`message` text NOT NULL,
`is_delivered` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- テーブルの構造 `product_masters`
--
CREATE TABLE `product_masters` (
`id` int(11) NOT NULL,
`product_number` int(11) NOT NULL,
`product_picture` text,
`product_name` text NOT NULL,
`category` text NOT NULL,
`price` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `product_masters`
--
INSERT INTO `product_masters` (`id`, `product_number`, `product_picture`, `product_name`, `category`, `price`, `created`, `modified`) VALUES
(1, 123456, '8dba2adf462b05c19af87b693b171c6f.jpg', 'cute ghost', 'halloween', 300, '2016-10-20 22:41:42', '2016-10-20 22:41:42'),
(2, 2, '5de3081dd96b7e5ed8d91c45d8db9df5.jpg', 'ハロウィン少年団', 'halloween', 300, '2016-10-21 01:32:31', '2016-10-21 01:32:31'),
(3, 3, '8d224a32d859398d38ee92f0d00f1605.jpg', 'パンプキン', 'halloween', 300, '2016-10-21 01:33:43', '2016-10-21 01:33:43'),
(4, 4, '91cf01411e0caac7e487b31dc94db39e.jpg', 'ハロウィン飲み会', 'halloween', 300, '2016-10-21 01:34:49', '2016-10-21 01:34:49');
-- --------------------------------------------------------
--
-- テーブルの構造 `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`firstname` text NOT NULL,
`lastname` text NOT NULL,
`email` text NOT NULL,
`password` text NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `users`
--
INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `password`, `created`, `modified`) VALUES
(1, 'Yuuki', 'Noda', 'noda@test.com', '$2y$10$ukrtwk4Jr71HnaEJ96Yn4.X69smVIVxrs4Mpk4vxksYIjSE6M73Je', '2016-10-20 10:13:48', '2016-10-20 20:06:37'),
(2, 'Takuya', 'Kawamura', 'takuya@test.com', '$2y$10$mMfqYlZCelk15f5kjFOqH.DvVzqy/oRJHuM7kndHaHUmaMThOSLme', '2016-10-20 11:07:25', '2016-10-20 21:11:51'),
(3, 'Kiyokazu', 'Oami', 'kiyokazu@test.com', '123456', '2016-10-20 11:09:08', '2016-10-20 11:09:08'),
(4, 'Yui', 'Sasaki', 'sasaki@test.com', '123456', '2016-10-20 11:31:11', '2016-10-20 11:31:11'),
(5, 'test', 'test2', 'test@test.com', '$2y$10$LiqxD4MDUiYKU68htWgMxe0dav84r03hOO1IcW750g/PUeMtYl9G6', '2016-10-20 21:11:17', '2016-10-20 21:11:17'),
(6, 'Yukitoshi', 'Kihana', 'kihana@test.com', '$2y$10$OtkLt7JAxRrzuRRe8InMd.hU141OSuTpF16gSErTAv9RiwSvghGNW', '2016-10-20 22:23:11', '2016-10-20 22:23:11'),
(7, 'taro', 'Sumida', 'taro@test.com', '$2y$10$bpyQ3ypuvBMarIx3.7ZsMec13D7drRwE2wSLVkWQO/s.jSRGxcuDm', '2016-10-21 00:16:07', '2016-10-21 00:16:07');
-- --------------------------------------------------------
--
-- テーブルの構造 `user_settings`
--
CREATE TABLE `user_settings` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`picture` text,
`display_name` text,
`firstname_local` text,
`lastname_local` text,
`birthday` date DEFAULT NULL,
`language` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `user_settings`
--
INSERT INTO `user_settings` (`id`, `user_id`, `picture`, `display_name`, `firstname_local`, `lastname_local`, `birthday`, `language`, `created`, `modified`) VALUES
(6, 2, 'ed3c5e9f129035616c406b68c14c179f.jpg', '河村拓哉', 'たくや', '河村', NULL, 'Ja', '2016-10-20 17:09:55', '2016-10-20 17:09:55'),
(7, 1, '8198c4679bfbae5e8615df0ce4a9372c.jpg', '野田祐機', 'ゆうき', 'のだ', NULL, 'Ja', '2016-10-20 17:33:11', '2016-10-20 17:33:11'),
(8, 3, '11ab5cf8c0e9e8ee3c22b57c20a6567f.jpg', '大網きよかず', 'きよかず', 'おおあみ', NULL, 'Ja', '2016-10-20 22:24:15', '2016-10-20 22:24:15'),
(9, 7, '45671adc8337b56441772ceb807d9afa.jpg', '隅田太郎', 'たろう', 'すみだ', NULL, 'Ja', '2016-10-21 00:19:54', '2016-10-21 00:19:54');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `addresses`
--
ALTER TABLE `addresses`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `card_histories`
--
ALTER TABLE `card_histories`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `product_masters`
--
ALTER TABLE `product_masters`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `user_settings`
--
ALTER TABLE `user_settings`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `addresses`
--
ALTER TABLE `addresses`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `card_histories`
--
ALTER TABLE `card_histories`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `product_masters`
--
ALTER TABLE `product_masters`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `user_settings`
--
ALTER TABLE `user_settings`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Ruby | UTF-8 | 471 | 3.21875 | 3 | [] | no_license | class Market
attr_reader :name,
:vendors
def initialize(name)
@name = name
@vendors = []
@vendor_names = vendor_names
end
def add_vendor(vendor)
@vendors << vendor
end
def vendor_names
@vendor_names = @vendors.map do |vendor|
vendor.name
end
end
# def vendors_that_sell(item)
# @vendors.select do |vendor|
# vendor.inventory.include? item
# end
# require "pry"; binding.pry
# end
end
|
Java | UTF-8 | 1,207 | 2.546875 | 3 | [] | no_license | package schedule.microservice;
import java.util.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import schedule.model.*;
import schedule.repositories.*;
@Service
public class ServiceMicro {
@Autowired
ServiceRepo serviceRepo;
public ScheduleService saveOrUpdate(ScheduleService schedule)
{
return serviceRepo.save(schedule);
}
public ScheduleService getServiceById(long id)
{
return serviceRepo.findById(id).orElse(null);
}
public ArrayList<ScheduleService> getAllServices()
{
ArrayList<ScheduleService> services = new ArrayList<ScheduleService>();
for (ScheduleService service : serviceRepo.findAll())
{
services.add(service);
}
return services;
}
public boolean serviceExistsById(long id)
{
return serviceRepo.existsById(id);
}
public List<TimeAvailability> getAllAvailabilities(long id)
{
ScheduleService service = getServiceById(id);
if (service == null)
{
return null;
}
else
{
return service.getAvailablities();
}
}
}
|
Shell | UTF-8 | 377 | 3.59375 | 4 | [] | no_license | #!/usr/bin/env bash
append_suffix(){
case $1 in
1?) echo "${1}%{T5}th%{T-}" ;;
*1) echo "${1}%{T5}st%{T-}" ;;
*2) echo "${1}%{T5}nd%{T-}" ;;
*3) echo "${1}%{T5}rd%{T-}" ;;
*) echo "${1}%{T5}th%{T-}" ;;
esac
}
IFS=_ read -r month day rest < <(date "+%^B_%-d_%{F#4a4f4f}%^A%{F-} %R")
echo "$month $(append_suffix "$day") $rest"
|
Java | UTF-8 | 3,869 | 2.296875 | 2 | [] | no_license | package cityBuilder.gameScreen;
import java.util.ArrayList;
import cityBuilder.load.Screen;
import cityBuilder.load.TilesLoad;
import cityBuilder.load.build.buildActor;
import cityBuilder.load.build.buildInventory;
import cityBuilder.load.inventory.Inventory;
import cityBuilder.load.inventory.InventoryActor;
import cityBuilder.load.tileInfo.tileInfo;
import cityBuilder.objects.Citizen;
import cityBuilder.objects.Tile;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
public class GameScreen implements Screen
{
public Tile[][] tiles;
public static final String LOG = Simulation.class.getSimpleName();
private Simulation simulation;
private Renderer renderer;
private boolean game_finished = false;
private ArrayList<Citizen> citizens = new ArrayList<Citizen>();
int level;
public int Wood = 0;
public int Stone = 0;
public int Food = 0;
public int Gold = 0;
private TextureAtlas atlas;
private tileInfo tileinfo;
private TilesLoad tileLoad;
private InventoryActor inventoryActor;
private buildActor builder;
public GameScreen( Application app, OrthographicCamera camera, Stage stage, SpriteBatch batch, ArrayList<Citizen> citizens )
{
atlas = new TextureAtlas(Gdx.files.internal("TextureAtlas/isoAnno12.atlas"));
this.citizens = citizens;
Gdx.app.log( LOG, "Creating opening screen" );
Skin inventorySkin = new Skin(Gdx.files.internal("skins/inventoryTest/uiskin.json"));
Inventory inventory = new Inventory();
buildInventory buildInv = new buildInventory();
DragAndDrop dragAndDrop = new DragAndDrop();
tileinfo = new tileInfo( "", inventorySkin );
tileinfo.setVisible(false);
inventoryActor = new InventoryActor(this, inventory, dragAndDrop, inventorySkin);
inventoryActor.setPosition(10, 10);
inventoryActor.setMovable( false );
inventoryActor.setVisible( false );
builder = new buildActor(inventory, buildInv, "build", inventorySkin);
builder.setPosition(680, 150);
builder.setMovable( false );
builder.setVisible( false );
//map layout
tileLoad = new TilesLoad(atlas);
tiles = tileLoad.getTileArray();
simulation = new Simulation( this, inventory, inventoryActor, buildInv, builder, citizens, tiles, atlas );
renderer = new Renderer( this, camera, stage, batch, atlas, inventoryActor, builder, tileinfo, citizens, tiles );
}
@Override
public void update(float delta, float touchX, float touchY, float width, float height, boolean touched_down, boolean fast_press, boolean back_pressed, boolean down_pressed, boolean enter_pressed, boolean up_pressed, float distance )
{
simulation.update( delta );
simulation.variables( touchX, touchY, width, height, touched_down, fast_press, back_pressed, down_pressed, up_pressed, distance );
}
@Override
public void dispose()
{
renderer.dispose();
}
public void BuildFarm()
{
simulation.BuildFarm();
}
public void BuildWoodCutter()
{
simulation.BuildWoodCutter();
}
public void BuildWarehouse() {
simulation.BuildWarehouse();
}
public void buildRoad() {
simulation.buildRoad();
}
public void buildTree() {
simulation.buildTree();
}
public void Game_Finished( int level, ArrayList<Citizen> citizens )
{
game_finished = true;
this.level = level;
this.citizens = citizens;
}
@Override
public boolean isDone()
{
return game_finished;
}
@Override
public int level()
{
return level;
}
@Override
public void render( Application app )
{
renderer.render( simulation );
}
@Override
public ArrayList<Citizen> citizens()
{
return citizens;
}
} |
Python | UTF-8 | 504 | 4.3125 | 4 | [] | no_license | # Definiamo delle funzioni per l'esecuzione delle operazioni
# Addizione
def add(x, y):
return x+y
# Sottrazione
def subtract(x, y):
return x-y
# Moltiplicazione
def multiply(x, y):
return x*y
# Divisione
def divide(x, y):
if (y == 0):
raise ValueError("Can not divide by zero")
return x / y
# Potremmo testare in questo modo tutte le funzioni ma questa soluzione non è scalabile quando ci sono molte funzioni da testare
# print(add(3, 5))
# print(subtract(5, 2))
# .... |
Markdown | UTF-8 | 1,586 | 3.265625 | 3 | [] | no_license | # Селектор даты
[importance 5]
Создайте тройной селектор даты, который выступает как единый компонент. То есть, можно подписываться на `"select"` сразу у этого компонента.
Конструктор:
```js
var dateSelector = new DateSelector({
yearFrom: 2010, // начальный год в селекторе
yearTo: 2020, // конечный год в селекторе
value: new Date(2012, 2, 31) // текущая выбранная дата
});
```
События:
<ul>
<li>`select` -- при изменении даты.</li>
</ul>
Методы:
<ul>
<li>`setValue(date, quiet)` -- устанавливает дату `date`. Если второй аргумент `true`, то событие не генерируется.</li>
<li>`getElement()` -- возвращает DOM-элемент для компоненты для вставки в документ.</li>
</ul>
Использование - добавление в документ:
```js
dateSelector.getElement().appendTo('body');
```
Использование - подписка на изменение и вывод значения:
```js
$(dateSelector).on("select", function(e) {
$('#value').html(e.value);
});
```
Пример в действии:
[iframe border=1 src="solution"]
[edit task src="source"/]
P.S. При выборе месяца дни должны подстраиваться под него. Чтобы не было доступно 31 февраля. |
Ruby | UTF-8 | 464 | 2.546875 | 3 | [] | no_license | require_relative 'blog'
require_relative 'tweetable'
post = Blog::Post.new author: 'Lin Dong',
title: 'My Title',
body: 'Hi'
post.extend Tweetable
post.insert_comment Blog::Comment.new user: 'User1', body: "user1 body!"
post.insert_comment Blog::Comment.new user: nil, body: "user2 body!"
post.print
#begin
# post.tweet
#rescue Tweetable::NoBodyError
# puts 'Tweetable::NoBodyError'
#ensure
# puts 'ensure run'
#end
|
Markdown | UTF-8 | 2,647 | 3.28125 | 3 | [] | no_license | #Command Line (Windows)
This is an alternative interface to Windows which it is important to become familiar with. In this window you can type what are sometimes called 'DOS' commands. These commands let you have a finer level of control of your PC, and are particularly important for programmers to master.
Here are some simple commands:
- dir
- list all files in a directory
- cd ..
- change to a parent directory
- cd `<directory name>`
- change to a specific directory
It is essential that you become adept at these commands, and a few others.
Bear in mind that these commands always have a 'current directory' (a directory is another name for a folder). Try them now and see if you can 'navigate' to your `lab05a` folder. If the folder is located as shown here:

Then the commands to get there will look like this:

The commands entered above were
- `cd \`
- `cd course-work`
- `cd web-development`
- `cd lab05a`
Note in all of the above that the 'prompt' in the command window is always showing the 'current' drive/directory.
Also, if you have a 'space' in your directory (a bad idea generally), then you will have to use quotation marks in the commands. This can get difficulty to type, so in general it is best to adopt the following conventions.
- Never use spaces in directory or file names
- Never use upper case in directory or file names
- If you wish to use readable multiple words for a directory or file name, separate the words with '-'. e.g.
- web-development
- java-projects
Perhaps you might take this opportunity to adjust your workspace and projects to adopt the above conventions. If you do, then you will find that using DOS commands to navigate your folders will be considerably easier.
Before going on to the next step, make sure you are comfortable navigating in DOS around the file system, and in particular make sure you can navigate to your web development workspace.
Also, get used to using File Explorer in parellel - keeping an eye on where you are in the folder tree structure.
Finally, this 15 minute tutorial on the DOS command line might be worth skimming:
- [Windows Command Line in 15 Minutes](https://www.cs.princeton.edu/courses/archive/spr05/cos126/cmd-prompt.html)
The Command line we have been touring here has largely been superceeded by a newer application called `Powershell`. However, we will stick to the DOS shell here for the moment.
## Comand Line (Mac)
Commands on the mac as similiar - review this short tutorial here for the basics:
- <https://www.macworld.co.uk/feature/mac-software/how-use-terminal-on-mac-3608274/>
|
JavaScript | UTF-8 | 2,351 | 3.09375 | 3 | [
"MIT"
] | permissive | import { getCameras } from './Modules/fetchCameras.mjs';
import { displayCamera } from './Modules/displayCamera.mjs';
import { cart, addToCart, updateBadgeIcon, displayCartItems } from './Modules/cart.mjs';
main();
// Main function
/**
* Get and display the cameras.
* Add an event listener to add an item in the cart.
*/
async function main() {
try {
const cameras = await getCameras();
// console.log('Liste des APN :', cameras);
// Display all cameras
for (let i = 0; i < cameras.length; i++) {
const camera = cameras[i];
displayCamera(camera);
}
// Add event listener on icon add to cart
const targetAddToCart = document.querySelectorAll(".btn-addtocart");
for (const targetAddToCartElem of targetAddToCart) {
targetAddToCartElem.addEventListener("click", addToCartAction);
}
// Update cart object if an order exists
const checkOrderId = localStorage.getItem("orderId");
if (checkOrderId != null) {
cart.items = [];
cart.subtotal = 0;
localStorage.clear();
localStorage.setItem("cartIsEmpty", "true");
updateBadgeIcon(0);
displayCartItems(cart);
}
} catch(error) {
// alert("Erreur de connection avec le serveur ! \n" + error)
const message = "Une erreur est intervenue !";
const errorClass = "danger";
displayError(message, error, errorClass);
}
console.log("Etat de l'objet panier : ", cart);
}
/**
* Display the error message
*
* @param { string } message the message to be diplay to the user
* @param { string } error error return by the api
* @param { string } errorClass the class to be apply
*/
function displayError(message, error, errorClass) {
errorClass = "alert-" + errorClass
document.getElementById("error").classList.add(errorClass);
document.getElementById("error-message").classList.add("p-5");
document.getElementById("error-message").textContent = message + error;
}
/**
* Read the id of an item and call the addToCart function with the quantity to add.
*
*/
async function addToCartAction() {
let itemId = this.getAttribute("data-item-id");
await addToCart(itemId, 1);
} |
Java | UTF-8 | 202 | 1.507813 | 2 | [] | no_license | package net.boklab.core.client.user;
import com.google.gwt.event.shared.EventHandler;
public interface LoginRequestHandler extends EventHandler {
void onLoginRequest(LoginRequestEvent event);
}
|
C | UTF-8 | 1,272 | 3.984375 | 4 | [] | no_license |
/* Merge Sort
*
* COMPLEXITY: O(n log n)
*
* IMPLEMENTATION:
* Base Case: when the problem size is 1 or 0 the array is already sorted.
* Inductive Case: has three steps - recursively sort each half of the array and then
* merge the two together.
* Merging: set i and j to 1. If A1[i] is smaller than A2[j], append A1[i] to A and increase i by 1.
* otherwise, append A2[j] to A and increase j by 1. Repeat until i > len(A1) or j > len(A2).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int A[] = {4, 3, 2, 243, 4, 6, 395, 8};
//int A[] = {1};
int n = 8;
int B[1000];
void merge(int * a1, int * a2, int * a, int n1, int n2) {
int i = 0, j = 0;
int k = 0;
while (i < n1 && j < n2) {
if (a1[i] < a2[j]) {
a[k] = a1[i];
i++; k++;
} else {
a[k] = a2[j];
j++; k++;
}
}
while (j < n2) {
a[k] = a2[j];
j++; k++;
}
while (i < n1) {
a[k] = a1[i];
i++; k++;
}
}
void merge_sort(int * a, int n) {
if (n < 2) return;
int m = n/2;
merge_sort(a, m);
merge_sort(a+m, n-m);
// copy a1 and a2
memcpy(B, a, sizeof(int) * m);
memcpy(B+m, a+m, sizeof(int) * (n-m));
merge(B, B+m, a, m, n-m);
}
int main(void) {
merge_sort(A, n);
for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
}
return 0;
}
|
Ruby | UTF-8 | 127 | 2.515625 | 3 | [] | no_license | #!/usr/bin/ruby
str = <<END
This is super long strings
with multiple lines
and different special characters.
END
print str
|
C# | UTF-8 | 1,417 | 2.8125 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PlayerType
{
Player,
AI
};
public class PlayerModel
{
string name = "";
int money = 0;
int score = 0;
int stayFieldId = 0;
PlayerType playerType;
public PlayerModel(string name, int money, int score, PlayerType playerType)
{
this.name = name;
this.money = money;
this.score = score;
this.playerType = playerType;
}
public PlayerType GetPlayerType
{
get { return playerType; }
}
public string GetMoneyAsString
{
get
{
return this.money.ToString();
}
}
public int GetMoney
{
get
{
return this.money;
}
}
public string GetName
{
get
{
return this.name;
}
}
public int GetFieldID
{
get
{
return stayFieldId;
}
}
public void AddScore(int score)
{
this.score = score;
}
/*
* Add money for Player
* */
public void AddMoney(int money)
{
this.money += money;
}
/*
* Set Field Id for Play Chip
* */
public void SetFieldPosition(int id)
{
this.stayFieldId = id;
/*if(this.playerType == PlayerType.Player)
Debug.Log(id);*/
}
}
|
C++ | UTF-8 | 312 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<string>
#include<omp.h>
#include<stdio.h>
#include<cstring>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int n, a, b;
scanf("%d%d%d",&n,&a,&b);
if ((n - 1) % (a + b) >= a)
printf("Alice\n");
else
printf("Bob\n");
}
return 0;
}
|
C | UTF-8 | 805 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
int main(){
int queue[100], q_size, head, seek =0, diff;
float avg;
printf("%s\n", "***FCFS Disk Scheduling Algorithm***");
printf("%s\n", "Enter the size of the queue");
scanf("%d", &q_size);
printf("%s\n", "Enter queue elements");
for(int i=1; i<=q_size; i++)
{
scanf("%d",&queue[i]);
}
printf("%s\n","Enter initial head position");
scanf("%d", &head);
queue[0]=head;
for(int j=0; j<=q_size-1; j++)
{
diff = abs(queue[j]-queue[j+1]);
seek += diff;
printf("Move from %d to %d with Seek %d\n",queue[j],queue[j+1],diff);
}
printf("\nTotal seek time is %d\t",seek);
avg = seek/(float)q_size;
printf("\nAverage seek time is %f\t", avg);
return 0;
}
|
Java | UTF-8 | 341 | 1.867188 | 2 | [] | no_license | package in.uskcorp.tool.dmt.dao;
import java.util.List;
import in.uskcorp.tool.dmt.domain.Trainee;
import in.uskcorp.tool.dmt.domain.TrainingSummary;
public abstract class TraineeDAO extends APIDAO<Trainee> {
public abstract List<TrainingSummary> getSummary();
public abstract List<Trainee> readByValues(int batchId);
}
|
Java | UTF-8 | 616 | 3.09375 | 3 | [] | no_license |
public final class Employee {
private final String firstName;
private final String lastName;
private final Address address;
Employee(String firstName, String lastName, Address address)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = new Address(address.getCity(),address.getState());
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public Address getAddress()
{
return new Address(address.getCity(),address.getState());
}
}
|
Python | UTF-8 | 1,811 | 2.625 | 3 | [] | no_license | from flask import Blueprint, render_template, session, request
from AccessManagement import login_required
from Database import database
from Utilities import get_text_input, logger
create = Blueprint('create', __name__, template_folder='templates')
# Checks if the april tag id is valid.
# Returns the id as an int if so.
def get_april_id(form):
rtn = get_text_input(form['april_id'])
if not rtn.isdigit():
raise RuntimeError('April Tag ID must be in integer')
rtn = int(rtn)
return rtn
@create.route('/create', methods=['GET', 'POST'])
@login_required
def create_route():
options = {}
username = session['username']
try:
form = request.form
# Deal with POST requests.
if request.method == 'POST':
# If the request does not contain an "op" field.
if not 'op' in request.form:
raise RuntimeError('Did you click the button?')
# Add a ingredient.
elif form['op'] == 'add_ingred':
ingred_name = get_text_input(form['ingred_name'])
april_id = get_april_id(form)
database.check_ingred_april_id(username, ingred_name, april_id)
logger.debug('New ingredient: %s at April Tag %s' % \
(ingred_name, april_id))
# Add the ingredient into the database.
database.add_ingredient(username, ingred_name, april_id)
# Delete an ingredient.
elif form['op'] == 'delete_ingred':
# Delete the ingredient from the database.
database.delete_ingredient(username, form['ingred_name'])
else:
raise RuntimeError('Did you click the button?')
except Exception as e:
logger.exception(e)
options['error'] = e
# Retrieve ingredients even if POST request fails.
try:
options['ingredients'] = database.get_ingredients(username)
except Exception as e:
logger.exception(e)
options['error'] = e
return render_template('create.html', **options)
|
Java | UTF-8 | 714 | 3.078125 | 3 | [] | 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 graphic;
import javafx.scene.paint.Color;
/**
* Enum to manage the color of the Pawn
* @author p1509283
*/
public enum Colors {
WHITE(1,Color.WHITE),BLACK(2,Color.BLACK);
private final Color graphicColor;
private final int number;
Colors(int i,Color c){
this.number = i;
this.graphicColor = c;
}
public Color getGraphicColor() {
return graphicColor;
}
public int getNumber() {
return number;
}
}
|
Java | UTF-8 | 1,432 | 1.984375 | 2 | [] | no_license | package com.rjxx.taxeasy.dao.bo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.rjxx.comm.json.JsonDatetimeFormat;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* t_wxkb 实体类
* 由GenEntityMysql类自动生成
* Tue Oct 25 17:47:44 CST 2016
* @ZhangBing
*/
@Entity
@Table(name="t_wxkb")
public class Wxkb implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
protected Integer id;
@Column(name="access_token")
protected String accessToken;
@Column(name="scsj")
@JsonSerialize(using = JsonDatetimeFormat.class)
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
protected Date scsj;
@Column(name="expires_in")
protected String expiresIn;
@Column(name="gsdm")
protected String gsdm;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getAccessToken(){
return accessToken;
}
public void setAccessToken(String accessToken){
this.accessToken=accessToken;
}
public Date getScsj(){
return scsj;
}
public void setScsj(Date scsj){
this.scsj=scsj;
}
public String getExpiresIn(){
return expiresIn;
}
public void setExpiresIn(String expiresIn){
this.expiresIn=expiresIn;
}
public String getGsdm() {
return gsdm;
}
public void setGsdm(String gsdm) {
this.gsdm = gsdm;
}
}
|
Java | UTF-8 | 3,070 | 2.03125 | 2 | [] | no_license | package tw.InHouse.order_model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonFormat;
@Entity
@Table(name = "productTest")
@Component
public class ProductTest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "product_id")
private int product_id;
@Column(name = "product_name")
private String product_name;
@Column(name = "product_type")
private String product_type;
@Column(name = "product_color")
private String product_color;
@Column(name = "product_price")
private int product_price;
@Column(name = "product_size")
private String product_size;
@Column(name = "product_quantity")
private int product_quantity;
@Column(name = "product_picture")
private String product_picture;
@Column(name = "product_descrip")
private String product_descrip;
// private String product_startTime;
@Column(name = "product_updatetime")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date product_updatetime;
// @ManyToMany(mappedBy = "orderShopCartId")
// private Set<ShopCart> shopCart = new HashSet<ShopCart>();
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_type() {
return product_type;
}
public void setProduct_type(String product_type) {
this.product_type = product_type;
}
public String getProduct_color() {
return product_color;
}
public void setProduct_color(String product_color) {
this.product_color = product_color;
}
public int getProduct_price() {
return product_price;
}
public void setProduct_price(int product_price) {
this.product_price = product_price;
}
public String getProduct_size() {
return product_size;
}
public void setProduct_size(String product_size) {
this.product_size = product_size;
}
public int getProduct_quantity() {
return product_quantity;
}
public void setProduct_quantity(int product_quantity) {
this.product_quantity = product_quantity;
}
public String getProduct_picture() {
return product_picture;
}
public void setProduct_picture(String product_picture) {
this.product_picture = product_picture;
}
public String getProduct_descrip() {
return product_descrip;
}
public void setProduct_descrip(String product_descrip) {
this.product_descrip = product_descrip;
}
public Date getProduct_updatetime() {
return product_updatetime;
}
public void setProduct_updatetime(Date product_updatetime) {
this.product_updatetime = product_updatetime;
}
}
|
Java | UTF-8 | 2,023 | 2.375 | 2 | [] | no_license | package com.linzhijia.boot.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class TradeInfo {
/**
* 交易 ID
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer tradeId;
/**
* 交易状态(0未支付(即待付款),1支付中,2支付完成)
*/
@Column
private Integer tradeState;
/**
* 交易类型(0支付,1退款)
*/
@Column
private Integer tradeType;
/**
* 交易金额
*/
@Column
private Double tradeAmount;
/**
* 交易币种(0人民币 ,1美元)
*/
@Column
private Integer tradeAmountType;
/**
* 客户信息
*/
@ManyToOne
private Customer customer;
/**
* 创建时间
*/
@Column
private Date tradeTime;
public Integer getTradeId() {
return tradeId;
}
public void setTradeId(Integer tradeId) {
this.tradeId = tradeId;
}
public Integer getTradeState() {
return tradeState;
}
public void setTradeState(Integer tradeState) {
this.tradeState = tradeState;
}
public Integer getTradeType() {
return tradeType;
}
public void setTradeType(Integer tradeType) {
this.tradeType = tradeType;
}
public Double getTradeAmount() {
return tradeAmount;
}
public void setTradeAmount(Double tradeAmount) {
this.tradeAmount = tradeAmount;
}
public Integer getTradeAmountType() {
return tradeAmountType;
}
public void setTradeAmountType(Integer tradeAmountType) {
this.tradeAmountType = tradeAmountType;
}
public Date getTradeTime() {
return tradeTime;
}
public void setTradeTime(Date tradeTime) {
this.tradeTime = tradeTime;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
|
C++ | UTF-8 | 1,086 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <functional>
#include <unistd.h>
#include "nf_event.h"
#include "nf_event_iotask.h"
using namespace std::placeholders;
void cbfunc(EventLoop *loop, task_data_t data, int mask) {
IOTask &task = *((IOTask *)data.data.ptr);
std::cout << task.GetFd() << std::endl;
std::cout << mask << std::endl;
task.Stop();
}
class Cb {
public:
void CbFunc(EventLoop *loop, task_data_t data, int mask) {
IOTask &task = *((IOTask *)data.data.ptr);
std::cout << task.GetFd() << std::endl;
std::cout << mask << std::endl;
std::cout << "i=" << i << std::endl;
task.Stop();
}
int i;
};
int main() {
EventLoop loop;
IOTask task(loop, STDIN_FILENO, EV_POLLIN);
task_data_t data;
data.data.ptr = &task;
task.SetPrivateData(data);
task.Bind(cbfunc);
task.Start();
Cb cb;
cb.i = 33;
IOTask taskout(loop, STDOUT_FILENO, EV_POLLOUT);
data.data.ptr = &taskout;
taskout.SetPrivateData(data);
taskout.Bind(std::bind(&Cb::CbFunc, cb, _1, _2, _3));
taskout.Start();
loop.Run();
return 0;
}
|
JavaScript | UTF-8 | 3,297 | 3.015625 | 3 | [] | no_license | // ** Notes ** //
// all actions associated with the dashboard components
// Importing the request functionality from the api.js that enables us to check auth with all our requests
import request from '../utils/api'
// Dispatched when getting all shopping list data - see dispatch in getShoppingLists() - and used to update dashboardShoppingList.js state
export function receiveShoppingLists(shoppinglists){
return {
type: 'RECIEVE_SHOPPINGLISTS',
shoppinglists
}
}
// Get all the shopping lists for the currently logged in user
// ** MUST use componentDidMount() in the component (Dashboard.jsx)
export function getShoppingLists() {
return (dispatch) => {
return request( 'get', 'v1/shoppinglists' )
.then (res => {
dispatch(receiveShoppingLists(res.body))
})
.catch(err => {
dispatch(showError(err.message))
})
}
}
// Dispatched when getting data for a specific shopping list (search by Id) - see dispatch in getShoppingListById() - and used to update dashboardShoppingListById.js state.
export function receiveShoppingListById(shoppinglist){
return {
type: 'RECIEVE_SHOPPINGLIST_BY_ID',
shoppinglist
}
}
// Use this function to get shopping list data by shopping id for the user currently signed in
export function getShoppingListById(id) {
return (dispatch) => {
return request( 'get', `v1/shoppinglists/${id}` )
.then (res => {
console.log('ACTION',res.body)
dispatch(receiveShoppingListById(res.body))
})
.catch(err => {
dispatch(showError(err.message))
})
}
}
// Dispatched in the deleteShoppingListById() below and deletes the specific shopping list in store for the user currently signed in
export function deleteShoppingListByIdInStore (id) {
return {
type: 'DELETE_SHOPPINGLIST_BY_ID',
id
}
}
// Dispatched in the deleteItem() function in the SavingsProgressBar.jsx and deletes the shopping list from both store and database
// Also dispatches getShoppingListTotals() once shopping list deleted, so that total savings is updated.
export function deleteShoppingListById (id) {
return (dispatch) => {
return request('delete', `v1/shoppinglists/${id}`)
.then (res => {
dispatch(deleteShoppingListByIdInStore(id))
dispatch(getShoppingListTotals())
})
.catch(err => {
dispatch(showError(err.message))
})
}
}
// Dispatched when getting the the totalsavings for all shopping events for a particular user - see dispatch in getShoppingListTotals() in Dashboard.jsx sitting in componentDidMount - used to update state in dashboardShoppingListTotals reducer
export function receiveShoppingListTotals(shoppinglistTotals){
return {
type: 'RECIEVE_SHOPPINGLIST_TOTALS_BY_ID',
shoppinglistTotals
}
}
//Use this function to get a shopping list by shopping list id
//You must use component did mount
export function getShoppingListTotals() {
console.log('action totals')
return (dispatch) => {
return request( 'get', 'v1/shoppingliststotals' )
.then (res => {
dispatch(receiveShoppingListTotals(res.body))
})
.catch(err => {
dispatch(showError(err.message))
})
}
}
|
Java | UTF-8 | 2,462 | 2.59375 | 3 | [] | no_license | package com.modelmetrics.cloudconverter;
import com.modelmetrics.common.sforce.SalesforceSession;
import com.modelmetrics.common.sforce.SalesforceSessionFactory;
import com.modelmetrics.common.util.TestCaseWithDevOrg;
import com.sforce.soap.partner.DescribeSObjectResult;
import com.sforce.soap.partner.Field;
/**
* Test exercises default cloud converter script against a sample database -- there are a few
* items that are hard coded and will need to be changed when the source data changes.
*
* @author reidcarlberg
*
*/
//SuperClass has SFDC creds. Optional.
public class CloudConverterScript_SampleTest extends TestCaseWithDevOrg {
private String sampleObject = "mytable__c";
@Override
protected void setUp() throws Exception {
log.debug("starting setup");
super.setUp();
this.handleCustomObjectKill(this.sampleObject);
log.debug("setup complete");
}
@Override
protected void tearDown() throws Exception {
// TODO Auto-generated method stub
super.tearDown();
log.debug("starting clean up");
this.handleCustomObjectKill(this.sampleObject);
log.debug("clean up complete");
}
public void testCreatesObject() throws Exception {
CloudConverterScript_Sample script = new CloudConverterScript_Sample();
SalesforceSession salesforceSession = SalesforceSessionFactory.factory
.build(salesforceCredentials);
script.execute(salesforceCredentials.getUsername(),
salesforceCredentials.getPassword());
// bouncing the session
salesforceSession = SalesforceSessionFactory.factory
.build(salesforceCredentials);
assertTrue(this
.containsTestObject(salesforceSession, this.sampleObject));
DescribeSObjectResult describeSObjectResult = salesforceSession
.getSalesforceService().describeSObject(this.sampleObject);
log.info("Field size returned: "
+ describeSObjectResult.getFields().length);
// verify that they're the ones I expect based on the sample database
assertTrue(describeSObjectResult.getFields().length == 18);
for (int i = 0; i < describeSObjectResult.getFields().length; i++) {
Field field = describeSObjectResult.getFields(i);
log.debug("field " + field.getName());
if (field.getName().equalsIgnoreCase("mypicklist__c")) {
assertTrue(field.getPicklistValues().length == 5);
} else if (field.getName().equalsIgnoreCase("myid__c")) {
assertTrue(field.getExternalId().booleanValue());
}
}
// good enough time to clean up
}
}
|
C++ | UHC | 655 | 3.03125 | 3 | [] | no_license | #include <iostream>
// https://www.acmicpc.net/problem/15552
//C++ ϰ ְ cin/cout ϰ Ѵٸ, cin.tie(NULL) sync_with_stdio(false) ְ, endl (\n) . , ̷ ϸ ̻ scanf/printf/puts/getchar/putchar C ϸ ȴ.
//cin.tie(NULL) sync_with_stdio(false) ӵ ش.
using namespace std;
int sum()
{
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int num, a, b;
cin >> num;
for (int i = 0; i < num; i++) {
cin >> a >> b;
cout << a + b << '\n';
}
return 0;
}
|
Markdown | UTF-8 | 1,748 | 2.859375 | 3 | [] | no_license | # Cadastro de carro
**RF**
Deve ser possivel cadastrar um carro
**RN**
Não deve ser possivel cadastrar um carro com uma placa ja existente.
Não deve ser possivel alterar a placa de um carro para uma placa ja existente.
O carro deve ser cadastrado por padrao com disponibilidade.
Não deve ser possivel cadastrar um carro sem credencial de administrador.
# Listagem de carros
**RF**
Deve ser possivel listar todos os carros disponiveis
Deve ser possivel listar todos os carros disponiveis pelo nome da categoria
Deve ser possivel listar todos os carros disponiveis pelo nome da marca
Deve ser possivel listar todos os carros disponiveis pelo nome do carro
**RN**
Usuario não precisa estar logado no sistema
# Cadastro de especificação no carro
**RF**
Deve ser possivel cadastrar uma especificação num carro.
Deve ser possivel listar todas as especificações
**RN**
Não deve ser possivel cadastrar uma especificação num carro não cadastrado.
Não deve ser possivel cadastrar uma especificação ja existente num mesmo carro.
Não deve ser possivel cadastrar uma especificação sem credencial de administrador.
# Cadastrar imagem do carro
**RF**
Deve ser possivel cadastrar a imagem do carro
Deve ser possivel listar todos os carros
**RNF**
Deve ser utilizado o multer para realizar o upload
**RN**
Usuario deve poder cadastrar mais de uma imagem por carro
O usuario responsavel pelo cadastro deve ser administrador
# Aluguel de carro
**RF**
Deve ser possivel cadastrar um aluguel
**RN**
O aluguel deve ter duração minima de 24 horas
Não deve ser possivel cadastrar um novo aluguel caso ja exista um aberto para o mesmo carro
Não deve ser possivel cadastrar um novo aluguel caso ja exista um aberto para o mesmo usuario |
Python | UTF-8 | 4,836 | 2.84375 | 3 | [] | no_license | import random
from cs231n.data_utils import load_CIFAR10
import numpy as np
import matplotlib
matplotlib.use('Agg')
import pylab
import matplotlib.pyplot as plt
from cs231n.classifiers import KNearestNeighbor
def time_function(f, *args):
import time
tic = time.time()
f(*args)
toc = time.time()
return toc - tic
def matrix_compare(a,b):
difference = np.linalg.norm(a-b,ord='fro')
print "Difference was: %f" %(difference,)
if difference < 0.001:
print "Good! The distance matrices are the same"
else:
print "Uh-ohh! they are difference"
def cross_validate(X_train, y_train):
num_folds = 5
k_choices = [1,3,5,8,10,12,15,20,50,100]
X_train_folds = []
y_train_folds = []
N = len(X_train)
train_folds = np.array_split(range(N),num_folds,axis=0)
k_to_accuracies = {}
for k1 in k_choices:
fold_eval = []
for i in range(num_folds):
mask = np.ones(N,dtype=bool)
mask[train_folds[i]] = False
X_train_cur = X_train[mask]
y_train_cur = y_train[mask]
classifier = KNearestNeighbor()
classifier.train(X_train_cur, y_train_cur)
X_test_cur = X_train[train_folds[i]]
y_test_cur = y_train[train_folds[i]]
dists = classifier.compute_distances_no_loops(X_test_cur)
y_test_pred = classifier.predict_labels(dists,k=k1)
num_correct = np.sum(y_test_pred == y_test_cur)
accuracy = float(num_correct)/len(y_test_cur)
fold_eval.append(accuracy)
#pass
k_to_accuracies[k1] = fold_eval[:]
#k_to_accuracies[k1] = [1,2,3,4,5]
for k in sorted(k_to_accuracies):
for accuracy in k_to_accuracies[k]:
print 'k = %d, accuracy = %f' % (k, accuracy)
for k in k_choices:
accuracies = k_to_accuracies[k]
plt.scatter([k]*len(accuracies), accuracies)
accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])
accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])
plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)
plt.title('Cross-validation on k')
plt.xlabel('k')
plt.ylabel('Cross-validation accuracy')
plt.savefig('./figures/validation_k')
def test1():
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
print 'Training data shape:', X_train.shape
print 'Training label shape:', y_train.shape
print 'Test data shape:', X_test.shape
print 'Test label shape:', y_test.shape
# classes = ['plane','car','bird','cat','deer','dog','frog','horse','ship','truck']
# num_classes = len(classes)
# sample_per_class = 7
# for y,cls in enumerate(classes):
# idxs = np.flatnonzero(y_train == y)
# idxs = np.random.choice(idxs, sample_per_class, replace=False)
# for i, idx in enumerate(idxs):
# plt_idx = i*num_classes + y + 1
# plt.subplot(sample_per_class, num_classes, plt_idx)
# plt.imshow(X_train[idx].astype('uint8'))
# plt.axis('off')
# if i == 0:
# plt.title(cls)
# plt.savefig("./figures/cifar_sample.png")
# plt.show()
# plt.close()
num_training = 5000
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
num_test = 500
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
X_train = np.reshape(X_train, (X_train.shape[0],-1))
X_test = np.reshape(X_test,(X_test.shape[0],-1))
print X_train.shape, X_test.shape
from cs231n.classifiers import KNearestNeighbor
classifier = KNearestNeighbor()
classifier.train(X_train, y_train)
# two_loop_time = time_function(classifier.compute_distances_two_loops,X_test)
# print "two loop time %f" % two_loop_time
# one_loop_time = time_function(classifier.compute_distances_one_loop,X_test)
# print "one loop time %f " %one_loop_time
# no_loop_time = time_function(classifier.compute_distances_no_loops,X_test)
# print "no loop time %f "% no_loop_time
dists = classifier.compute_distances_no_loops(X_test)
# dist_one_loop = classifier.compute_distances_one_loop(X_test)
# dist_two_loops = classifier.compute_distances_two_loops(X_test)
#matrix_compare(dists,dist_one_loop)
#matrix_compare(dists,dist_two_loops)
y_test_pred = classifier.predict_labels(dists,k=5)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct)/num_test
print "God %d/%d correct => accuracy: %f" %(num_correct, num_test, accuracy)
cross_validate(X_train,y_train)
test1()
|
C# | UTF-8 | 3,739 | 2.53125 | 3 | [
"BSD-2-Clause",
"ISC"
] | permissive | using System;
using FluentAssertions;
using NextLevelSeven.Core;
using NextLevelSeven.Core.Encoding;
using NextLevelSeven.Test.Testing;
using NUnit.Framework;
namespace NextLevelSeven.Test.Core
{
[TestFixture]
public class EscapeFunctionalTestFixture : CoreBaseTestFixture
{
private static void Test_Escape(string expected, string test)
{
var messageParser = Message.Parse();
var messageBuilder = Message.Build();
messageParser.Encoding.Escape(test).Should().Be(expected);
messageBuilder.Encoding.Escape(test).Should().Be(expected);
}
private static void Test_SingleDelimiterEscape(string delimiter, string escapeCode)
{
var leftString = Any.String();
var middleString = Any.String();
var rightString = Any.String();
var test = String.Format("{0}{3}{1}{3}{2}", leftString, middleString, rightString, delimiter);
var expected = string.Format("{0}{3}{1}{3}{2}", leftString, middleString, rightString, escapeCode);
Test_Escape(expected, test);
}
[Test]
public void Escape_Converts_Null()
{
Test_Escape(null, null);
}
[Test]
public void Escape_Converts_ComponentCharacters()
{
Test_SingleDelimiterEscape("^", "\\S\\");
}
[Test]
public void Escape_Converts_EscapeCharacters()
{
Test_SingleDelimiterEscape("\\", "\\E\\");
}
[Test]
public void Escape_Converts_FieldCharacters()
{
Test_SingleDelimiterEscape("|", "\\F\\");
}
[Test]
public void Escape_Converts_PartialEscapeSequences()
{
// this contains what looks like the start of a variable length
// locally defined sequence but is only partially existing.
Test_Escape("\\E\\Zork", "\\Zork");
}
[Test]
public void Escape_Converts_RepetitionCharacters()
{
Test_SingleDelimiterEscape("~", "\\R\\");
}
[Test]
public void Escape_Converts_SubcomponentCharacters()
{
Test_SingleDelimiterEscape("&", "\\T\\");
}
[Test]
public void Escape_DoesNotConvert_HighlightTextMarker()
{
var message = String.Format("{0}\\H\\{1}", Any.String(), Any.String());
Test_Escape(message, message);
}
[Test]
public void Escape_DoesNotConvert_NormalTextMarker()
{
var message = String.Format("{0}\\N\\{1}", Any.String(), Any.String());
Test_Escape(message, message);
}
[Test]
public void Escape_DoesNotConvert_MultiByteCharacterSetLongEscapeSequence()
{
var message = String.Format("{0}\\MABCDEF\\{1}", Any.String(), Any.String());
Test_Escape(message, message);
}
[Test]
public void Escape_DoesNotConvert_MultiByteCharacterSetShortEscapeSequence()
{
var message = String.Format("{0}\\MABCD\\{1}", Any.String(), Any.String());
Test_Escape(message, message);
}
[Test]
public void Escape_DoesNotConvert_LocallyDefinedEscapeSequence()
{
var message = String.Format("{0}\\Z{2}\\{1}", Any.String(), Any.String(), Any.String());
Test_Escape(message, message);
}
[Test]
public void Escape_DoesNotConvert_SingleByteCharacterSetEscapeSequence()
{
var message = String.Format("{0}\\CABCD\\{1}", Any.String(), Any.String());
Test_Escape(message, message);
}
}
} |
Python | UTF-8 | 112 | 2.875 | 3 | [] | no_license | import math
import sys
a, b, v = map(int, sys.stdin.readline().split())
print(math.ceil((v - a) / (a - b)) + 1) |
Go | UTF-8 | 217 | 2.625 | 3 | [] | no_license | package solution
import "sort"
// Runtime 76 ms
// Memory 6.7 MB
func arrayPairSum(nums []int) int {
sort.Sort(sort.IntSlice(nums))
sum := 0
for i := 0; i < len(nums); i += 2 {
sum += nums[i]
}
return sum
}
|
Markdown | UTF-8 | 578 | 2.8125 | 3 | [
"MIT"
] | permissive |
# Individual reflection Dino Paslic – Week 4
## what do I want to learn or understand better?
Making good website design
## how can I help someone else, or the entire team, to learn something new?
Continue learning about the backend so that I can help the rest of the team
## what is my contribution towards the team’s use of Scrum?
Helping with discussions and trying to keep us in line of using scrum. Also as a PO, keeping up with my responsiblities
## what is my contribution towards the team’s deliveries?
Continued work on the code and helping with team reflection
|
C++ | UTF-8 | 2,588 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | /*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
#include "MicroTasks.h"
#include "MicroTasksTask.h"
#include "MicroTasksInterrupt.h"
#include "MicroTasksEventListener.h"
using namespace MicroTasks;
class Blink : public Task
{
private:
int state;
int pin;
int delay;
public:
Blink(int pin, int delay = 1000);
void setup();
unsigned long loop(WakeReason reason);
};
Blink::Blink(int pin, int delay) :
Task(), state(LOW), pin(pin), delay(delay)
{
}
void Blink::setup()
{
// initialize the digital pin as an output.
pinMode(pin, OUTPUT);
}
unsigned long Blink::loop(WakeReason reason)
{
// Update the LED
digitalWrite(pin, state);
// Update the state
state = LOW == state ? HIGH : LOW;
// return when we next want to be called
return delay;
}
Blink blink1 = Blink(10, 125);
Blink blink2 = Blink(11, 250);
Blink blink3 = Blink(12, 500);
Interrupt buttonEvent(2, FALLING);
class BlinkOnButton : public Task
{
private:
int state;
int pin;
EventListener buttonEventListener;
public:
BlinkOnButton(int pin);
void setup();
unsigned long loop(WakeReason reason);
};
BlinkOnButton::BlinkOnButton(int pin) :
Task(), state(LOW), pin(pin), buttonEventListener(this)
{
}
void BlinkOnButton::setup()
{
// initialize the digital pin as an output.
pinMode(pin, OUTPUT);
buttonEvent.Register(&buttonEventListener);
}
unsigned long BlinkOnButton::loop(WakeReason reason)
{
if (WakeReason_Event == reason && buttonEvent.IsTriggered())
{
// Update the LED
digitalWrite(pin, state);
// Update the state
state = LOW == state ? HIGH : LOW;
}
// return when we next want to be called
return MicroTask.Infinate | MicroTask.WaitForEvent;
}
BlinkOnButton blinkOnButton1 = BlinkOnButton(13);
BlinkOnButton blinkOnButton2 = BlinkOnButton(9);
// the setup function runs once when you press reset or power the board
void setup() {
MicroTask.startTask(blink1);
MicroTask.startTask(blink2);
MicroTask.startTask(blink3);
MicroTask.startTask(blinkOnButton1);
MicroTask.startTask(blinkOnButton2);
buttonEvent.Attach();
}
// the loop function runs over and over again forever
void loop() {
MicroTask.update();
}
|
JavaScript | UTF-8 | 94 | 2.75 | 3 | [] | no_license | function solution(numbers) {
return numbers.reduce((acc,e)=>acc+e, 0) / numbers.length;
}
|
C# | UTF-8 | 2,034 | 2.75 | 3 | [
"MIT"
] | permissive | using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Jurassic;
using SquishIt.Framework;
namespace SquishIt.CoffeeScript.Coffee
{
public class NativeCoffeeScriptCompiler
{
public string Compile(string file)
{
StringBuilder outputBuilder = new StringBuilder();
StringBuilder errorBuilder = new StringBuilder();
ProcessStartInfo coffee = new ProcessStartInfo();
coffee.CreateNoWindow = true;
coffee.RedirectStandardOutput = true;
coffee.RedirectStandardInput = true;
coffee.RedirectStandardError = true;
coffee.UseShellExecute = false;
if(!FileSystem.Unix)
{
coffee.Arguments = string.Format("/c coffee -cp {0} ", file);
coffee.FileName = "cmd";
}
else
{
coffee.Arguments = string.Format("-cp {0}", file);
coffee.FileName = "coffee";
}
Process process = new Process();
process.StartInfo = coffee;
// enable raising events because Process does not raise events by default
process.EnableRaisingEvents = true;
// attach the event handler for OutputDataReceived before starting the process
process.OutputDataReceived += (sender, e) => outputBuilder.Append(e.Data);
process.ErrorDataReceived += (sender, e) => errorBuilder.AppendLine(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
if(errorBuilder.ToString().Trim().Length > 0)
throw new ArgumentException(errorBuilder.ToString());
// use the output
string output = outputBuilder.ToString().Trim();
return output;
}
}
}
|
C# | UTF-8 | 1,177 | 2.828125 | 3 | [] | no_license | using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper.Configuration;
namespace SmokeEnGrill.API.Data
{
public class RetrofitRepository : IRetrofitRepository
{
private readonly DataContext _context;
private readonly IConfiguration _config;
public RetrofitRepository(DataContext context, IConfiguration config)
{
_context = context;
_config = config;
}
public void Add<T>(T entity) where T : class
{
_context.Add(entity);
}
public async void AddAsync<T>(T entity) where T : class
{
await _context.AddAsync(entity);
}
public void Update<T>(T entity) where T : class
{
_context.Update(entity);
}
public void Delete<T>(T entity) where T : class
{
_context.Remove(entity);
}
public void DeleteAll<T>(List<T> entities) where T : class
{
_context.RemoveRange(entities);
}
public async Task<bool> SaveAll()
{
return await _context.SaveChangesAsync() > 0;
}
}
} |
Java | UTF-8 | 770 | 2.765625 | 3 | [] | no_license | package Eventials.mailbox;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
public class MailboxUtils{
static String readBinaryFileAsString(File file){
try{
String data = Base64.getEncoder().encodeToString(Files.readAllBytes(file.toPath()));
return data.replace("|", " --pipesep-- ").replace("\n", " --linebreak-- ");
}
catch(IOException e){return null;}
}
static boolean saveBinaryStringToFile(File file, String data){
data = data.replace(" --pipesep-- ", "|").replace(" --linebreak-- ", "\n");
try(FileOutputStream fos = new FileOutputStream(file)){
fos.write(Base64.getDecoder().decode(data));
return true;
}
catch(IOException e){return false;}
}
}
|
Python | UTF-8 | 3,966 | 2.8125 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.preprocessing import LabelBinarizer
from keras import datasets, layers, models, callbacks
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
#load data
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
#show a few sample images with corresponding labels
fig, ax = plt.subplots(2, 3)
k=0
for i in range(2):
for j in range (3):
ax[i,j].imshow(train_images[k].reshape(28, 28), cmap='gray')
ax[i, j].title.set_text(train_labels[k])
k+=1
plt.tight_layout()
plt.show()
#normalize pixel values
train_images, test_images = train_images/255, test_images/255
########################
# Input Data Reshaping #
########################
print('Before Reshaping:')
print('Train: X=%s, y=%s' %(train_images.shape, train_labels.shape))
print('Test: X=%s, y=%s' %(test_images.shape, test_labels.shape))
print()
train_images = train_images.reshape(-1, 28, 28, 1)
test_images = test_images.reshape(-1, 28, 28, 1)
lab_bin = LabelBinarizer()
train_labels = lab_bin.fit_transform(train_labels)
test_labels = lab_bin.fit_transform(test_labels)
print('After Reshaping:')
print('Train: X=%s, y=%s' %(train_images.shape, train_labels.shape))
print('Test: X=%s, y=%s' %(test_images.shape, test_labels.shape))
print()
#split test data and labels into train and test groups
X_trn, X_tst, y_trn, y_tst = train_test_split(train_images, train_labels, test_size=0.2, random_state=0)
#'''
######################
# Creating the Model #
######################
model = models.Sequential(
[
layers.Conv2D(filters=75, kernel_size=(3, 3), strides=1, padding='valid', activation='relu', input_shape=(28, 28, 1)),
layers.MaxPool2D(pool_size=(2,2), strides=1, padding='valid'),
layers.Conv2D(filters=50, kernel_size= (3, 3), strides=1, padding='valid', activation='relu'),
layers.MaxPool2D(pool_size=(2,2), strides=1, padding='valid'),
layers.Conv2D(filters=25, kernel_size= (3, 3), strides=1, padding='valid', activation='relu'),
layers.MaxPool2D(pool_size=(2,2), strides=1, padding='valid'),
layers.Flatten(),
layers.Dense(units=64, activation='relu'),
layers.Dense(units=10, activation='softmax')
]
)
# declaring utility functions to prevent overtraining
early_stopping = callbacks.EarlyStopping(monitor='val_loss', min_delta=0.001, patience=3, verbose=1)
red_lr = callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=1, min_lr=0.00001, verbose=1)
#compile model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
#fit model
history = model.fit(X_trn, y_trn, batch_size=256, epochs=15, validation_data=(X_tst, y_tst), callbacks=[early_stopping, red_lr])
#print results: first accuracy then loss
plt.plot(history.history['accuracy'], label='Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training Accuracy and Validation')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()
plt.plot(history.history['loss'], label='Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training Loss and Validation')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(loc='upper right')
plt.show()
# print accuracy and loss of TEST
test_loss, test_accuracy = model.evaluate(test_images, test_labels, verbose=1)
print('Accuracy: %s, Loss: %s' %(test_accuracy, test_loss))
# have model make predictions based on Test images
predictions = model.predict_classes(test_images)
# get rid of one-hot encoding to use in confusion matrix
test_labels = np.argmax(test_labels, axis=1)
cm = confusion_matrix(test_labels, predictions)
fig, ax = plt.subplots(figsize=(12,12))
sns.heatmap(cm, cmap='Reds', linewidth=0.5, linecolor='Black', annot=True, fmt="d")
#''' |
SQL | UTF-8 | 14,955 | 3.078125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 06, 2017 at 01:04 PM
-- Server version: 10.1.13-MariaDB
-- PHP Version: 5.6.23
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `hospitalmanagementsystem`
--
-- --------------------------------------------------------
--
-- Table structure for table `discounts`
--
CREATE TABLE `discounts` (
`discount_id` int(11) NOT NULL PRIMARY KEY,
`name` varchar(225) NOT NULL,
`discount` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `discounts`
--
INSERT INTO `discounts` (`discount_id`, `name`, `discount`, `status`) VALUES
(1, '', '', '0'),
(2, 'Phil healths', '5', '1'),
(3, 'SSS', '10', '1');
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`orders_id` int(11) NOT NULL PRIMARY KEY,
`transaction_id` varchar(225) NOT NULL,
`services_id` varchar(225) NOT NULL,
`qty` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`orders_id`, `transaction_id`, `services_id`, `qty`) VALUES
(5, '88', '1', '1'),
(6, '8', '1', '1'),
(7, '8', '11', '1'),
(8, '8', '3', '1'),
(9, '9', '1', '1'),
(10, '10', '1', '1'),
(11, '11', '4', '1'),
(12, '12', '1', '1'),
(13, '15', '3', '1'),
(14, '15', '1', '1'),
(15, '15', '5', '1');
-- --------------------------------------------------------
--
-- Table structure for table `orders_discount`
--
CREATE TABLE `orders_discount` (
`orders_discount_id` int(11) NOT NULL,
`transaction_id` varchar(225) NOT NULL,
`discount_id` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `orders_discount`
--
INSERT INTO `orders_discount` (`orders_discount_id`, `transaction_id`, `discount_id`) VALUES
(2, '8', '3'),
(3, '9', '3'),
(4, '10', '3'),
(5, '11', '3'),
(6, '12', '3'),
(7, '15', '2');
-- --------------------------------------------------------
--
-- Table structure for table `orders_rooms`
--
CREATE TABLE `orders_rooms` (
`orders_rooms_id` int(11) NOT NULL,
`transaction_id` varchar(225) NOT NULL,
`room_id` varchar(225) NOT NULL,
`qty` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `orders_rooms`
--
INSERT INTO `orders_rooms` (`orders_rooms_id`, `transaction_id`, `room_id`, `qty`) VALUES
(7, '8', '2', '2'),
(8, '9', '1', '1'),
(9, '10', '1', '1'),
(10, '11', '1', '1'),
(11, '12', '1', '1'),
(12, '15', '1', '1');
-- --------------------------------------------------------
--
-- Table structure for table `patients`
--
CREATE TABLE `patients` (
`patient_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(225) NOT NULL,
`birthday` varchar(225) NOT NULL,
`gender` varchar(225) NOT NULL,
`address` varchar(225) NOT NULL,
`phone` varchar(225) NOT NULL,
`img` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`confine` varchar(225) NOT NULL,
`room` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `patients`
--
INSERT INTO `patients` (`patient_id`, `name`, `birthday`, `gender`, `address`, `phone`, `img`, `email`, `confine`, `room`, `status`) VALUES
(1, 'Anne Curtis', '1997-08-06', 'Male', '061 dao st. marikina heights\r\n061 dao st. marikina heights', '09993628811', 'c.jpg', 'asd@gmail.com', 'In', '', '1'),
(2, 'Angel Locsin', '2016-11-30', 'Male', '061 dao st. marikina heights\r\n061 dao st. marikina heights', '639489101882', '535111_1040587059334734_5366597921990537295_n.jpg', '', 'out', '', '0'),
(3, 'Genalyn Mercado', '2015-11-30', 'Female', 'asd', '21312', 'b.jpg', '', 'out', '', '1'),
(4, 'a b. v', '2016-09-07', 'Male', 'asd', 'alakneth@gmail.com', 'asd.png', '', 'In', 'none', '0'),
(5, 'test tester. testibngf', '2003-06-19', 'Female', 'tester adderss', '12354678', '1468758339_5cf9674b6980f5c30ec7151f6dd2fca1.jpeg', '123sd@gmail.com', 'In', 'none', '1'),
(6, 'test testerasd. ASD', '1987-09-23', 'Male', 'test', '12312512', '1468758339_5cf9674b6980f5c30ec7151f6dd2fca1.jpeg', 'sd123123a@gmail.com', 'In', 'none', '1'),
(7, 'man kid. papa', '1526-10-20', 'Female', '061 dao st. marikina heights\r\n061 dao st. marikina heights', '639489101882', '1468758339_5cf9674b6980f5c30ec7151f6dd2fca1.jpeg', '2134@gmail.com', 'out', 'none', '1'),
(8, 'men barcode. mendoza', '1997-08-06', 'Male', '061 dao st. marikina heights\r\n061 dao st. marikina heights', '639489101882', '1468758339_5cf9674b6980f5c30ec7151f6dd2fca1.jpeg', 'alakneth@gmail.com', 'in', 'none', '1'),
(9, 'al d. buhi', '1991-11-03', 'Male', '061 dao st. marikina heights\r\n061 dao st. marikina heights', '639489101882', '1468758339_5cf9674b6980f5c30ec7151f6dd2fca1.jpeg', 'alakneth@gmail.com', 'out', 'none', '1');
-- --------------------------------------------------------
--
-- Table structure for table `physician`
--
CREATE TABLE `physician` (
`physician_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(225) NOT NULL,
`phone` varchar(225) NOT NULL,
`fee` varchar(225) NOT NULL,
`img` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL,
`license` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`bday` varchar(225) NOT NULL,
`address` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `physician`
--
INSERT INTO `physician` (`physician_id`, `name`, `phone`, `fee`, `img`, `status`, `license`, `email`, `bday`, `address`) VALUES
(5, 'RITU RAUT', 'Surgeon', 'Rs. 500/-', '1468758339_5cf9674b6980f5c30ec7151f6dd2fca1.jpeg', '1', '123599946743', 'MiamiJackson@gmail.com', '1979-12-31', 'Baliuag bulacan');
-- --------------------------------------------------------
--
-- Table structure for table `rooms`
--
CREATE TABLE `rooms` (
`room_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(225) NOT NULL,
`category` varchar(225) NOT NULL,
`price` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL,
`number` varchar(225) NOT NULL,
`description` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `rooms`
--
INSERT INTO `rooms` (`room_id`, `name`, `category`, `price`, `status`, `number`, `description`) VALUES
(1, '4th floor dengue ward', 'Private', '120', '1', '34', 'asds23124352134'),
(2, '1st floor ICU', 'Private', '1233', '1', '21', 'asd'),
(3, '2nd floor', 'Private', '123', '0', '53', 'asd'),
(4, 'ground floor', 'ICU', '12', '1', '2', 'asdasd'),
(5, 'special room', 'Private', '1', '1', '1', '1');
-- --------------------------------------------------------
--
-- Table structure for table `services`
--
CREATE TABLE `services` (
`services_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(225) NOT NULL,
`category` varchar(225) NOT NULL,
`description` varchar(225) NOT NULL,
`price` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `services`
--
INSERT INTO `services` (`services_id`, `name`, `category`, `description`, `price`, `status`) VALUES
(1, 'Checkup', 'Services', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '300', '1'),
(2, 'Blood Chem', 'Laboratory', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '450', '1'),
(3, 'Ascof Lagundi', 'Pharmacy', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '80', '1'),
(4, 'Wheel Chair', 'Utilities', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '2000', '1'),
(5, 'Private Room', 'Utilities', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '2000', '1'),
(6, 'General Checkup', 'Doctors Fee', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '999', '1'),
(7, 'Parasetamol Biogesic', 'Pharmacy', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '45', '1'),
(8, 'Anti Tetano Vaccine', 'Services', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '350', '1'),
(9, 'X-ray', 'Laboratory', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '400', '1'),
(10, 'UltraSound', 'Laboratory', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit', '3000', '1'),
(11, 'asd', 'Services', 'asd', '123', '1'),
(12, 'a', 'Pharmacy', 'aasdasd', '123', '1'),
(13, 'as', 'Pharmacy', 'as', '23', '0');
-- --------------------------------------------------------
--
-- Table structure for table `transactions`
--
CREATE TABLE `transactions` (
`transaction_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`date` varchar(225) NOT NULL,
`patient_id` int(11) NOT NULL,
`physician_id` int(11) NOT NULL,
`total` varchar(225) NOT NULL,
`payment_status` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL,
FOREIGN KEY (`patient_id`) REFERENCES patients(`patient_id`) ON DELETE CASCADE,
FOREIGN KEY (`physician_id`) References physician(`physician_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `transactions`
--
INSERT INTO `transactions` (`transaction_id`, `date`, `patient_id`, `physician_id`, `total`, `payment_status`, `status`) VALUES
(8, '2016-09-26 13:36:13', '1', '5', '2672.1', 'Cash', '1'),
(9, '2016-09-26 16:12:29', '2', '5', '378', 'Cash', '1'),
(10, '2016-10-10 01:39:45', '3', '5', '390', 'Cash', '1'),
(11, '2016-10-17 12:13:26', '4', '5', '1908', 'Cash', '1'),
(12, '2017-01-04 22:51:21', '5', '5', '378', 'Cash', '1'),
(13, '2017-01-04 22:53:57', '6', '5', '0', '0', '1'),
(14, '2017-01-04 22:57:36', '5', '5', '0', '0', '1'),
(15, '2017-01-04 22:58:35', '6', '5', '2261', '', '1');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`name` varchar(225) NOT NULL,
`user` varchar(225) NOT NULL,
`pass` varchar(225) NOT NULL,
`role` varchar(225) NOT NULL,
`img` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `name`, `user`, `pass`, `role`, `img`, `status`) VALUES
(1, 'Vic Fuentes', 'admin', '1234', '1', 'cover.png', '1'),
(2, 'Ronnie Radkle', 'staff', '1234', '0', 'Untitled.png', '1'),
(3, 'Black Blue', 'staff2', '1234', '0', 'backblue.gif', '0'),
(4, 'Kellin Quin', 'cahier', '1234', '0', 'full-bg-5 - Copy.jpg', '1');
-- --------------------------------------------------------
--
-- Table structure for table `visitors`
--
CREATE TABLE `visitors` (
`visitor_id` int(11) NOT NULL,
`name` varchar(225) NOT NULL,
`pass` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`code` varchar(225) NOT NULL,
`stat` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `visitor_acc`
--
CREATE TABLE `visitor_acc` (
`va_id` int(11) NOT NULL,
`pass` varchar(225) NOT NULL,
`name` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`code` varchar(225) NOT NULL,
`status` varchar(225) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `visitor_acc`
--
INSERT INTO `visitor_acc` (`va_id`, `pass`, `name`, `email`, `code`, `status`) VALUES
(1, '1234', 'tester', '639489101882', 'v4w8diph', '1'),
(2, '1234', 'jomar', '639364470607', 'sjiozuf4', '0');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `discounts`
--
ALTER TABLE `discounts`
ADD PRIMARY KEY (`discount_id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`orders_id`);
--
-- Indexes for table `orders_discount`
--
ALTER TABLE `orders_discount`
ADD PRIMARY KEY (`orders_discount_id`);
--
-- Indexes for table `orders_rooms`
--
ALTER TABLE `orders_rooms`
ADD PRIMARY KEY (`orders_rooms_id`);
--
-- Indexes for table `patients`
--
ALTER TABLE `patients`
ADD PRIMARY KEY (`patient_id`);
--
-- Indexes for table `physician`
--
ALTER TABLE `physician`
ADD PRIMARY KEY (`physician_id`);
--
-- Indexes for table `rooms`
--
ALTER TABLE `rooms`
ADD PRIMARY KEY (`room_id`);
--
-- Indexes for table `services`
--
ALTER TABLE `services`
ADD PRIMARY KEY (`services_id`);
--
-- Indexes for table `transactions`
--
ALTER TABLE `transactions`
ADD PRIMARY KEY (`transaction_id`);
ALTER TABLE `transactions`
ADD FOREIGN KEY (`patient_id`) REFERENCES patients(`patient_id`) ON DELETE CASCADE,
ADD FOREIGN KEY (`physician_id`) References physician(`physician_id`) ON DELETE CASCADE;
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- Indexes for table `visitors`
--
ALTER TABLE `visitors`
ADD PRIMARY KEY (`visitor_id`);
--
-- Indexes for table `visitor_acc`
--
ALTER TABLE `visitor_acc`
ADD PRIMARY KEY (`va_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `discounts`
--
ALTER TABLE `discounts`
MODIFY `discount_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `orders_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
--
-- AUTO_INCREMENT for table `orders_discount`
--
ALTER TABLE `orders_discount`
MODIFY `orders_discount_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `orders_rooms`
--
ALTER TABLE `orders_rooms`
MODIFY `orders_rooms_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `patients`
--
ALTER TABLE `patients`
MODIFY `patient_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT for table `physician`
--
ALTER TABLE `physician`
MODIFY `physician_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `rooms`
--
ALTER TABLE `rooms`
MODIFY `room_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `services`
--
ALTER TABLE `services`
MODIFY `services_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `transactions`
--
ALTER TABLE `transactions`
MODIFY `transaction_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `visitors`
--
ALTER TABLE `visitors`
MODIFY `visitor_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `visitor_acc`
--
ALTER TABLE `visitor_acc`
MODIFY `va_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
PHP | UTF-8 | 76 | 2.8125 | 3 | [] | no_license | <?php
// search text within a string
echo strpos("Hello world", "world");
?> |
Java | UTF-8 | 839 | 1.90625 | 2 | [] | no_license | /**
*
*/
package com.storm.core.bolts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Tuple;
/**
* @author vinaybhore
*
*/
public class MobileRequestBolt extends BaseBasicBolt{
/**
*
*/
private static final long serialVersionUID = 1L;
public static final Logger LOG = LoggerFactory.getLogger(MobileRequestBolt.class);
/**
*
*/
public MobileRequestBolt() {
// TODO Auto-generated constructor stub
}
public void execute(Tuple input, BasicOutputCollector collector) {
LOG.info(input.toString());
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
// TODO Auto-generated method stub
}
}
|
Java | UTF-8 | 3,390 | 2.578125 | 3 | [] | no_license | package com.keepfit.stepdetection.algorithms.kornel;
import android.content.Context;
import com.keepfit.stepdetection.algorithms.AccelerationData;
import com.keepfit.stepdetection.algorithms.BaseAlgorithm;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kornelkotan on 23/02/2016.
*/
public class KornelAlgorithm extends BaseAlgorithm {
private static String NAME = "Kornel Algorithm";
private int stepsCounted;
private int overallSteps;
private long timeWindow = 5000;
List<AccelerationData> buffer = new ArrayList<>();
private AccelerationData cachedData;
public KornelAlgorithm(Context context) {
super(context, NAME);
cachedData = new AccelerationData(0, 0, 0, 0);
}
public KornelAlgorithm() {
super(NAME);
cachedData = new AccelerationData(0, 0, 0, 0);
}
@Override
public void handleSensorData(AccelerationData data) {
buffer.add(data);
if (timeWindow < (buffer.get(buffer.size() - 1).getTimeStamp() - buffer.get(0).getTimeStamp())) {
handleSensorData(buffer);
buffer.clear();
}
}
public void handleSensorData(List<AccelerationData> adList) {
double threshold;
threshold = calculateThreshold(adList);
stepsCounted = calculateStepCount(adList, threshold);
overallSteps += stepsCounted;
}
private double calculateThreshold(List<AccelerationData> adList) {
double peakMean;
int peakCount = 0;
double peakAccumulate = 0;
for (int k = 1; k < adList.size() - 1; k++) {
double forwardSlope = adList.get(k + 1).getXYZMagnitude() - adList.get(k).getXYZMagnitude();
double backwardSlope = adList.get(k).getXYZMagnitude() - adList.get(k - 1).getXYZMagnitude();
if (forwardSlope < 0 && backwardSlope > 0) {
peakCount++;
peakAccumulate = peakAccumulate + adList.get(k).getXYZMagnitude();
}
}
peakMean = peakAccumulate / peakCount;
return peakMean;
}
private int calculateStepCount(List<AccelerationData> adList, double threshold) {
int stepCount = 0;
double thresholdMultiplier = 0.85;
long minTimeBetweenSteps = 200;
// TODO set the lowfilter regarder to the values from the csv
double lowFilter = 11;
long lastStepFoundTimeStamp = 0;
for (int k = 1; k < adList.size() - 1; k++) {
double currentValue = adList.get(k).getXYZMagnitude();
double nextValue = adList.get(k + 1).getXYZMagnitude();
double previousValue = adList.get(k - 1).getXYZMagnitude();
double forwardSlope = nextValue - currentValue;
double backwardSlope = currentValue - previousValue;
if ((forwardSlope < 0 && backwardSlope > 0) && (currentValue > (thresholdMultiplier * threshold))
&& currentValue > lowFilter) {
if ((minTimeBetweenSteps < adList.get(k).getTimeStamp() - lastStepFoundTimeStamp)) {
stepCount++;
lastStepFoundTimeStamp = adList.get(k).getTimeStamp();
}
}
cachedData = adList.get(k);
}
return stepCount;
}
@Override
public int getStepCount() {
return overallSteps;
}
}
|
Go | UTF-8 | 1,209 | 2.859375 | 3 | [
"MIT"
] | permissive | package commands
import (
"github.com/urfave/cli"
"github.com/dveselov/go-libreofficekit"
"errors"
)
var (
DOC_ERR = "cannot load document to libre office"
SAVE_ERR = "cannot save as document to libre office"
)
func Convert(path string) *cli.Command{
format := ""
return &cli.Command{
Name: "convert",
Aliases: []string{"convert path/input.html path/output.html type"},
Usage: "does file conversion",
Action: func(c *cli.Context) error {
args := c.Args()
pathToInput := args.Get(0)
pathToOutput := args.Get(1)
fileType := args.Get(2)
if len(pathToInput) == 0 {
return errors.New("Invalid Args [Input missing] ")
}
if len(pathToOutput) == 0 {
return errors.New("Invalid Args [Output missing] ")
}
if len(fileType) == 0 {
return errors.New("Invalid Args [FileType missing] ")
}
office, err := libreofficekit.NewOffice(path)
document, err := office.LoadDocument(pathToInput)
if err != nil {
return errors.New(DOC_ERR + err.Error())
}
err = document.SaveAs(pathToOutput, fileType, format)
if err != nil {
return errors.New(SAVE_ERR + err.Error())
}
document.Close()
office.Close()
return err
},
}
} |
SQL | UTF-8 | 263 | 2.671875 | 3 | [] | no_license |
CREATE proc actionUpdateSpeed as begin
set noCount on
if exists(select * from actions where actionN=1 and timeOfOldestRequest is not null)
begin
update actions set timeOfOldestRequest=null where actionN=1;
exec dbo.updateSpeed
end
end
|
Markdown | UTF-8 | 787 | 3.671875 | 4 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | # Ranking
A Ranking anomaly detector is one that assigns anomaly scores to samples in a dataset. The interface provides the `rank()` method which returns a set of scores from a dataset object.
## Score a Dataset
Return the anomaly scores for each sample in a dataset:
```php
public rank(Dataset $dataset) : array
```
**Example**
```php
$scores = $estimator->rank($dataset);
var_dump($scores);
```
```sh
array(3) {
[0]=> float(0.35033859096744)
[1]=> float(0.40992076925443)
[2]=> float(1.68163357834096)
}
```
## Rank a Single Sample
Return the anomaly score of a single sample:
```php
public rankSample(array $sample) : float
```
**Example**
```php
$score = $estimator->rankSample([0.001, 6.99, 'chicago', 20000]);
var_dump($score);
```
```sh
float(0.39431742584649)
``` |
C++ | UTF-8 | 2,915 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <vector>
#include <map>
static uint64_t const N = 524288;
static uint64_t const P = 524812289;
static uint64_t const G = 194516551;
struct big_integer {
explicit big_integer(std::string const &str) {
sign = str[0] == '-';
for (size_t i = str.length(); i > 0; i--) {
if (str[i - 1] != '-') {
digits.push_back(static_cast<uint64_t>(str[i - 1] - '0'));
}
}
while (digits.size() < N) {
digits.push_back(0);
}
}
std::vector<uint64_t> digits;
bool sign;
};
std::vector<uint64_t> fft(std::vector<uint64_t> const &a, uint64_t w) {
if (a.size() == 1) {
return {a[0]};
}
std::vector<uint64_t> a0;
a0.reserve(a.size() / 2);
for (size_t i = 0; i < a.size(); i += 2) {
a0.push_back(a[i]);
}
std::vector<uint64_t> a1;
a1.reserve(a.size() / 2);
for (size_t i = 1; i < a.size(); i += 2) {
a1.push_back(a[i]);
}
auto u0 = fft(a0, w * w % P);
auto u1 = fft(a1, w * w % P);
std::vector<uint64_t> ans(a.size());
size_t M = u0.size();
uint64_t g = 1;
for (size_t i = 0; i < a.size(); i++) {
ans[i] = (u0[i % M] + g * u1[i % M]) % P;
g = g * w % P;
}
return ans;
}
uint64_t pow(uint64_t a, uint64_t b, uint64_t mod) {
if (b == 0) {
return 1;
}
uint64_t a2 = pow(a, b / 2, mod);
a2 = a2 * a2 % mod;
if (b % 2 == 1) {
a2 = a2 * a % mod;
}
return a2;
}
std::vector<uint64_t> inverse_fft(std::vector<uint64_t> const &a, uint64_t w) {
auto b = fft(a, w);
std::vector<uint64_t> ans(b.size());
auto n = pow(N, P - 2, P);
ans[0] = b[0] * n % P;
for (size_t i = 1; i < N; i++) {
ans[i] = b[static_cast<size_t>(N - i)] * n % P;
}
return ans;
}
bool is_prime(uint64_t p) {
for (uint64_t i = 2; i * i <= p; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
int main() {
std::ios_base::sync_with_stdio(false);
std::string str1, str2;
std::cin >> str1 >> str2;
big_integer a(str1), b(str2);
auto ffta = fft(a.digits, G);
auto fftb = fft(b.digits, G);
std::vector<uint64_t> c(N);
for (size_t i = 0; i < N; i++) {
c[i] = ffta[i] * fftb[i] % P;
}
auto ans = inverse_fft(c, G);
for (size_t i = 0; i < ans.size(); i++) {
if (i + 1 < ans.size()) {
ans[i + 1] = ans[i + 1] + ans[i] / 10;
}
ans[i] %= 10;
}
while (!ans.empty() && ans.back() == 0) {
ans.pop_back();
}
if (ans.empty()) {
std::cout << "0";
} else {
if (a.sign != b.sign) {
std::cout << "-";
}
for (size_t i = ans.size(); i > 0; i--) {
std::cout << ans[i - 1];
}
}
std::cout << std::endl;
return 0;
}
|
Java | UTF-8 | 653 | 1.90625 | 2 | [] | no_license | package com.nokia.application.ossuamws.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.nokia.application.ossuamws.model.Request.OperatorDetailsRequest;
import com.nokia.application.ossuamws.model.entity.Operator;
import com.nokia.application.ossuamws.model.entity.OperatorDetails;
@Repository
public interface OperatorDetailRepository extends JpaRepository<OperatorDetails, Integer>,CrudRepository<OperatorDetails, Integer>{
OperatorDetails save(OperatorDetailsRequest empReq);
}
|
C++ | UTF-8 | 658 | 3.25 | 3 | [] | no_license | #ifndef __REVERSE__
#define __REVERSE__
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
vector<string> strVec;
int start, end;
start = end = 0;
int cur = 0;
while(cur != string::npos){
start = s.find_first_not_of(' ', cur);
if(start == string::npos)
break;
end = s.find_first_of(' ', start) - 1;
cur = end + 1;
string str = s.substr(start, end - start + 1);
strVec.push_back(str);
}
if(strVec.size() == 0) return;
for(int i = strVec.size()-1; i > 0; i--){
cout<<strVec[i]<<" ";
}
cout<<strVec[0];
}
};
#endif
|
C# | UTF-8 | 3,711 | 3.5625 | 4 | [] | no_license | using System;
using System.Collections.Generic;
namespace myfirstdotnet
{
class Program
{
static void Main(string[] args)
{
// string place = "Coding Dojo";
// Console.WriteLine($"My name is {0}, I am " + 28 + " years old", "Tim");
// for (int i = 1; i < 6; i = i + 1)
// {
// Console.WriteLine(i);
// }
// int i = 1;
// while (i < 6)
// {
// Console.WriteLine(i);
// i = i + 1;
// }
// int numRings = 3;
// if (numRings >= 5)
// {
// Console.WriteLine("You are welcome to join the party");
// }
// else
// {
// Console.WriteLine("Go win some more rings");
// }
// int[] arrayOfInts = {1, 2, 3, 4, 5};
// Console.WriteLine(arrayOfInts[0]); // The first number lives at index 0.
// Console.WriteLine(arrayOfInts[1]); // The second number lives at index 1.
// Console.WriteLine(arrayOfInts[2]); // The third number lives at index 2.
// Console.WriteLine(arrayOfInts[3]); // The fourth number lives at index 3.
// Console.WriteLine(arrayOfInts[4]); // The fifth and final number lives at index 4.
// int[] arr = {1, 2, 3, 4};
// Console.WriteLine($"The first number of the arr is {arr[0]}");
// arr[0] = 8;
// Console.WriteLine($"The first number of the arr is now {arr[0]}");
// Initializing an empty list of Motorcycle Manufacturers
List<string> bikes = new List<string>();
//Use the Add function in a similar fashion to push
bikes.Add("Kawasaki");
bikes.Add("Triumph");
bikes.Add("BMW");
bikes.Add("Moto Guzzi");
bikes.Add("Harley Davidson");
bikes.Add("Suzuki");
//Accessing a generic list value is the same as you would an array
Console.WriteLine(bikes[5]); //Prints "BMW"
Console.WriteLine($"We currently know of {bikes.Count} motorcycle manufacturers.");
Console.WriteLine("The current manufacturers we have seen are:");
for (var idx = 0; idx < bikes.Count; idx++)
{
Console.WriteLine("-" + bikes[idx]);
}
// Insert a new item between a specific index
bikes.Insert(2, "Yamaha");
//Removal from Generic List
//Remove is a lot like Javascript array pop, but searches for a specified value
//In this case we are removing all manufacturers located in Japan
bikes.Remove("Suzuki");
bikes.Remove("Yamaha");
bikes.RemoveAt(0); //RemoveAt has no return value however
//The updated list can then be iterated through using a foreach loop
Console.WriteLine("List of Non-Japanese Manufacturers:");
foreach (string manu in bikes)
{
Console.WriteLine("-" + manu);
}
}
}
}
|
Java | ISO-8859-1 | 1,588 | 2.640625 | 3 | [] | no_license | /**
*
*/
package org.airhispania.xplane2rc.apt.model;
import java.util.List;
/**
* @author Jose Manuel Garca Valladolid - josemanuelgv@gmail.com
*
* AIRPORT DATA (APT.DAT) FILE SPECIFICATION VERSION 1000
*/
public class LandRunway {
public static int APT_CODE = 100;
/**
* Width of runway in metres. Two decimal places recommended. Must be >=
* 1.00
*/
private Float width;
/**
* Code defining the surface type (concrete, asphalt, etc). Integer value
* for a Surface Type Code (see below)
*/
private char surface_type;
private List<LandRunwayEnd> ends;
/**
* @return the ends
*/
public List<LandRunwayEnd> getEnds() {
return ends;
}
/**
* @param ends
* the ends to set
*/
public void setEnds(List<LandRunwayEnd> ends) {
this.ends = ends;
}
/**
* @return the width
*/
public Float getWidth() {
return width;
}
/**
* @param width
* the width to set
*/
public void setWidth(Float width) {
this.width = width;
}
/**
* @return the surface_type
*/
public char getSurface_type() {
return surface_type;
}
/**
* @param surface_type
* the surface_type to set
*/
public void setSurface_type(char surface_type) {
this.surface_type = surface_type;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String r = " RUNWAY ";
r = r + width + "m : ";
for (LandRunwayEnd e : this.getEnds()) {
r = r + e.toString() + " ";
}
return r;
}
}
|
Java | UTF-8 | 768 | 2.3125 | 2 | [
"MIT"
] | permissive | package org.fluentjava.mockodore.util.sidripper;
import java.util.Arrays;
import java.util.List;
import org.fluentjava.mockodore.model.sid.SidRegisterAddress;
public class SidWriteListenerHub implements SidWriteListener {
private final List<SidWriteListener> delegates;
private SidWriteListenerHub(List<SidWriteListener> delegates) {
this.delegates = delegates;
}
public static SidWriteListener delegatingTo(SidWriteListener... delegates) {
return new SidWriteListenerHub(Arrays.asList(delegates));
}
@Override
public void playCallStarting() {
delegates.stream().forEach(d -> d.playCallStarting());
}
@Override
public SidRegWriteListener reg(SidRegisterAddress reg) {
return (v) -> delegates.stream().forEach(d -> d.reg(reg).write(v));
}
}
|
Markdown | UTF-8 | 2,779 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | ---
layout: post
title: mysql中多版本并发控制
date: 2019-05-13
---
> 为了解决写数据时,不可以对数据进行读的问题。mysql引入的多版本并发控制(MVCC)

提innodb中对于数据表,系统会在表的上增加3列系统列,分别是:DB_ROW_ID、DB_TRX_ID、DB_ROLL_PTR。我们可以从代码中看到:
```
dict_table_add_system_columns(
/*==========================*/
dict_table_t* table, /*!< in/out: table */
mem_heap_t* heap) /*!< in: temporary heap */
{
ut_ad(table);
ut_ad(table->n_def == (table->n_cols - table->get_n_sys_cols()));
ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
ut_ad(!table->cached);
/* NOTE: the system columns MUST be added in the following order
(so that they can be indexed by the numerical value of DATA_ROW_ID,
etc.) and as the last columns of the table memory object.
The clustered index will not always physically contain all system
columns.
Intrinsic table don't need DB_ROLL_PTR as UNDO logging is turned off
for these tables. */
dict_mem_table_add_col(table, heap, "DB_ROW_ID", DATA_SYS,
DATA_ROW_ID | DATA_NOT_NULL,
DATA_ROW_ID_LEN);
#if (DATA_ITT_N_SYS_COLS != 2)
#error "DATA_ITT_N_SYS_COLS != 2"
#endif
#if DATA_ROW_ID != 0
#error "DATA_ROW_ID != 0"
#endif
dict_mem_table_add_col(table, heap, "DB_TRX_ID", DATA_SYS,
DATA_TRX_ID | DATA_NOT_NULL,
DATA_TRX_ID_LEN);
#if DATA_TRX_ID != 1
#error "DATA_TRX_ID != 1"
#endif
if (!table->is_intrinsic()) {
dict_mem_table_add_col(table, heap, "DB_ROLL_PTR", DATA_SYS,
DATA_ROLL_PTR | DATA_NOT_NULL,
DATA_ROLL_PTR_LEN);
#if DATA_ROLL_PTR != 2
#error "DATA_ROLL_PTR != 2"
#endif
/* This check reminds that if a new system column is added to
the program, it should be dealt with here */
#if DATA_N_SYS_COLS != 3
#error "DATA_N_SYS_COLS != 3"
#endif
}
}
```
# 如何实现控制的
### 情况一:
|步骤| T1 | T2|
| ---- | ------------- |:-------------:|
|1| begin| |
|2| select * from t | |
|3| | begin|
|4| | update t set age=18 where id = 1|
|5| select * from t --> return ? |
步骤1:事务T1获取一个TRX_ID 如:2
步聚2: 到表中查DB_TRX_ID大于2且DB_ROLL_PTR不为空的数据+查DB_TRX_ID小于2的数据(保留疑问)
步骤3:事务T2获取一个TRX_ID 如:3
步骤4:

copy一行数据。
把原id那一行数据的DB_ROLL_PTR 变更成3
新的一行DB_TRX_ID=3
步骤5:
age分别是12、24
### 情况二:
|步骤| T1 | T2|
| ---- | ------------- |:-------------:|
|1| | begin|
|2| | update t set age=18 where id = 1|
|3| begin| |
|4| select * from t retun ??? | |
返回:
age分别是12、24
# Undo log
|
C++ | UTF-8 | 3,002 | 3 | 3 | [
"Unlicense"
] | permissive |
// Required includes
// #include <stdint.h>
// #include <iostream>
// #include <vector>
class Histogram final
{
public:
class HistogramValue final
{
friend class Histogram;
public:
HistogramValue();
~HistogramValue();
private:
int64_t valueIteratedTo;
int64_t valueIteratedFrom;
int64_t countAtValueIteratedTo;
int64_t countAddedInThisIterationStep;
int64_t totalCountToThisValue;
int64_t totalValueToThisValue;
double percentile;
double percentileLevelIteratedTo;
};
Histogram(int64_t highestTrackableValue,
int64_t numberOfSignificantValueDigits);
~Histogram();
int64_t getHighestTrackableValue() const;
int64_t getNumberOfSignificantValueDigits() const;
int64_t getTotalCount() const;
int64_t getCountAtValue(int64_t value) const;
void forAll(std::function<void (const int64_t value, const int64_t count)> func) const;
void forPercentiles(const int32_t tickPerHalfDistance,
std::function<void (const double percentileTo,
const int64_t value,
const int64_t count)> func) const;
void outputPercentileValues(std::ostream& out, int tickPerHalfDistance, double unitScalingValue);
int64_t getMaxValue() const;
int64_t getMinValue() const;
double getMeanValue() const;
int64_t lowestEquivalentValue(int64_t value) const;
int64_t medianEquivalentValue(int64_t value) const;
int64_t highestEquivalentValue(int64_t value) const;
int64_t sizeOfEquivalentRange(int64_t value) const;
int64_t nextNonEquivalentValue(int64_t value) const;
int64_t getValueAtPercentile(double percentile) const;
double getPercentileAtOrBelowValue(int64_t value) const;
int64_t getCountBetweenValues(int64_t lo, int64_t hi) const;
void recordValue(int64_t value);
void recordValue(int64_t value, int64_t expectedInterval);
void print( std::ostream& stream ) const;
bool valuesAreEquivalent(int64_t a, int64_t b) const;
private:
int64_t identityCount;
int64_t highestTrackableValue;
int64_t numberOfSignificantValueDigits;
int32_t subBucketHalfCountMagnitude;
int32_t subBucketHalfCount;
int64_t subBucketMask;
int32_t subBucketCount;
int32_t bucketCount;
int32_t countsArrayLength;
int64_t totalCount;
std::vector< int64_t > counts;
void init();
int32_t getBucketIndex(int64_t value) const;
int32_t getSubBucketIndex(int64_t value, int32_t bucketIndex) const;
int32_t countsArrayIndex(int32_t bucketIndex, int32_t subBucketIndex) const;
int32_t countsIndexFor(int64_t value) const;
int64_t getCountAtIndex(int32_t bucketIndex, int32_t subBucketIndex) const;
void incrementCountAtIndex(int32_t countsIndex);
void incrementTotalCount();
};
std::ostream& operator<< (std::ostream& stream, const Histogram& matrix); |
Shell | UTF-8 | 4,620 | 3.5625 | 4 | [] | no_license | #!/bin/bash
set -e
if [ $# -ne 3 ];then
echo "usage: $0 TestType Platform TestCase"
exit 1
fi
#----------------------------------------------------------------------------------------
TestType="$1"
Platform="$2"
TestCase="$3"
#----------------------------------------------------------------------------------------
resultsPath=$(cat data_path.txt)
#ResultIniFile=$srcResultFile
#echo srcFile:$ResultIniFile
PointsPath='Points_Files'
curPointsIniDir='ini_Points'
#----------------------------------------------------------------------------------------
echo --------------------------------------------------------------------------------
echo "写入测试结果跑分到Excel文件..."
echo "当前路径:"
pwd
echo --------------------------------------------------------------------------------
#There are many branches for test cases in judgment.So use case mode...
case $TestCase in
"iozone")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
sh get_score_2config_iozone.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
"netperf")
cmdStr="The current test case is $TestCase."
echo $cmdStr
;;
"lmbench")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
echo --------------------------------------------------------------------------------
;;
"stream")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#stream单核测试
sh get_score_2config_stream_all.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
"UnixBench")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#UnixBench在不同机器上执行不同的线程脚本,会生成不同的测试结果文件,因此需要判断后执行
sh judge_UnixBench_IniFile.sh $TestType $Platform
#echo --------------------------------------------------------------------------------
;;
"spec2000-1core")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#spec2000单核浮点型及整型测试结果
sh get_score_2config_spec2000_1core_all.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
"spec2000-ncore")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#spec2000多核浮点型及整型测试结果
sh get_score_2config_spec2000_ncore_all.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
"spec2006-1core")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#spec2006单核浮点型及整型测试结果
sh get_score_2config_spec2006_1core_all.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
"spec2006-ncore")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#spec2000多核浮点型及整型测试结果
sh get_score_2config_spec2006_ncore_all.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
"SpecJvm2008")
echo --------------------------------------------------------------------------------
cmdStr="The current test case is $TestCase."
echo $cmdStr
#SpecJvm2008测试
sh create_Excel_Points_SpecJvm2008.sh $TestType $Platform $TestCase
echo --------------------------------------------------------------------------------
;;
*)
cmdStr="Error:UnSupport this Testcase:$Testcase.Please check it!"
echo $cmdStr
exit 1
;;
esac
echo [$TestCase] write results as Ini File successfully!
echo --------------------------------------------------------------------------------
|
C++ | UTF-8 | 1,604 | 2.875 | 3 | [] | no_license | String toHex(uint16_t dec){
//double majorD = dec/16;
//Serial.println("dec = " + String(dec));
int major = dec/16;
//double minor = majorD - major;
int minor = dec%16;
//Serial.println("major = " + String(major));
//Serial.println("minor = " + String(minor));
int intVal[2];
intVal[0] = major;
intVal[1] = minor;
char witch[2];
for(int i=0; i<2; i++){
if(intVal[i] == 0){witch[i] = '0';}
else if(intVal[i] == 1){witch[i] = '1';}
else if(intVal[i] == 2){witch[i] = '2';}
else if(intVal[i] == 3){witch[i] = '3';}
else if(intVal[i] == 4){witch[i] = '4';}
else if(intVal[i] == 5){witch[i] = '5';}
else if(intVal[i] == 6){witch[i] = '6';}
else if(intVal[i] == 7){witch[i] = '7';}
else if(intVal[i] == 8){witch[i] = '8';}
else if(intVal[i] == 9){witch[i] = '9';}
else if(intVal[i] == 10){witch[i] = 'A';}
else if(intVal[i] == 11){witch[i] = 'B';}
else if(intVal[i] == 12){witch[i] = 'C';}
else if(intVal[i] == 13){witch[i] = 'D';}
else if(intVal[i] == 14){witch[i] = 'E';}
else if(intVal[i] == 15){witch[i] = 'F';}
else{ Serial.println("ERROR");}
}
String out = witch;
out = out.substring(0,2);
//Serial.println("out = " + out);
return out;
}
// return witch;
/*char witch[2]; //the german word for witch is "die Hexe";
if(major<10){
witch[0] = '0' + major;
delay(10);
}
else{
witch[0] = '0' + major%10 + 17;
delay(10);
}
if(minor<10){
witch[1] = '0' + minor;
delay(10);
}
else{
witch[1] = '0' + minor%10 + 17;
delay(10);
}
return witch;
}*/
|
JavaScript | UTF-8 | 2,611 | 2.875 | 3 | [] | no_license | var xhr = new XMLHttpRequest()
xhr.open("GET","https://raw.githubusercontent.com/Rajavasanthan/jsondata/master/pagenation.json", true)
xhr.send()
xhr.onload=function() {
var data = JSON.parse(this.response);
let final = document.createElement('div');
final.setAttribute('id','final1');
document.body.append(final);
const choosePerson = (details) => {
console.log(details, 'details');
const checkPerson=document.getElementsByClassName('personDetails')
console.log( checkPerson[0], final, typeof checkPerson, typeof final);
if( checkPerson[0]){
document.getElementById('final1').removeChild(checkPerson[0]);
}
let page = document.createElement('div');
page.setAttribute('class','personDetails');
page.innerHTML= `${details.id}. Name: ${details.name} Email: ${details.email}`;
final.append(page)
}
let wrap = document.createElement('div');
document.body.append(wrap);
wrap.setAttribute('class','wrapperStyle');
const prev = document.createElement('span')
prev.innerHTML='<<'
wrap.appendChild(prev)
prev.setAttribute('class','person')
let maxLimit = 24 ;
let previousLimit = 0;
function pagination(previousLimit, maxLimit) {
// previousLimit = previousLimit;
// maxLimit = maxLimit;
// const check = nextPage ? index > : previousLimit <= limit;
data.length > 0 && data.map(( details, index ) => {
if ( index > previousLimit && index <= maxLimit ) {
// previousLimit = previousLimit+1;
let person = document.createElement('span');
person.innerHTML = details.id;
person.setAttribute('class', 'person');
wrap.appendChild(person);
person.onclick = function() {
choosePerson(details);
};
}
// console.log(details.id, 'id');
})
console.log(previousLimit, maxLimit);
previousLimit = previousLimit;
maxLimit = maxLimit
}
pagination(previousLimit, maxLimit);
const next = document.createElement('span')
next.innerHTML='>>'
wrap.appendChild(next)
next.setAttribute('class','person')
next.onclick = function() {
pagination(previousLimit + 25, maxLimit + 25);
}
// var first = createElement('first')
// createElement.innerHTML = '1'
// var res = getElementById("id")
// var res= res.slice(0,20)
}; |
PHP | UTF-8 | 242 | 2.6875 | 3 | [] | no_license | <?php
namespace App;
class Option
{
public $id;
public $name;
public $sub;
public function __construct($id, $name, $sub = false)
{
$this->id = $id;
$this->name = $name;
$this->sub = $sub;
}
} |
C# | UTF-8 | 1,357 | 3.3125 | 3 | [] | no_license | namespace P2_06_ByteBank
{
class ContaCorrente
{
private Cliente _titular;
public Cliente Titular
{
get => _titular;
set { _titular = value; }
}
public int _agencia;
public int Agencia { get => _agencia; set { _agencia = value; } }
public int _numero;
public int Numero { get => _numero; set { _numero = value; } }
private double saldo = 100;
public double Saldo
{
get => saldo;
set
{
if (value >= 0)
saldo = value;
}
}
public bool Sacar(double valor)
{
if (saldo < valor)
{
return false;
}
saldo -= valor;
return true;
}
public void Depositar(double valor) =>
saldo += valor;
public bool Transferir(double valor, ContaCorrente contaDestino)
{
if (saldo < valor)
return false;
saldo -= valor;
contaDestino.Depositar(valor);
return true;
}
public override string ToString() =>
string.Format(@"
{0}
Agencia: {1},
Conta: {2},
Saldo: {3},
", _titular.Nome, _agencia, _numero, saldo);
}
} |
PHP | UTF-8 | 692 | 2.515625 | 3 | [] | no_license | <?php
$courseID = $_GET['id'];
try {
$con = new PDO("mysql:host=localhost;dbname=youthcyb_cs160s4g2;charset=utf8mb4", "youthcyb_160s4g2", "group2gumface");
$con->exec("set names utf8");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO roadmap_data (course_id)
VALUES (".$courseID.")";
// use exec() because no results are returned
$con->exec($sql);
$message1 = "New course added successfully to your roadmap";
echo "<script type='text/javascript'>alert('$message1');</script>";
}
catch(PDOException $e)
{
$message2 = "already in your roadmap";
echo "<script type='text/javascript'>alert('$message2');</script>";
}
?> |
Python | UTF-8 | 2,316 | 2.515625 | 3 | [
"MIT"
] | permissive | from django.urls import reverse, resolve
from django.test import TestCase
from users.views import signup
from users.models import CustomUser
from users.forms import CustomUserCreationForm
class SignUpTests(TestCase):
def setUp(self):
url = reverse('signup')
self.response = self.client.get(url)
def test_index_view_is_available(self):
self.assertEquals(self.response.status_code, 200)
def test_signup_url_resolves_signup_view(self):
view = resolve('/signup/')
self.assertEquals(view.func, signup)
def test_csrf(self):
self.assertContains(self.response, 'csrfmiddlewaretoken')
def test_contains_form(self):
form = self.response.context.get('form')
self.assertIsInstance(form, CustomUserCreationForm)
class SuccessfulSignUpTests(TestCase):
def setUp(self):
url = reverse('signup')
data = {
'username': 'john',
'email': 'john@doe.com',
'password1': 'abcdef123456',
'password2': 'abcdef123456'
}
self.response = self.client.post(url, data)
self.index_url = reverse('index')
def test_redirection(self):
"""
A valid form submission should redirect the user to the home page
"""
self.assertRedirects(self.response, self.index_url)
def test_user_creation(self):
self.assertTrue(CustomUser.objects.exists())
def test_user_authentication(self):
"""
Create a new request to an arbitrary page.
The resulting response should now have `user` in its context after a successful sign up.
"""
response = self.client.get(self.index_url)
user = response.context.get('user')
self.assertTrue(user.is_authenticated)
class InvalidSignUpTest(TestCase):
def setUp(self):
url = reverse('signup')
self.response = self.client.post(url, {})
def test_signup_status_code(self):
"""
An invalid form submission should return to the same page
"""
self.assertEquals(self.response.status_code, 200)
def test_form_errors(self):
form = self.response.context.get('form')
self.assertTrue(form.errors)
def test_user_creation(self):
self.assertFalse(CustomUser.objects.exists())
|
Markdown | UTF-8 | 713 | 3.078125 | 3 | [] | no_license | # Scrabble-Game
It takes input as a bag of letters and finds a word of maximum score(based on a formula) from a dictionary of words which is broken into smaller dictionaries on the basis of word's length.
Words selected from dictionary can be created from letters in bag.
# Sample-Inputs
- O* tbLush
- Zy ms*e
# Some Points
- Bag of letters can have alphabets(in upper or lower case) which may be separated by space(s) or stars(*).
- A star can match any vowel.
- There are weights associated with each alphabet which will help in calculation of score for a word.
- Weights for each alphabet, star and the formula for calculation of final score of a word can be seen in scrabble.
- C file.
|
Java | UTF-8 | 937 | 2.359375 | 2 | [] | no_license | package com.apps.testpackage;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class scrolldown {
public static void main(String[] args) {
//Wait <WebDriver> wait = null;
System.setProperty("webdriver.chrome.driver", "/Users/saidinesh/eclipse-workspace/Drivers/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor) driver;
// Launch the application
driver.get("http://demo.guru99.com/test/guru99home/");
//To maximize the window. This code may not work with Selenium 3 jars. If script fails you can remove the line below
driver.manage().window().maximize();
// This will scroll down the page by 1000 pixel vertical
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
}
|
TypeScript | UTF-8 | 774 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | import { ScaleConfig } from '../../common/types';
import { ScaleType } from '../../common/constants';
import { Size } from '../../../../utils/types';
const X_TICK_DISTANCE_PX = 100;
// Y ticks can be closer since the height of a label is much less than the max width of a label across multiple resolutions
const Y_TICK_DISTANCE_PX = 30;
const MIN_TICK_COUNT = 2;
export const getTickCount = (
{ width, height }: Size,
{ yScaleType }: ScaleConfig
): { xTickCount: number; yTickCount: number } => {
const xTickCount = Math.max(Math.floor(width / X_TICK_DISTANCE_PX), MIN_TICK_COUNT);
const yTickCount = Math.max(
Math.floor(height / (Y_TICK_DISTANCE_PX + (yScaleType === ScaleType.Log ? 60 : 0))),
MIN_TICK_COUNT
);
return { xTickCount, yTickCount };
};
|
Java | UTF-8 | 232 | 1.75 | 2 | [
"Apache-2.0"
] | permissive | package com.common.android.utils.input;
import android.view.KeyEvent;
public interface KeyListener {
boolean onKeyUp(final int keyCode, final KeyEvent event);
boolean onKeyDown(final int keyCode, final KeyEvent event);
} |
SQL | UTF-8 | 28,215 | 3.125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.0-dev
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 29, 2016 at 10:45 PM
-- Server version: 10.1.10-MariaDB
-- PHP Version: 7.0.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `photographer`
--
-- --------------------------------------------------------
--
-- Table structure for table `categorylists`
--
CREATE TABLE `categorylists` (
`id` int(11) NOT NULL,
`category_name` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `categorylists`
--
INSERT INTO `categorylists` (`id`, `category_name`) VALUES
(1, 'Abstract'),
(2, 'Animals'),
(3, 'Black and White'),
(4, 'Celebrities'),
(5, 'City & Architecture'),
(6, 'Commercial'),
(7, 'Concert'),
(8, 'Family'),
(9, 'Fashion'),
(10, 'Film'),
(11, 'Fine Art'),
(12, 'Food'),
(13, 'Journalism'),
(14, 'Landscapes'),
(15, 'Macro'),
(16, 'Nature'),
(17, 'People'),
(18, 'Performing Arts'),
(19, 'Sport'),
(20, 'Still Life'),
(21, 'Street'),
(22, 'Transportation'),
(23, 'Travel'),
(24, 'Underwater'),
(25, 'Urban Exploration'),
(26, 'Wedding'),
(27, 'Uncategorised');
-- --------------------------------------------------------
--
-- Table structure for table `favorites`
--
CREATE TABLE `favorites` (
`user_id` int(11) NOT NULL,
`image_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `favorites`
--
INSERT INTO `favorites` (`user_id`, `image_id`, `created_at`, `updated_at`) VALUES
(1, 6, '2016-04-29 20:37:03', '2016-04-29 20:37:03'),
(1, 9, '2016-04-29 20:43:44', '2016-04-29 20:43:44'),
(1, 15, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(1, 35, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(2, 7, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(2, 18, '2016-04-29 20:25:10', '2016-04-29 20:25:10'),
(2, 21, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(2, 44, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(3, 25, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(3, 58, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(4, 47, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(4, 50, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(4, 52, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(5, 26, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(5, 57, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(6, 13, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(6, 29, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(7, 56, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(8, 11, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(9, 67, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(10, 1, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(10, 11, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(11, 16, '2016-04-29 19:19:00', '0000-00-00 00:00:00'),
(12, 29, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(12, 44, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(13, 7, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(13, 26, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(13, 58, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(14, 23, '2016-04-29 19:19:08', '0000-00-00 00:00:00'),
(15, 42, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(15, 60, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(15, 66, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(16, 7, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(16, 46, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(16, 64, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(16, 67, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(17, 9, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(17, 13, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(17, 22, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(17, 38, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(17, 64, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(18, 27, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(18, 35, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(18, 38, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(18, 48, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(18, 51, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(19, 9, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(19, 13, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(20, 2, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(20, 19, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(21, 6, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(22, 41, '2016-04-29 19:19:16', '0000-00-00 00:00:00'),
(23, 18, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(23, 52, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(23, 60, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(23, 64, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(24, 12, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(24, 66, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(25, 11, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(25, 19, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(25, 61, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(26, 27, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(26, 57, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(27, 20, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(27, 31, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(27, 35, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(27, 62, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(28, 18, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(28, 55, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(29, 24, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(29, 33, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(29, 67, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(30, 27, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(30, 31, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(31, 5, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(31, 40, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(31, 66, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(32, 15, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(32, 17, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(32, 18, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(32, 38, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(33, 9, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(33, 41, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(33, 52, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(34, 3, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(34, 31, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(34, 38, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(35, 12, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(35, 42, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(36, 57, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(36, 63, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(37, 37, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(38, 9, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(38, 15, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(38, 42, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(38, 55, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(39, 2, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(39, 11, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(39, 16, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(39, 32, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(39, 45, '2016-04-29 19:17:41', '0000-00-00 00:00:00'),
(40, 31, '2016-04-29 19:16:11', '0000-00-00 00:00:00'),
(40, 65, '2016-04-29 19:17:41', '0000-00-00 00:00:00');
-- --------------------------------------------------------
--
-- Table structure for table `follows`
--
CREATE TABLE `follows` (
`follower_id` int(11) NOT NULL,
`followed_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`type` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'follow'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `follows`
--
INSERT INTO `follows` (`follower_id`, `followed_id`, `created_at`, `updated_at`, `type`) VALUES
(3, 1, '2016-04-29 17:39:58', '2016-04-29 17:39:58', 'follow'),
(3, 5, '2016-04-28 22:07:59', '2016-04-28 22:07:59', 'follow'),
(4, 3, '2016-04-28 15:59:45', '2016-04-28 15:59:45', 'follow'),
(4, 5, '2016-04-28 22:03:10', '2016-04-28 22:03:10', 'follow'),
(5, 3, '2016-04-28 21:49:34', '2016-04-28 21:49:34', 'follow'),
(6, 1, '2016-04-29 17:47:20', '2016-04-29 17:47:20', 'follow'),
(13, 3, '2016-04-29 20:00:23', '2016-04-29 20:00:23', 'follow'),
(27, 1, '2016-04-29 19:38:47', '2016-04-29 19:38:47', 'follow'),
(32, 1, '2016-04-29 19:40:30', '2016-04-29 19:40:30', 'follow');
-- --------------------------------------------------------
--
-- Table structure for table `images`
--
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`image_title` varchar(255) NOT NULL,
`image_description` varchar(600) NOT NULL,
`image_link` varchar(255) NOT NULL,
`image_category` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`view_counter` int(11) NOT NULL DEFAULT '0',
`rating_counter` int(11) NOT NULL,
`pulse_counter` decimal(10,2) NOT NULL,
`popularity` varchar(10) NOT NULL DEFAULT 'fresh',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `images`
--
INSERT INTO `images` (`id`, `image_title`, `image_description`, `image_link`, `image_category`, `user_id`, `view_counter`, `rating_counter`, `pulse_counter`, `popularity`, `created_at`, `updated_at`) VALUES
(1, 'Aurora Borealis', '', '5723835079d4e.jpg', 16, 6, 4, 1, '25.00', 'fresh', '2016-04-29 19:14:01', '2016-04-29 19:14:01'),
(2, 'The two of us', '', '572383368119e.jpg', 15, 6, 4, 1, '25.00', 'fresh', '2016-04-29 19:14:07', '2016-04-29 19:14:07'),
(3, 'Test Image Upload - 1', 'Dummy data for test image', '571d2fadbfc83.jpg', 16, 3, 25, 6, '24.00', 'fresh', '2016-04-29 18:44:08', '2016-04-29 18:44:08'),
(4, 'Test Image Upload - 2', '', '571d2ff5bcc59.jpg', 1, 3, 23, 5, '21.74', 'fresh', '2016-04-29 20:34:18', '2016-04-29 20:34:18'),
(5, 'Test Image Upload - 3', '', '571d3044b53d7.jpg', 9, 3, 47, 0, '0.00', 'fresh', '2016-04-29 08:38:46', '2016-04-29 08:38:46'),
(6, 'Test Image Upload - 4', '', '571d30a7c3500.jpg', 15, 3, 4, 2, '50.00', 'fresh', '2016-04-29 20:37:04', '2016-04-29 20:37:04'),
(7, 'Test Image Upload - 6', '', '571d312e44d32.jpg', 1, 3, 108, 56, '51.85', 'upcoming', '2016-04-29 20:24:50', '2016-04-29 20:24:50'),
(8, 'Test Image Upload - 7', '', '571d322f6e7d0.jpg', 1, 3, 6, 1, '16.67', 'fresh', '2016-04-29 08:48:53', '2016-04-29 08:48:53'),
(9, 'light trail by sohel', 'light trail', '571dcfbcbd4b6.jpg', 1, 4, 70, 26, '37.14', 'upcoming', '2016-04-29 20:45:02', '2016-04-29 20:45:02'),
(10, 'Upload Test Image', '', '571dd0ef05e29.jpg', 16, 3, 15, 5, '33.33', 'fresh', '2016-04-29 20:14:10', '2016-04-29 20:14:10'),
(11, 'test data upload', '', '571dd121144e7.jpg', 16, 3, 7, 5, '71.43', 'fresh', '2016-04-28 15:32:48', '2016-04-28 15:32:48'),
(12, 'khik khik ', '', '571de21f0aedb.jpg', 1, 5, 16, 0, '0.00', 'fresh', '2016-04-29 08:19:00', '2016-04-29 08:19:00'),
(13, 'Test Image Upload - Jilani', 'This is captured by jilani ... ', '57228cda01d2d.jpg', 14, 5, 3, 0, '0.00', 'fresh', '2016-04-29 08:02:26', '2016-04-29 08:02:26'),
(14, 'City Light', 'City Light by Hasan Hafiz Pasha, it\'s pasha\'s photography', '572314f38fe95.jpg', 17, 3, 3, 1, '33.33', 'fresh', '2016-04-29 08:48:47', '2016-04-29 08:48:47'),
(15, 'Lightroom Preset Balloon Released', '\r\nI\'m super excited to let you all know that today, after 2 months of tweaking and testing, I\'ve finally released my Presets package for Lightroom!', '5723822ecaf3e.jpg', 1, 6, 2, 1, '50.00', 'fresh', '2016-04-29 15:49:08', '2016-04-29 15:49:08'),
(16, 'Counting sheep', 'Morning view near Schiedam, Netherlands. Lost count at about a hundred sheep :-)', '5723829f62a11.jpg', 16, 6, 1, 0, '0.00', 'fresh', '2016-04-29 17:35:46', '2016-04-29 17:35:46'),
(17, 'Shooting Star', '', '572382c0c4608.jpg', 11, 6, 0, 0, '0.00', 'fresh', '2016-04-29 15:50:24', '2016-04-29 15:50:24'),
(18, 'dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit', '', 'photo-1Af0sF2OS5S5gatqrKzVP_Silhoutte.jpg', 21, 12, 3, 1, '33.33', 'fresh', '2016-04-29 20:33:50', '2016-04-29 20:33:50'),
(19, 'eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est.', '', 'photo-1iFJ5qQylTD2POC68qBgh_Uluru.jpg', 5, 10, 0, 0, '0.00', 'fresh', '2016-04-29 20:25:54', '0000-00-00 00:00:00'),
(20, 'Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc', '', 'photo-12919e13b.jpg', 10, 11, 1, 0, '0.00', 'fresh', '2016-04-29 20:42:34', '2016-04-29 20:42:34'),
(21, 'rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac', '', 'photo-1415931633537-351070d20b81.jpg', 25, 28, 0, 0, '0.00', 'fresh', '2016-04-29 20:26:10', '0000-00-00 00:00:00'),
(22, 'Sed eget lacus. Mauris non dui nec urna suscipit nonummy.', '', 'photo-1422207109431-97544339f995.jpg', 3, 4, 1, 0, '0.00', 'fresh', '2016-04-29 20:26:18', '2016-04-29 19:14:07'),
(23, 'ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat', '', 'photo-1422207134147-65fb81f59e38.jpg', 5, 11, 0, 0, '0.00', 'fresh', '2016-04-29 20:26:26', '0000-00-00 00:00:00'),
(24, 'adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu', '', 'photo-1424746219973-8fe3bd07d8e3.jpg', 23, 5, 0, 0, '0.00', 'fresh', '2016-04-29 20:26:36', '0000-00-00 00:00:00'),
(25, 'vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue', '', 'photo-1425315283416-2acc50323ee6.jpg', 21, 2, 0, 0, '0.00', 'fresh', '2016-04-29 20:26:45', '0000-00-00 00:00:00'),
(26, 'ultrices a, auctor non, feugiat nec, diam. Duis mi enim,', '', 'photo-1427501482951-3da9b725be23.jpg', 23, 13, 2, 0, '0.00', 'fresh', '2016-04-29 20:27:00', '2016-04-29 20:00:23'),
(27, 'erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla', '', 'photo-1427805371062-cacdd21273f1.jpg', 24, 7, 0, 0, '0.00', 'fresh', '2016-04-29 20:27:08', '0000-00-00 00:00:00'),
(28, 'vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend', '', 'photo-1428263197823-ce6a8620d1e1.jpg', 3, 37, 0, 0, '0.00', 'fresh', '2016-04-29 20:27:21', '0000-00-00 00:00:00'),
(29, 'eu nulla at sem molestie sodales. Mauris blandit enim consequat', '', 'photo-1428278953961-a8bc45e05f72.jpg', 2, 36, 0, 0, '0.00', 'fresh', '2016-04-29 20:27:29', '0000-00-00 00:00:00'),
(30, 'dictum mi, ac mattis velit justo nec ante. Maecenas mi', '', 'photo-1428279148693-1cf2163ed67d.jpg', 16, 27, 0, 0, '0.00', 'fresh', '2016-04-29 20:27:37', '0000-00-00 00:00:00'),
(31, 'Donec felis orci, adipiscing non, luctus sit amet, faucibus ut,', '', 'photo-1428452932365-4e7e1c4b0987.jpg', 7, 19, 0, 0, '0.00', 'fresh', '2016-04-29 20:27:46', '0000-00-00 00:00:00'),
(32, 'natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.', '', 'photo-1428865798880-73444f4cbefc.jpg', 20, 31, 0, 0, '0.00', 'fresh', '2016-04-29 20:27:55', '0000-00-00 00:00:00'),
(33, 'Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor', '', 'photo-1428894976381-853e04af6262.jpg', 2, 6, 0, 0, '0.00', 'fresh', '2016-04-29 20:28:04', '0000-00-00 00:00:00'),
(34, 'at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum', '', 'photo-1428930377079-45a584b6dd6b.jpg', 5, 4, 0, 0, '0.00', 'fresh', '2016-04-29 20:28:18', '0000-00-00 00:00:00'),
(35, 'ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque', '', 'photo-1428948304740-392e214d312f.jpg', 4, 5, 0, 0, '0.00', 'fresh', '2016-04-29 20:28:25', '0000-00-00 00:00:00'),
(36, 'eu arcu. Morbi sit amet massa. Quisque porttitor eros nec', '', 'photo-1428954376791-d9ae785dfb2d.jpg', 15, 33, 0, 0, '0.00', 'fresh', '2016-04-29 20:28:34', '0000-00-00 00:00:00'),
(37, 'ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem', '', 'photo-1428959249159-5706303ea703.jpg', 20, 35, 0, 0, '0.00', 'fresh', '2016-04-29 20:28:44', '0000-00-00 00:00:00'),
(38, 'Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna.', '', 'photo-1428976343495-f2c66e701b2b.jpg', 9, 7, 0, 0, '0.00', 'fresh', '2016-04-29 20:28:52', '0000-00-00 00:00:00'),
(39, 'ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel', '', 'photo-1428976365951-b70e0fa5c551.jpg', 24, 7, 0, 0, '0.00', 'fresh', '2016-04-29 20:29:00', '0000-00-00 00:00:00'),
(40, 'magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu', '', 'photo-1429030150151-548690082f0b.jpg', 20, 31, 0, 0, '0.00', 'fresh', '2016-04-29 20:29:09', '0000-00-00 00:00:00'),
(41, 'consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus.', '', 'photo-1429032021766-c6a53949594f.jpg', 20, 14, 0, 0, '0.00', 'fresh', '2016-04-29 20:29:18', '0000-00-00 00:00:00'),
(42, 'gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet', '', 'photo-1429041966141-44d228a42775.jpg', 2, 16, 0, 0, '0.00', 'fresh', '2016-04-29 20:29:27', '0000-00-00 00:00:00'),
(43, 'nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat.', '', 'photo-1429042007245-890c9e2603af.jpg', 11, 40, 0, 0, '0.00', 'fresh', '2016-04-29 20:29:36', '0000-00-00 00:00:00'),
(44, 'Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu.', '', 'photo-1429152937938-07b5f2828cdd.jpg', 5, 8, 0, 0, '0.00', 'fresh', '2016-04-29 20:29:46', '0000-00-00 00:00:00'),
(45, 'vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci', '', 'photo-1429198739803-7db875882052.jpg', 17, 32, 2, 0, '0.00', 'fresh', '2016-04-29 20:29:55', '2016-04-29 19:40:30'),
(46, 'Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae,', '', 'photo-1429277005502-eed8e872fe52.jpg', 18, 4, 0, 0, '0.00', 'fresh', '2016-04-29 20:30:03', '0000-00-00 00:00:00'),
(47, 'elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris', '', 'photo-1429277096327-11ee3b761c93.jpg', 21, 16, 0, 0, '0.00', 'fresh', '2016-04-29 20:30:12', '0000-00-00 00:00:00'),
(48, 'Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna.', '', 'photo-1429277158984-614d155e0017.jpg', 10, 16, 0, 0, '0.00', 'fresh', '2016-04-29 20:30:20', '0000-00-00 00:00:00'),
(49, 'enim consequat purus. Maecenas libero est, congue a, aliquet vel,', '', 'photo-1429308755210-25a272addeb3.jpg', 10, 40, 0, 0, '0.00', 'fresh', '2016-04-29 20:30:27', '0000-00-00 00:00:00'),
(50, 'eu tellus eu augue porttitor interdum. Sed auctor odio a', '', 'photo-1429547584745-d8bec594c82e.jpg', 17, 29, 0, 0, '0.00', 'fresh', '2016-04-29 20:30:35', '0000-00-00 00:00:00'),
(51, 'tristique senectus et netus et malesuada fames ac turpis egestas.', '', 'photo-1429616588302-fec569e203ce.jpg', 20, 19, 0, 0, '0.00', 'fresh', '2016-04-29 20:30:48', '0000-00-00 00:00:00'),
(52, 'malesuada fames ac turpis egestas. Fusce aliquet magna a neque.', '', 'photo-1429637119272-20043840c013.jpg', 20, 27, 3, 0, '0.00', 'fresh', '2016-04-29 20:30:59', '2016-04-29 19:39:10'),
(53, 'Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla', '', 'photo-1429734160945-4f85244d6a5a.jpg', 18, 7, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:07', '0000-00-00 00:00:00'),
(54, 'cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut', '', 'photo-1429743433956-0e34951fcc67.jpg', 12, 37, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:15', '0000-00-00 00:00:00'),
(55, 'cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet', '', 'photo-1429966163023-c132bc887fdd.jpg', 8, 20, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:22', '0000-00-00 00:00:00'),
(56, 'ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero', '', 'photo-1430263326118-b75aa0da770b.jpg', 16, 10, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:31', '0000-00-00 00:00:00'),
(57, 'tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim', '', 'photo-1430598825529-927d770c194f.jpg', 15, 28, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:37', '0000-00-00 00:00:00'),
(58, 'eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis', '', 'photo-1430747562296-5556d17a15a5.jpg', 16, 35, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:46', '0000-00-00 00:00:00'),
(59, 'elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu', '', 'photo-1430760814266-9c81759e5e55.jpg', 4, 14, 0, 0, '0.00', 'fresh', '2016-04-29 20:31:53', '0000-00-00 00:00:00'),
(60, 'Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna,', '', 'photo-1430866880825-336a7d7814eb.jpg', 1, 37, 0, 0, '0.00', 'fresh', '2016-04-29 20:32:03', '0000-00-00 00:00:00'),
(61, 'et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget', '', 'photo-1430916273432-273c2db881a0.jpg', 7, 4, 0, 0, '0.00', 'fresh', '2016-04-29 20:32:14', '0000-00-00 00:00:00'),
(62, 'lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque.', '', 'photo-1431051047106-f1e17d81042f.jpg', 25, 21, 0, 0, '0.00', 'fresh', '2016-04-29 20:32:20', '0000-00-00 00:00:00'),
(63, 'rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in,', '', 'photo-1437912958086-300d70657a11.jpg', 3, 16, 0, 0, '0.00', 'fresh', '2016-04-29 20:33:17', '0000-00-00 00:00:00'),
(64, 'Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin', '', 'photo-1431578500526-4d9613015464.jpg', 4, 24, 0, 0, '0.00', 'fresh', '2016-04-29 20:32:40', '0000-00-00 00:00:00'),
(65, 'malesuada fames ac turpis egestas. Fusce aliquet magna a neque.', '', 'photo-1431184052543-809fa8cc9bd6.jpg', 20, 34, 0, 0, '0.00', 'fresh', '2016-04-29 20:32:33', '0000-00-00 00:00:00'),
(66, 'felis. Donec tempor, est ac mattis semper, dui lectus rutrum', '', 'photo-1437913135140-944c1ee62782.jpg', 8, 40, 0, 0, '0.00', 'fresh', '2016-04-29 20:33:26', '0000-00-00 00:00:00'),
(67, 'consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque', '', 'photo-1437915015400-137312b61975.jpg', 2, 34, 0, 0, '0.00', 'fresh', '2016-04-29 20:33:33', '0000-00-00 00:00:00'),
(68, 'সবুজের স্পন্দন - ১', '', '5723c6b050ba7.jpg', 16, 1, 0, 0, '0.00', 'fresh', '2016-04-29 20:40:16', '2016-04-29 20:40:16'),
(69, 'Fedded Green', '', '5723c6d7bc446.jpg', 16, 1, 1, 0, '0.00', 'fresh', '2016-04-29 20:41:05', '2016-04-29 20:41:05');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `created_at`, `updated_at`) VALUES
(1, 'Hasan Hafiz Pasha', 'mach.pasha@gmail.com', '$2y$10$/Hxr3lYMe5YtbfLAjOLziu.7vZMhe/O2Jlclv4TFxRdKOeGjjrV52', '2016-04-29 17:05:45', '2016-04-24 20:29:27'),
(2, 'Abu Sohel', 'abusoheljnu@gmail.com', '$2y$10$2klMD5sDGl2/cDfiLDNC2ewN82RQWCI1zHN49jfszBYbYkAQ7eNqm', '2016-04-29 17:05:55', '2016-04-25 17:57:21'),
(3, 'jilani khandaker', 'jilanikhandaker@yahoo.com', '$2y$10$7RKkNN25kKJNlRWysoAEYOjk5cQ3HJpMDQxutr.cFsfeuQzlnL//u', '2016-04-29 17:06:01', '2016-04-25 19:20:34'),
(4, 'MD Tazin Jahed Jony', 'tazinjahed@gmail.com', '$2y$10$4zmHgFwHrZeS.zm1PCMmpuf66jnI3m9cyTLuU46PJLpbipiDAcRPG', '2016-04-29 17:06:04', '2016-04-29 15:40:19'),
(5, 'Anwarul Islam Abir', 'anwarulislamabir@gmail.com', '$2y$10$.2m/XMBJZVD5tQ7MX3KDKe3xKgDbP8LbpeGR.PyeIoBJ5VadUVV4u', '2016-04-29 17:26:34', '2016-04-29 17:26:34'),
(6, 'arnisha akhter jubly', 'arnishaakhter@yahoo.com', '$2y$10$Nl25aRXR8fnTQUB7LmezzuEkJotMuKhOpVcW4vwGS/FDyl2dhORMi', '2016-04-29 17:27:15', '2016-04-29 17:27:15'),
(7, 'Jannatul Ferdus Ruma', 'ruma.ruma705@gmail.com', '$2y$10$hlRynABUXbu1VQYlNTStvutc.oFpLtwex2d4le.v4QZTIvv4hap7S', '2016-04-29 17:27:54', '2016-04-29 17:27:54'),
(8, 'Mahadi Hasan Raju', 'mahadihasannight@gmail.com', '$2y$10$AFA4/LSKWA3iYp37kLnW7./AIAExROOe2hJpcTqOpmHj8tP7DZAMm', '2016-04-29 17:28:27', '2016-04-29 17:28:27'),
(9, 'Alamin Hossain', 'mohammad.alamin51@yahoo.com', '$2y$10$kMlyepFqM6ecPEV5s/zKKOGG3.jpA4NFEqGPrzS86qH3.FV3FpXs.', '2016-04-29 17:28:59', '2016-04-29 17:28:59'),
(10, 'Zobaydul Korim Rony', 'zkrony001@gmail.com', '$2y$10$rEeeHeTMPTquIs35RXpxIeNLwZaxw5sb4NOVPkiLn6XS2AhMUL3ya', '2016-04-29 17:29:52', '2016-04-29 17:29:52'),
(11, 'mehedi pervez kanon', 'mehedipervez@gmail.com', '$2y$10$XYXViyy2atDcmUWbvRFDgeZmWWYTQqgVI7Hsr0fFgJoS12UXhmknm', '2016-04-29 17:30:43', '2016-04-29 17:30:43'),
(12, 'Jarin Tasnim', 'diba.ipsc@gmail.com', '$2y$10$Hf3KtyVo7KDivxG3gVyM9uCiHIAoyPLaRLdgW7bMbKqpkhR09m5l6', '2016-04-29 17:31:22', '2016-04-29 17:31:22'),
(13, 'Masudur Rahman Masud', 'masudjnu87@gmail.com', '$2y$10$ZHD6Gqy/3WR8XLflYagseOIUhuXkysVM0mtMx5sQOvfADhuq15SoS', '2016-04-29 17:32:50', '2016-04-29 17:32:50'),
(14, 'Alamgir Hossain', 'alcsejnu@gmail.com', '$2y$10$sWptN9UDnqAu80DkHSq29Oo/sGhXwZJnnvjdRExhqzf6lUiAdPhJ6', '2016-04-29 17:33:48', '2016-04-29 17:33:48'),
(15, 'Griffin Moss', 'et@arcueuodio.com', 'NIU91EYR7FX', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(16, 'Yuli Pope', 'pretium.aliquet@liberoest.co.uk', 'PJM07DZV3DO', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(17, 'Linus Berger', 'Suspendisse.eleifend.Cras@mauris.co.uk', 'EIA88QQK6DG', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(18, 'Walker Lucas', 'justo@famesac.com', 'XTH53FYC4DW', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(19, 'Talon Barr', 'nec.ligula@enim.com', 'OCN36IEW1PF', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(20, 'Zeph Greer', 'at.iaculis@risusvariusorci.edu', 'QVG73MTJ3CS', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(21, 'Benedict Benton', 'Nulla.facilisis.Suspendisse@libero.net', 'ARW58LCV8HG', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(22, 'Xanthus Hendricks', 'dui.Cum@cursusIntegermollis.org', 'LGL16HXI8MO', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(23, 'Nicholas Price', 'malesuada.vel@posuerevulputate.ca', 'FMI14HSW4AW', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(24, 'Asher Preston', 'accumsan.sed@magnaSuspendisse.net', 'KJN85EMI6ZQ', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(25, 'Robert Peters', 'vestibulum.Mauris.magna@utipsumac.com', 'HQM73SOM8DZ', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(26, 'Yasir Shaffer', 'tincidunt@vehiculaaliquet.net', 'ETP88YUY3ZM', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(27, 'Colin Carson', 'fringilla.mi@Nullamfeugiatplacerat.net', 'PRR70ITL2KB', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(28, 'Joel Carr', 'vestibulum.Mauris@mi.net', 'OEN34XYW9TP', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(29, 'Lester Odom', 'eget@pharetrasedhendrerit.org', 'LSJ43DPW2ZO', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(30, 'Sean Walton', 'pharetra.Quisque.ac@auctor.com', 'XMD15TQP8RR', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(31, 'Quamar Meyer', 'nisi.sem.semper@magna.net', 'VSE62PMQ0QZ', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(32, 'Mark Irwin', 'eros.turpis@In.org', 'VXM79NFW0OM', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(33, 'Damon Simon', 'Cras.eu@euismodest.net', 'MDC20HFB9IE', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(34, 'Colby Tyson', 'dui.augue.eu@vulputatelacus.co.uk', 'POC19HVY3LP', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(35, 'Kadeem Flowers', 'faucibus@mattissemperdui.net', 'XLP90IGC1UZ', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(36, 'Davis Neal', 'vitae.diam.Proin@turpisAliquam.co.uk', 'AMS16AGM4CD', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(37, 'Abbot Mcmahon', 'sit.amet@faucibusleoin.org', 'EFY89PAC5TG', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(38, 'Dean Guthrie', 'risus.Nulla.eget@acurna.org', 'JHY87TBQ9OU', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(39, 'Dennis Perkins', 'porttitor.vulputate.posuere@justo.edu', 'IJM61BKR9NZ', '2016-04-29 19:10:04', '0000-00-00 00:00:00'),
(40, 'Brian Wilkinson', 'arcu.iaculis@eulacusQuisque.edu', 'WWG29SOG6TF', '2016-04-29 19:10:04', '0000-00-00 00:00:00');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categorylists`
--
ALTER TABLE `categorylists`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `favorites`
--
ALTER TABLE `favorites`
ADD PRIMARY KEY (`user_id`,`image_id`);
--
-- Indexes for table `follows`
--
ALTER TABLE `follows`
ADD PRIMARY KEY (`follower_id`,`followed_id`);
--
-- Indexes for table `images`
--
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `categorylists`
--
ALTER TABLE `categorylists`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;
--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=70;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Markdown | UTF-8 | 1,711 | 2.890625 | 3 | [] | no_license | # Custom block page
The original Pi-Hole code has been modified, first modified 26/06/2018. [License](https://github.com/pi-hole/pi-hole/blob/master/LICENSE).
Info/steps on my custom Pi-Hole block page. It's not finished yet I don't think, but I hope this works as a helpful guide for others.
Thanks to Pi-Hole (Original code [here](https://github.com/pi-hole/pi-hole), site [here](https://pi-hole.net/)) for being awesome and WaLLy3K for providing [the idea and direction](https://github.com/WaLLy3K/Pi-hole-Block-Page).

Custom dark theme of Pi-Hole's blockpage for your sleepy eyes.
---
# 1. Back-up
Copy the pihole directory to wherever you want to back-it-up to. E.g: from root, **cp -r /var/www/html/pihole/ home/pi/**
Don't blame me if your Pi-Hole blows up.
# 2. Shuffle around files
Rename the original block page in /var/www/html/pihole/. Doesn't matter what to, I just used ORIG_blockingpage.css.
Move the background you want into /var/www/html/admin/img/. The one I used is up there, bg.png.
# 3. Custom blockpage
Move blockingpage.css into /var/www/html/pihole/.
Run **sudo service lighttpd force-reload** and you're done!
---
In the CSS file, search for the following if you want to modify specific parts and are a noob at CSS like me.
**Flag1** - Change the background picture.
**Flag2** - The header bar colour and rounded corners. Go 2 code blocks down for header font.
**Flag3** - The "Why am I here?" box of the header that brings up the pop-up box.
**Flag4** - Inside of the above pop-up box.
**Flag5** - The actual blockpage background colour, font, whatever.
**Flag6** - Button details.
**Flag7** - Footer details.
|
Java | UTF-8 | 2,116 | 3.046875 | 3 | [] | no_license | package modele;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import dao.HeuresSessionModuleDao;
import dao.ModuleDao;
/**
* Objet qui contient la liste des boutons reliés aux matières de la session
*
* @author Jerome
*
*/
public class Bouton {
private ArrayList<JRadioButton> boutonDesModules;
private ButtonGroup groupeDeBoutons;
public ArrayList<JRadioButton> getBoutonDesModules() {
return boutonDesModules;
}
public void setBoutonDesModules(ArrayList<JRadioButton> boutonDesModules) {
this.boutonDesModules = boutonDesModules;
}
public ButtonGroup getGroupeDeBoutons() {
return groupeDeBoutons;
}
public void setGroupeDeBoutons(ButtonGroup groupeDeBoutons) {
this.groupeDeBoutons = groupeDeBoutons;
}
/**
* Méthode qui remplit une liste de Bouton avec les matières et leur nombre
* d'heures si ils ont encore des heures de disponibles
*
* @param idSession
*/
public void remplir(int idSession) {
boutonDesModules = new ArrayList<JRadioButton>();
groupeDeBoutons = new ButtonGroup();
ArrayList<Module> listeModule = new ArrayList<Module>();
ModuleDao moduleDao = new ModuleDao();
Session session = new Session();
session.setIdSession(idSession);
listeModule = moduleDao.findModuleAvecHeures(idSession);
HashMap<Module, Integer> liste = new HashMap<>();
HeuresSessionModuleDao heureSessionModuleDao = new HeuresSessionModuleDao();
for (Module module : listeModule) {
liste.put(
module,
heureSessionModuleDao.findHeuresSessionModule(
session.getIdSession(), module.getIdModule())
.getNbreHeuresDisponibles());
}
for (Module clefs : liste.keySet()) {
JRadioButton bouton = new JRadioButton(clefs.getNomModule() + " : "
+ liste.get(clefs) + "/" + clefs.getNbHeuresAnnuelles()
+ " heures disponibles");
boutonDesModules.add(bouton);
groupeDeBoutons.add(bouton);
}
JRadioButton boutonSupprimer = new JRadioButton("Supprimer");
boutonDesModules.add(boutonSupprimer);
groupeDeBoutons.add(boutonSupprimer);
}
}
|
Markdown | UTF-8 | 1,094 | 2.921875 | 3 | [] | no_license | # ReactAPILAyer
JavaScript API Layer
Fetching data from an API is not a React specific concept however; there Axios is a tool that helps
Axios is a PROMISE based HTTP client for making HTTP requests from a browser to any web server.
Features of Axios :
• Makes XMLHttpRequests from browser to web server
• Makes HTTP request from node.js also
• Supports the promise API
• Handles request and response
• Cancel requests
• Automatically transforms JSON data
Installation Using npm
$ npm install axios -- save
package on npm
https://npmjs.com/package/axios
homepage
https://github.com/axios/axios
Load Data From an API in React :
Whenever we have to load data into a React app, we should consider doing that in the componentDidMount lifecycle method.Why? Because you want to use setState to store the data inside your component’s state as soon as the response returns.
API Layer Structure in project :
Src :
APIUtils.js
APIConstants.js
HandleError.js
Usage : Import above files in component .js file and we can perform the API data operations.
|
Markdown | UTF-8 | 821 | 2.75 | 3 | [
"MIT"
] | permissive | # mshenfield.dev
This is the source code for my resume/vanity project/spot to plop random crap down [mshenfield.dev](https://mshenfield.dev).
This is a site that is just POHTML and POJS and POCSS. It shows in some spots, but it's refreshing to see how powerful
these foundational tools have become.
## Running
The easiest way to develop is to clone this repository and point your browser directly at the main page using a `file://`
path (`file:///path/to/mshenfield.dev/index.html`). Setting up a decent dev server that automatically invalidates
the browser's cache is still in the works.
## Testing
🏗️ <span style="color: red; backround-color: yellow;">UNDER CONSTRUCTION</span>
## License
[MIT](LICENSE). Feel free to copy pieces, just don't copy the whole thing and slap you're name on it pretty please.
|
Markdown | UTF-8 | 7,300 | 2.6875 | 3 | [] | no_license | # 가상환경 구축
* 가상환경을 구축하는 이유
* 여러 패키지를 사용하다 보면, 패키지의 버전차이, 또는 각종 이유로 충돌이 발생하게 된다. 따라서 최소한의 기능을 가진 깨끗한 공간이 필요하기에 가상환경을 구축한다.
* 가상환경을 구축하기 위해서는 우선 내 기준으로 설명하자면 다른 번잡스러운 것들을 없애기 위해서 바탕화면을 기준으로 시작한다
* python 터미널에서 python -m venv 폴더이름을 생성
* 폴더이름을 project라고 가정 후
* project 폴더로 이동 : cd project
* Scripts 폴더로 이동 : cd Scripts
* activate 명령어를 통해 가상환경 실행
* pip install django 를 통해 장고 설치
* 가상환경 구축 완료
# 장고를 시작해보자
* 프로젝트를 만들어보자 : django-admin startproject myproject(project 이름)
* 여기서 잠깐 - 서버를 실행시킬때에는 myproject 에서 실행시킨다.
* 앱을 생성하자 - 앱을 생성하기 전에 myproject로 이동 : cd myproject
* python manage.py startapp (앱 이름) 으로 앱 생성
* 자 여기까지는 쉽다.
* 이제 연결작업을 해보자


* settings.py 에서 INSTALLED_APPS 에서 내가 만든 앱을 확인시켜준다. 등록을 해준다. 연결을 해준다

* user폴더는 안보인다고 생각을 하고 html 파일 만들기 위해 templates 라는 폴더를 만들어주고 그 안에 html 파일을 생성한다.
* templates 폴더는 우선 앱 밑에 생성한다.

(이 사진 같은 경우에는 수업시간에 한 내용으로 템플릿을 연결해준것이다.)

* views 에다가 함수를 입력해준다. 리퀘스트를 요청을 하고 html 을 받아 화면에 출력시키는 것을 해준다.
* 함수를 만들고 출력시킬 준비가 끝났으니 이제 url 을 통해서 입력을 받았을 때 보여주는 연결을 해줄 것이다.

* path 를 추가해서 url을 띄어주는 것이고!!! 경로를 설정해주는 것이다.
* 정리를 해보자면 , 해당 url로 접근 시, views.py 에 있는 함수를 실행시키고, 그 함수가 html 파일을 화면에 보여주는 것이다.
## 간단하게 이미지 추가하는 법!!!

* 우선 project 밑에다가 static 이라는 폴더를 추가한 후에 위 사진 처럼 경로를 설정해준다.
* 또 하나 스펠링이라던가, 오타를 유심히 보자 이것 때문에 20분 정도 날렸다.

* 이미지를 추가했다면, 그 이미지를 html로 불러와야 한다.
```html
/* django 문법과 html 문법 */
{% load static %}
<img src="{% static '폴더경로/사진이름.확장자' %}"
```
## 앱을 여러 개 구동 시키기
* 이 부분은 우선 넘어가자
## 글자 수 세는 프로그램 만들어보기
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>글자 수 세는 프로그램</h1>
<a href="">ABOUT</a>
<form>
<textarea name="fulltext" cols="40" rows="10"></textarea>
<br>
<input type="submit" value="제출하기">
</form>
</body>
</html>
```
* 위 html에 대한 설명
* ABOUT 이라는 것에 링크를 걸어둔 것이고
* form 은 사용자로부터 텍스트를 입력 받는 것이다.
* input type 을 보면 submit 은 그 즉시 제출하는 것이기 때문에 따로 이름을 설정 안해준 것이고 제출하기를 누르면 바로 서버로 간다.
* 


* 맨 위에서부터 설명을 하자면 우선 urls에 경로 설정을 해준다. about 페이지와 result 페이지를 만들기 때문에 두 가지 경로 설정을 해준것이다.
* 경로를 설정했으니 경로에서 불러올 함수를 생성을 해주는 데 full 이라는 것은 fulltext라는 이름을 가진 것에서 get 가져온다. 그리고 return 값을 줄 때 딕셔너리 형태로 저장된 값을 리턴을 해주는 것을 볼 수 있다.
* html 파일을 보면 한 가지 특징이 있는데 {{}} 이것으로 감싸진 녀석들을 볼 수가 있다. 이는 템플릿 언어라고도 하며 장고에서 쓰이는 언어다.
* 템플릿 언어는 다음 장에서 알아보도록 하자.
## 템플릿 언어
* 장고에서 제공해주는 언어
* 변수 : {{변수}} , 와 같은 형태로 표현이 된다. 또한 .(콤마) 를 통해서 변수의 속성으로 접근 할 수도 있다.
* 필터 : | (파이프) 를 통해서 적용할 수 있는데, 대표적으로 {{변수 | length}}
* 태그 : {% tag %}
* 반복문
* {% for blog in blog_list %}
{{blog. title}}
{% endfor %}
* {% if blog_list %}
{{blot_list | length}}
{% else %}
* 상속과 블록 : {% extends base.html %} 베이스를 상속받는다. html 이 길어질 때 사용하면 굉장히 효율적이다.
* 블록 {% block %}, {% endblock %}
## model 과 admin
* model : 원하는 데이터 등록, class를 이용

* 블로그 class 정의 (클래스를 정의할때 첫 문자는 대문자)
* 모델의 필드를 받아온다.

* model을 데이터베이스와 연동한다.
* 연동하기 위해서는 명령어를 terminal 에서 등록시켜줘야한다
* python manage.py makemigrations
* python manage.py migrate
* admin 계정 생성하기
* python manage.py createsuperuser

* name 을 입력
* email 입력
* password 계속 빈칸으로 유지가 되니 유의하여 비밀번호 입력
* 생성 후 서버 구동 시키고 /admin 계정으로 이동
* admin page 에서 블로그를 작성하기 위해서는 admin.py 에 블로그를 등록시킨다.

* 블로그에서 글을 작성하게 되면 제목이 보이지 않고 object로 나오게 되는데 이를 제목으로 확인하기 위해서는

* str 함수를 이용해서 제목을 보이게 한다.
## 두 개의 앱을 연결하기
* 한 프로젝트 안에 다양한 앱을 설치할 경우가 있고, 또 거의 대부분은 하나의 앱으로 이루어지지 않는다.
* 그러한 방법으로는 각 앱을 연결할 수 있게 해주고 이 앱의 url 을 통해서 확인한다.

* 이처럼 우선 프로젝트 url 에 각 앱의 경로를 설정을 해주고 그 다음

* 각각의 앱의 url 에다가 html 창을 띄울 경로를 설정한다.

* 이런식으로!!! |
PHP | UTF-8 | 822 | 2.65625 | 3 | [] | no_license | <?php
// Mulai session
session_start();
// Load twig.php
require_once __DIR__.'/twig.php';
// Load konfigurasi database
include 'connection.php';
//ambil data dari database
$sql = "SELECT * FROM product";
$result = $conn->query($sql);
$data =null;
if ($result->num_rows > 0) {
foreach ($result as $index => $value) {
$data[$index] = $value;
$data[$index]['detail'] = [];
$qq = mysqli_query($conn,"SELECT * FROM product_detail where id_product=".$value['id']);
foreach ($qq as $i => $value) {
$data[$index]['detail'][$i] = $value;
}
}
}
session_unset();
session_destroy();
// Variabel judul halaman
$title = "Niagahoster | Web Hosting Indonesia Unlimited - Gratis Domain & SSL";
// Render template index.html
// Kirim variabel
echo $twig->render('/index.html', ['title' => $title, 'data' => $data]); |
Go | UTF-8 | 825 | 3.140625 | 3 | [] | no_license | package main
/* Stolen from https://github.com/bitly/go-notify/blob/master/notify.go */
import (
"sync"
)
var subscriber = &subscriptions{
count: 0,
clients: make(map[int]chan string),
}
type subscriptions struct {
count int
clients map[int]chan string
sync.RWMutex
}
type client struct {
id int
channel chan string
}
func Subscribe() client {
subscriber.Lock()
defer subscriber.Unlock()
subscriber.count += 1
ch := make(chan string)
subscriber.clients[subscriber.count] = ch
cl := client{subscriber.count, ch}
return cl
}
func (c *client) Leave() {
subscriber.Lock()
defer subscriber.Unlock()
delete(subscriber.clients, c.id)
close(c.channel)
}
func Publish(m string) {
subscriber.RLock()
defer subscriber.RUnlock()
for i := range subscriber.clients {
subscriber.clients[i] <- m
}
}
|
PHP | UTF-8 | 2,399 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | <?php declare(strict_types = 1);
namespace ForkNetwork\StrictPHPUnit\Tests\Framework;
use ForkNetwork\StrictPHPUnit\StrictTestTrait;
use ForkNetwork\StrictPHPUnit\Tests\Framework\Fixtures\GenericClass;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
class StrictTestCaseTest extends TestCase
{
use StrictTestTrait;
/**
* @var GenericClass
*/
private $genericClass;
/**
* Set up the SUT.
*/
protected function setUp(): void
{
$this->genericClass = new GenericClass();
}
/**
* Assert that expectations are handled as they are always done.
*/
public function testItShouldAcceptNormalExpectations(): void
{
$testCaseMock = $this->getMockBuilder(TestCase::class)
->getMock();
$testCaseMock
->expects($this->once())
->method('hasExpectationOnOutput')
->willReturn(true);
$result = $this->genericClass->callsOneMethod($testCaseMock);
$this->assertTrue($result);
}
/**
* Assert that an unexpected method call throws an exception instead of silently continuing.
*/
public function testItShouldFailOnUnexpectedMethodCalls(): void
{
$testCaseMock = $this->getMockBuilder(TestCase::class)
->getMock();
$this->expectException(ExpectationFailedException::class);
$this->genericClass->callsOneMethod($testCaseMock);
}
/**
* Assert that the now default disabled auto return value generation can be enabled again.
*/
public function testItShouldAcceptUnexpectedMethodCallsWhenExplicitlyConfigured(): void
{
$testCaseMock = $this->getMockBuilder(TestCase::class)
->enableAutoReturnValueGeneration()
->getMock();
$result = $this->genericClass->callsOneMethod($testCaseMock);
$this->assertFalse($result, 'The default generated return value is false.');
}
/**
* Assert that the createMock method also disallows unexpected method calls.
* (i.e. it is using the getMockBuilder method)
*/
public function testItShouldFailForCreateMockMethod(): void
{
$testCaseMock = $this->createMock(TestCase::class);
$this->expectException(ExpectationFailedException::class);
$this->genericClass->callsOneMethod($testCaseMock);
}
}
|
Java | UTF-8 | 1,797 | 2.640625 | 3 | [] | no_license | package com.demo.spring;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import org.apache.activemq.Message;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;
@Component
public class MyJmsListener {
/*
*
* It create a JMS Listener and consume every message from inbound.queue and
* post back the same message to outbound.queue
*
*/
@JmsListener(destination = "inbound.queue")
@SendTo("outbound.queue")
public String receiveMessage(final Message strMessage) throws JMSException {
String messageData = null;
System.out.println("Received message " + strMessage);
String response = null;
if (strMessage instanceof TextMessage) {
TextMessage textMessage = (TextMessage) strMessage;
messageData = textMessage.getText();
response = "Message: " + messageData;
}
return response;
}
/*
*
* It create a JMS Listener and consume every message from inbound.topic and
* post back the same message to outbound.topic
*/
@JmsListener(destination = "inbound.topic")
@SendTo("outbound.topic")
public String receiveMessageFromTopic(final Message strMessage) throws JMSException {
String messageData = null;
System.out.println("Received message " + strMessage);
String response = null;
if (strMessage instanceof TextMessage) {
TextMessage textMessage = (TextMessage) strMessage;
messageData = textMessage.getText();
response = "Message: " + messageData;
}
return response;
}
}
|
Markdown | UTF-8 | 2,144 | 3.578125 | 4 | [] | no_license | # Single Responsibility Principle
Single Responsibility Principle ,中文含义是 单一职责原则。
## 定义
There should never be more than one reason for a class to change.
## 单一职责原则的优点
* 类的复杂性降低
* 可读性提高
* 可维护性提高
* 变更引起的风险降低
注:单一职责原则提出了一个编写程序的标准,用“职责”或“变化原因”衡量接口或类设计得是否优良,但这些都是不可度量的,所以,我们需要因项目而异,因环境而异
# 单一职责原则同样适用于方法
即一个方法尽可能做一件事。
# 对于单一职责原因
接口一定要做到单一职责,类的设计尽量做到只有一个原因引起变化。
# 程序
````
class IPhone{
public:
void chat(object);
void dial(stringPhoneNumber);
void hangup();
};
````
电话类:注:dial:拨通电话;chat:通话;hangup:挂电话
这么一个接口包含两个职责:协议管理(dial,hangup)和数据传送(chat)
这样看来,协议接通会引起这个接口或类的变化,数据传送也会引起这个接口或类的变化。
两个原因都引起了类的变化。但是!!这两个职责并不互相影响。所以说:拆分!!!
````
class ConnectionManager{
public:
virtual void dial(string);
virtual void hangup();
};
class IConnectionManager : public ConnectionManager{
public:
void dial(string phoneNumber);
void hangup();
};
class DataTransfer{
public:
virtual void DataTransfer(IConnectionManager);
};
class IDataTransfer : public DataTransfer{
public:
void DataTransfer(IConnectionManager cm);
};
class Phone{
ConnectionManager con;
DataTransfer date;
};
````
这么做,我们就实现了单一职责。
但是这样会导致一个问题:该方式需要把ConnectionManager和DataTransfer组合在一起才能使用,组合是一种强耦合关系拥有共同生命期,而且增加了类的复杂性,多了两个类,不好不好。
修改后如下
````
class Phone : public IConnectionManager, public IDataTransfer{
};
````
|
C++ | UTF-8 | 5,998 | 3.25 | 3 | [] | no_license | // Base Module Code
// s - show, t - test, a - act, A - address, B - on selectout, C - off selectout
// mode 1- initial(ask is device there), 2 - send an address to set, 3 - send command to on (B)/off (C) select or request to act or test
// a (act), t (test) : 1-forward, 2- reverse, 3-right, 4- left, 5- stop (no test to stop), 6-LED ON, 7-LED OFF
#include <Wire.h>
/* Pin Definitions*/
#define LED 15
#define SELECT_IN A3
#define SELECT_OUT A2
#define MOTOR1_1 8
#define MOTOR1_2 9
#define MOTOR1_PWM 5
#define MOTOR2_1 10
#define MOTOR2_2 11
#define MOTOR2_PWM 6
int mode = 1; //initial mode
boolean ledshow=false;
byte type = '1';
byte address = 0;
volatile boolean needToStop = false;
void setup()
{
// set pins to input and output modes
pinMode(LED, OUTPUT);
pinMode(SELECT_IN, INPUT);
pinMode(SELECT_OUT, OUTPUT);
pinMode(MOTOR1_1,OUTPUT);
pinMode(MOTOR1_2,OUTPUT);
pinMode(MOTOR1_PWM,OUTPUT);
pinMode(MOTOR2_1,OUTPUT);
pinMode(MOTOR2_2,OUTPUT);
pinMode(MOTOR2_PWM,OUTPUT);
Serial.begin(9600);
//begin i2c communication with default address
Wire.begin(10);
Wire.onReceive(receiveEvent); // register events
Wire.onRequest(requestEvent);
//Serial.println("address 10");//TEST
//giving some time to set up
delay(5000);
//waite unttil the slave is selected
while (digitalRead(SELECT_IN) == HIGH) {
delay(10);
//Serial.println("address 10");//TEST
}
//when selected change the default address to another
Wire.begin(11);
Wire.onReceive(receiveEvent); // register events
Wire.onRequest(requestEvent);
//Serial.println("address 11");//TEST
}
void loop()
{
delay(10);
//handling show command - On LED for 3 seconds
if(ledshow == true){
digitalWrite(LED, HIGH);
delay(3000);
digitalWrite(LED, LOW);
ledshow = false;
}
//handling stops after activating motors
if(needToStop){
delay(500);
stopMotors();
needToStop = false;
}
//Serial.println(address);//TEST
}
// function that executes whenever data is received from master
void receiveEvent(int howMany)
{
//types of messages - s - show, B- On selectout, C- Off selectout, t1 - test 1, a1 - act 1
char command;
int id;
int add;
//Address assigning
if(mode == 2){
add = Wire.read ();
address = add;
Wire.begin(add); // set new address
Wire.onReceive(receiveEvent); // register events
Wire.onRequest(requestEvent);
Serial.println(address);
mode = 3;
}
//listening mode
else if(mode == 3){
command = Wire.read ();
if(command == 'B'){
digitalWrite(SELECT_OUT, HIGH); //On selectout
}
else if(command == 'C'){
digitalWrite(SELECT_OUT, LOW); //Off selectout
}
//if got one byte
else if (howMany == 1){
if(command == 's'){ // show LED
show();
}
}
//if got two bytes
else if (howMany == 2){
//real time capability demonstration
if(command == 't'){ // test
id= Wire.read ();
test(id);
}
//actions in programs
else if(command == 'a'){ // act
id= Wire.read ();
act(id);
}
}
}
// throw away any garbage
while (Wire.available () > 0) {
Wire.read ();
}
}
// function that executes whenever data is requested by master
void requestEvent()
{
//Serial.println("write");//TEST
switch (mode) {
case 1:
Wire.write(type); //send type
mode = 2; //will receive an address soon
break;
case 2:
break;
case 3: //send whether ready to receive another message
if(needToStop){
Wire.write(0);
}
else{
Wire.write(1);
}
break;
default:
break;
}
}
// show device
void show(){
ledshow = true;
}
// actions
void act(int id){
switch (id) {
case '1': forward();
break;
case '2': reverse();
break;
case '3': turnRight();
needToStop = true;
break;
case '4': turnLeft();
needToStop = true;
break;
case '5': stopMotors();
break;
case '6':
digitalWrite(LED, HIGH);
break;
case '7':
digitalWrite(LED, LOW);
break;
default:
break;
}
}
// tests
void test(int id){
switch (id) {
case '1': forward();
needToStop = true;
break;
case '2': reverse();
needToStop = true;
break;
case '3': turnRight();
needToStop = true;
break;
case '4': turnLeft();
needToStop = true;
break;
case '5': stopMotors();
break;
case '6':
show();
break;
default:
break;
}
}
// run the base forward
void forward(){
digitalWrite(MOTOR1_PWM, HIGH);
digitalWrite(MOTOR1_1, HIGH);
digitalWrite(MOTOR1_2, LOW);
digitalWrite(MOTOR2_PWM, HIGH);
digitalWrite(MOTOR2_1, HIGH);
digitalWrite(MOTOR2_2, LOW);
}
// run the base reverse
void reverse(){
digitalWrite(MOTOR1_PWM, HIGH);
digitalWrite(MOTOR1_1, LOW);
digitalWrite(MOTOR1_2, HIGH);
digitalWrite(MOTOR2_PWM, HIGH);
digitalWrite(MOTOR2_1, LOW);
digitalWrite(MOTOR2_2, HIGH);
}
// turn right the base
void turnRight(){
digitalWrite(MOTOR1_PWM, HIGH);
digitalWrite(MOTOR1_1, HIGH);
digitalWrite(MOTOR1_2, LOW);
digitalWrite(MOTOR2_PWM, HIGH);
digitalWrite(MOTOR2_1, LOW);
digitalWrite(MOTOR2_2, HIGH);
}
// turn left the base
void turnLeft(){
digitalWrite(MOTOR1_PWM, HIGH);
digitalWrite(MOTOR1_1, LOW);
digitalWrite(MOTOR1_2, HIGH);
digitalWrite(MOTOR2_PWM, HIGH);
digitalWrite(MOTOR2_1, HIGH);
digitalWrite(MOTOR2_2, LOW);
}
//fast stop
void stopMotors(){
digitalWrite(MOTOR1_PWM, HIGH);
digitalWrite(MOTOR1_1, HIGH);
digitalWrite(MOTOR1_2, HIGH);
digitalWrite(MOTOR2_PWM, HIGH);
digitalWrite(MOTOR2_1, HIGH);
digitalWrite(MOTOR2_2, HIGH);
}
|
Java | UTF-8 | 2,489 | 2.140625 | 2 | [] | no_license | package com.zhongjian.shedule;
import java.net.URISyntaxException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import com.zhongjian.commoncomponent.TaskBase;
import com.zhongjian.localservice.OrderService;
@Component
public class OrderShedule extends TaskBase implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private OrderService orderService;
void orderShedule() {
// 定时执行任务,每隔5分钟钟执行一次
executeShedule(new Runnable() {
@Override
public void run() {
orderService.todoSth();
}
}, 0, 300);
}
void withdraw() {
// 定时执行任务,每天执行一次
executeShedule(new Runnable() {
@Override
public void run() {
try {
orderService.withdraw();
} catch (URISyntaxException e) {
}
}
}, 0, 14 * 60);
}
//延时处理订单
public void delayHandleCVOrder(Integer orderId,Integer time) {
if (orderService.getDelieverModel(orderId) == 2) {
orderService.lockDistributeOrder(orderId);
return;
}
// 延时60s把订单改为平台处理
executeDelayShedule(new Runnable() {
@Override
public void run() {
orderService.changeAndDistributeOrder(orderId);
}
}, time);
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
this.orderShedule();
this.withdraw();
}
//检查订单是否有金额错误
public void checkCVOrder(Integer orderId) {
// 延时60s把订单改为平台处理
executeDelayShedule(new Runnable() {
@Override
public void run() {
orderService.checkCVOrder(orderId);
}
}, 5);
}
//延时处理造假订单
public void delayCreateOrder(Integer marketid, Integer uid, Integer addressid) {
// 延时60s把订单改为平台处理
executeDelayShedule(new Runnable() {
@Override
public void run() {
orderService.createFalseRorder(marketid, uid, addressid);
}
}, 24 * 60 * 60);
}
//延时处理造假订单
public void delayFinishOrder(Integer roid ,String login_token) {
// 延时60s把订单改为平台处理
executeDelayShedule(new Runnable() {
@Override
public void run() {
orderService.finishRorder(roid, login_token);
}
}, 48 * 60);
}
}
|
Java | UTF-8 | 26,274 | 1.585938 | 2 | [] | no_license | package com.oxigenoxide.balls;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.oxigenoxide.balls.objects.SoundRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Main extends ApplicationAdapter {
static SpriteBatch batch;
static Game game;
static Scene menu;
static Scene welcome;
static Scene splash;
static GameOver gameOver;
static Scene currentScene;
static Scene overlayScene;
public static Scene nextScene;
public static Box2DDebugRenderer b2dr;
public static OrthographicCamera cam;
public static ShapeRenderer sr;
public static float width, height;
public static Vector2[] tap;
public static Vector2[] tap_previous;
public static Vector2[] tap_delta;
public static Vector2[] tap_begin;
public static Vector2 pos_middle;
public static float[] tap_distance;
public static float tap_speed;
public static float tap_angle;
public static float[] speedDistanceLastFrames;
public static float[] speedTimeLastFrames;
public static float[] directionLastFrames;
public static final int TAPSPEEDPRECISION = 10;
public static final int TAPANGLEPRECISION = 5;
public static Vector2 pos_cam;
public static ArrayList<SoundRequest> soundRequests;
public static SoundRequest[] soundRequestsToPlay;
public static float dt_one;
public static float dt;
public static final float PIXELSPERMETER = 40;
//public static final float PIXELSPERMETER = 1;
public static final float METERSPERPIXEL = 1 / PIXELSPERMETER;
public static float pointsPerPixel;
public static float pixelsPerPoint;
static Music currentMusic;
static Music lastMusic;
public static AssetManager assets;
public static FirebaseInterface fbm;
public static GameInterface gm;
public static AdMobInterface amm;
public static boolean resourcesLoaded;
public static boolean signedIn;
static boolean inGame;
public static int testerID = 0;
public static Shop shop;
static boolean isLoaded;
public static final int adHeight = 17;
public static boolean noAds = false; // DONE
public static boolean noFX = false; // DONE
public static boolean noMusic = false; // DONE
public static boolean noCollection = false; // DONE
public static boolean noLevels = false; // DONE
public static boolean noFlow = false; // DONE
public static boolean noScore = false; // DONE
public static boolean doFade;
public static boolean inScreenShotMode;
public static float shakeAng;
public static float fadeDir;
static float fade;
public static Res res;
static float shakeIntensity;
public static UserData userData;
public static GameData gameData;
long startTime;
public static final int SOUNDCAP = 2;
public static final boolean RESEARCHMODE = true;
public static final boolean DOSCREENSHOTMODE = false;
/*
Every time you release check this:
- DEBUGTOOLS in Game should be false
- RESEARCHMODE should be false
- DOSCREENSHOTMODE should be false
*/
// GET RELEASE KEY: keytool -list -v -keystore C:\Keys\googlekeys.jks -alias key_ball (Release key is pretty useless)
public Main(FirebaseInterface fbm, AdMobInterface amm, GameInterface gm) {
super();
resetStatics();
this.fbm = fbm;
this.amm = amm;
this.gm = gm;
}
void resetStatics() {
isLoaded = false;
resourcesLoaded = false;
userData = null;
signedIn = false;
}
long rank;
@Override
public void create() {
fbm.signIn();
assets = new AssetManager();
width = 108;
height = Gdx.graphics.getHeight() / (float) Gdx.graphics.getWidth() * 108;
pos_middle = new Vector2(width / 2, height / 2);
soundRequests = new ArrayList<SoundRequest>();
soundRequestsToPlay = new SoundRequest[SOUNDCAP];
pointsPerPixel = Gdx.graphics.getWidth() / width;
pixelsPerPoint = 1 / pointsPerPixel;
batch = new SpriteBatch();
cam = new OrthographicCamera(width, height);
cam.position.set(width / 2, height / 2, 0);
b2dr = new Box2DDebugRenderer();
sr = new ShapeRenderer();
sr.setAutoShapeType(true);
//game = new Game();
menu = new Menu();
splash = new Splash();
tap = new Vector2[]{new Vector2(), new Vector2()};
tap_previous = new Vector2[]{new Vector2(), new Vector2()};
tap_delta = new Vector2[]{new Vector2(), new Vector2()};
tap_begin = new Vector2[]{new Vector2(), new Vector2()};
tap_distance = new float[2];
pos_cam = new Vector2();
pos_cam.set(width / 2, height / 2);
speedDistanceLastFrames = new float[TAPSPEEDPRECISION];
speedTimeLastFrames = new float[TAPSPEEDPRECISION];
directionLastFrames = new float[TAPANGLEPRECISION];
ShaderProgram.pedantic = false;
setScene(splash);
DataManager.getInstance().initializeGameData();
gameData = DataManager.getInstance().gameData;
startTime = System.currentTimeMillis();
testerID = gameData.testerID;
rank = gm.getRank();
}
public static void setScreenShotMode() {
game.setDoWiggle(false);
inScreenShotMode = true;
}
public void update() {
dt = Gdx.graphics.getDeltaTime();
dt_one = dt * 60;
for (int i = 0; i < tap.length; i++) {
tap[i].set(((Gdx.input.getX(i) / 4f) * (width / (Gdx.graphics.getWidth() / 4f))),
((-(Gdx.input.getY(i) / 4f - Gdx.graphics.getHeight() / 4f) * (height / (Gdx.graphics.getHeight() / 4f)))));
tap_delta[i].set(tap[i].x - tap_previous[i].x, tap[i].y - tap_previous[i].y);
tap_distance[i] = getHypothenuse(tap_delta[i].x, tap_delta[i].y);
}
tap_angle = angleBetweenPoints(tap_previous[0], tap[0]);
if(Gdx.input.justTouched())
for (int i = 0; i < tap.length; i++)
tap_begin[i].set(tap[i]);
for (int i = 0; i < tap.length; i++) {
tap_previous[i].set(tap[i]);
}
for (int i = 0; i < TAPSPEEDPRECISION - 1; i++) {
speedDistanceLastFrames[i] = speedDistanceLastFrames[i + 1];
speedTimeLastFrames[i] = speedTimeLastFrames[i + 1];
}
for (int i = 0; i < TAPANGLEPRECISION - 1; i++) {
directionLastFrames[i] = directionLastFrames[i + 1];
}
speedDistanceLastFrames[TAPSPEEDPRECISION - 1] = tap_distance[0];
speedTimeLastFrames[TAPSPEEDPRECISION - 1] = dt_one;
directionLastFrames[TAPANGLEPRECISION - 1] = tap_delta[0].angleRad();
tap_speed = getSum(speedDistanceLastFrames) / getSum(speedTimeLastFrames);
currentScene.update();
if (overlayScene != null)
overlayScene.update();
if (!signedIn && fbm.isSignedIn() && fbm.isSnapshotLoaded()) {
signedIn = true;
onSignIn();
}
if (signedIn && !fbm.isSignedIn()) {
signedIn = false;
}
shakeIntensity = Math.max(0, shakeIntensity - .1f);
if (doFade) {
fade += fadeDir * .03f;
//fade += fadeDir * .0005f;
if (fade >= 2.2f) {
fadeDir = -1;
onFadePeak();
}
if (fade <= 0)
doFade = false;
}
int index = 0;
for (SoundRequest sr : soundRequests) {
soundRequestsToPlay[index] = sr;
index++;
if (index >= SOUNDCAP)
break;
}
if (soundRequests.size() > SOUNDCAP) {
for (SoundRequest sr : soundRequests) {
if (soundRequestsToPlay[0] != null && sr.priority > soundRequestsToPlay[0].priority) {
soundRequestsToPlay[1] = soundRequestsToPlay[0];
soundRequestsToPlay[0] = sr;
} else if (soundRequestsToPlay[1] != null && sr.priority > soundRequestsToPlay[1].priority)
soundRequestsToPlay[1] = sr;
}
}
for (SoundRequest sr : soundRequestsToPlay) {
if (sr != null)
playSound(sr.soundID, sr.volume);
}
for (int i = 0; i < SOUNDCAP; i++) {
soundRequestsToPlay[i] = null;
}
soundRequests.clear();
// Music
if (currentMusic != null)
currentMusic.setVolume(Math.min(1, currentMusic.getVolume() + .01f));
if (lastMusic != null) {
lastMusic.setVolume(Math.max(0, lastMusic.getVolume() - .01f));
if (lastMusic.getVolume() == 0) {
lastMusic.stop();
lastMusic = null;
}
}
}
public static void addSoundRequest(int soundID, int priority, float volume, float pitch) {
if (!noFX)
soundRequests.add(new SoundRequest(soundID, priority, volume, pitch));
}
public static void addSoundRequest(int soundID, int priority) {
if (!noFX)
soundRequests.add(new SoundRequest(soundID, priority));
}
public static void addSoundRequest(int soundID) {
if (!noFX)
soundRequests.add(new SoundRequest(soundID));
}
public static void setMusic(Music music) {
if (!Main.noMusic) {
if (lastMusic != null)
lastMusic.stop();
lastMusic = currentMusic;
currentMusic = music;
currentMusic.setVolume(0);
currentMusic.setLooping(true);
currentMusic.play();
}
}
public static void setNoMusic() {
if (!Main.noMusic) {
if (lastMusic != null)
lastMusic.stop();
lastMusic = currentMusic;
currentMusic = null;
}
}
public static void shake() {
if (!noFX && !inScreenShotMode)
if (shakeIntensity < 3)
shakeIntensity = 3;
}
public static void shake(float impact) {
if (!noFX && !inScreenShotMode)
if (impact > shakeIntensity && impact > 2)
shakeIntensity = impact;
}
public static void shakeSmall() {
if (!noFX)
if (shakeIntensity < 2)
shakeIntensity = 2;
}
public static void setShakeAng(float ang) {
//shakeAng=(float)Math.PI*.5f;
//shakeAng=(float)Math.PI*.5f;
//shakeAng=(float)Math.toDegrees(ang);
shakeAng = ang;
}
@Override
public void render() {
update();
//cam.position.set(pos_cam.x + (int) (shakeIntensity * Math.sin(shakeIntensity)),pos_cam.y + (int) (shakeIntensity * Math.sin(shakeIntensity)),0);
//cam.update();
//batch.setProjectionMatrix(cam.combined);
//sr.setProjectionMatrix(cam.combined);
setCamEffects();
currentScene.render(batch, sr);
if (overlayScene != null)
overlayScene.render(batch, sr);
setNoCamEffects();
if (resourcesLoaded) {
batch.begin();
if (!inScreenShotMode)
res.sprite_watermark.draw(batch);
if (fade > 0) {
batch.setShader(Res.shader_fade);
Res.shader_fade.setUniformf("fade", (float) Math.min(fade, 2f));
Res.shader_fade.setUniformf("screenSize", width, height);
Res.shader_fade.setUniformf("dir", fadeDir);
batch.draw(Res.tex_fade, 0, 0);
batch.setShader(null);
}
batch.end();
}
}
public static void setCamEffects() {
//setCamZoom();
setCamShake();
}
public static void setNoCamEffects() {
setCamNoZoom();
setCamNormal();
}
public static void setCamZoom() {
cam.zoom = .5f;
}
public static void setCamNoZoom() {
cam.zoom = 1;
}
public static void setCamShake() {
cam.position.set(pos_cam.x + (int) (Math.cos(shakeAng) * shakeIntensity * Math.sin(shakeIntensity * 10)), pos_cam.y + (int) (Math.sin(shakeAng) * shakeIntensity * Math.sin(shakeIntensity * 10)), 0);
cam.update();
batch.setProjectionMatrix(cam.combined);
sr.setProjectionMatrix(cam.combined);
}
public static void setCamNormal() {
cam.position.set(pos_cam.x, pos_cam.y, 0);
cam.update();
batch.setProjectionMatrix(cam.combined);
sr.setProjectionMatrix(cam.combined);
}
public static int drawNumberSign(SpriteBatch batch, int number, Vector2 pos, int font, Texture tex_sign, int yDisposition) {
int digitAmount = 0;
ArrayList<Integer> digits = new ArrayList<Integer>();
int power = 0;
while (number >= Math.pow(10, power)) {
digitAmount++;
power++;
}
if (number == 0) {
digitAmount = 1;
}
int crunchNumber = number;
for (int i = digitAmount - 1; i >= 0; i--) {
digits.add((int) (crunchNumber / Math.pow(10, i)));
crunchNumber %= Math.pow(10, i);
}
int width = 0;
for (int i : digits) {
width += Res.tex_numbers[font][i].getWidth() + 1;
}
width += tex_sign.getWidth() + 2;
int textWidth = width;
width--;
int iWidth = 0;
batch.draw(tex_sign, pos.x - width / 2 + iWidth, pos.y + yDisposition);
iWidth += tex_sign.getWidth() + 2;
for (int i : digits) {
batch.draw(Res.tex_numbers[font][i], pos.x - width / 2 + iWidth, pos.y);
iWidth += Res.tex_numbers[font][i].getWidth() + 1;
}
return textWidth;
}
public static ArrayList<Integer> getDigits(int number) {
int digitAmount = 0;
ArrayList<Integer> digits = new ArrayList<Integer>();
int power = 0;
while (number >= Math.pow(10, power)) {
digitAmount++;
power++;
}
if (number == 0) {
digitAmount = 1;
}
int crunchNumber = number;
for (int i = digitAmount - 1; i >= 0; i--) {
digits.add((int) (crunchNumber / Math.pow(10, i)));
crunchNumber %= Math.pow(10, i);
}
return digits;
}
public static int getTextWidth(ArrayList<Integer> digits, int font) {
int width = 0;
for (int i : digits) {
width += Res.tex_numbers[font][i].getWidth() + 1;
}
width--;
return width;
}
public static void drawNumberSign(SpriteBatch batch, ArrayList<Integer> digits, Vector2 pos, int font, Texture tex_sign, int yDisposition) {
int iWidth = 0;
batch.draw(tex_sign, pos.x + iWidth, pos.y + yDisposition);
iWidth += tex_sign.getWidth() + 2;
for (int i : digits) {
batch.draw(Res.tex_numbers[font][i], pos.x + iWidth, pos.y);
iWidth += Res.tex_numbers[font][i].getWidth() + 1;
}
}
public static void drawNumber(SpriteBatch batch, ArrayList<Integer> digits, Vector2 pos, int font) {
int iWidth = 0;
for (int i : digits) {
batch.draw(Res.tex_numbers[font][i], pos.x + iWidth, pos.y);
iWidth += Res.tex_numbers[font][i].getWidth() + 1;
}
}
public static void drawNumber(SpriteBatch batch, int number, Vector2 pos, int font) {
int digitAmount = 0;
ArrayList<Integer> digits = new ArrayList<Integer>();
int power = 0;
while (number >= Math.pow(10, power)) {
digitAmount++;
power++;
}
if (number == 0) {
digitAmount = 1;
}
int crunchNumber = number;
for (int i = digitAmount - 1; i >= 0; i--) {
digits.add((int) (crunchNumber / Math.pow(10, i)));
crunchNumber %= Math.pow(10, i);
}
int width = 0;
for (int i : digits) {
width += Res.tex_numbers[font][i].getWidth() + 1;
}
width--;
int iWidth = 0;
for (int i : digits) {
batch.draw(Res.tex_numbers[font][i], pos.x - width / 2 + iWidth, pos.y);
iWidth += Res.tex_numbers[font][i].getWidth() + 1;
}
}
@Override
public void dispose() {
batch.dispose();
if (isLoaded) {
game.dispose();
menu.dispose();
shop.dispose();
splash.dispose();
welcome.dispose();
assets.dispose();
DataManager.getInstance().saveData();
}
}
public void onPause() {
if (signedIn) {
System.out.println("ONPAUSE");
userData.timePlayed += (System.currentTimeMillis() - startTime) / 1000;
startTime = System.currentTimeMillis();
userData.adsClicked += amm.getAdsClicked();
userData.orbs = Main.gameData.orbs;
Main.gameData.userData = userData;
Shop.saveData();
userData.ballsUnlocked.clear();
userData.highscore = gameData.highscore;
for (boolean b : Main.gameData.unlocks) {
userData.ballsUnlocked.add(b);
}
System.out.println("SAVE-REPORT: userData.timePlayed: " + userData.timePlayed);
fbm.setUserData(userData);
fbm.leave();
DataManager.getInstance().saveData();
}
}
public void onResume() {
System.out.println("ONRESUME");
startTime = System.currentTimeMillis();
}
public static void reset(){
game.clear();
game.unpause();
game=new Game();
game.replay();
setNoMusic();
}
@Override
public void pause() {
super.pause();
}
static void onSignIn() {
fbm.getUID();
fbm.onSignIn();
testerID = fbm.getTesterID();
if (RESEARCHMODE)
setVersion(testerID);
gameData.testerID = testerID;
userData = fbm.getUserData();
if (userData == null)
userData = new UserData();
Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);
boolean isNewDate = true;
for (String s : userData.daysPlayed) {
if (s.equals(formattedDate)) {
isNewDate = false;
break;
}
}
if (isNewDate)
userData.daysPlayed.add(formattedDate);
}
public static void onLoaded() {
isLoaded = true;
game = new Game();
if (DOSCREENSHOTMODE)
setScreenShotMode();
menu = new Menu();
welcome = new Welcome();
shop = new Shop();
}
public static void setVersion(int id) {
noAds = false;
noFlow = false;
noFX = false;
noScore = false;
noMusic = false;
noLevels = false;
noCollection = false;
int version = id % 10;
switch (version) {
case 0:
noAds = true;
break;
case 1:
noFlow = true;
break;
case 2:
noFX = true;
break;
case 3:
noScore = true;
break;
case 4:
noMusic = true;
break;
case 5:
noLevels = true;
break;
case 6:
noCollection = true;
break;
default:
}
}
public static void startFade(Scene nextScene) {
System.out.println("Start FADE");
if (!doFade) {
System.out.println("Start FADE success");
Main.nextScene = nextScene;
startFade();
}
}
public static void startFade() {
if (!doFade) {
doFade = true;
fadeDir = 1;
}
}
public static void onFadePeak() {
if (nextScene != null) {
setScene(nextScene);
System.out.println("SETSCENE: " + nextScene.getClass());
nextScene = null;
return;
}
Game.onFadePeak();
}
public static void setPalette(Color[] colors) {
Res.shader_palette.setUniformf("color0", colors[0]);
Res.shader_palette.setUniformf("color1", colors[1]);
Res.shader_palette.setUniformf("color2", colors[2]);
Res.shader_palette.setUniformf("color3", colors[3]);
}
public static void setOverlayGameOver() {
overlayScene = gameOver;
}
public static void setOverlayNull() {
overlayScene = null;
}
public static void setSceneGame() {
//gameOver = new GameOver();
startFade(game);
inGame = true;
}
public static void setSceneMenu() {
startFade(menu);
}
public static void setSceneMenuNow() {
setScene(menu);
}
public static void setSceneWelcome() {
startFade(welcome);
}
public static void setSceneShop() {
startFade(shop);
}
static void setScene(Scene scene) {
if (currentScene != null)
currentScene.hide();
scene.show();
currentScene = scene;
}
public static void setAdVisibility(boolean visibility) {
if (!noAds) {
if (visibility) {
amm.show();
} else
amm.hide();
}
}
public static void initializeResources() {
res = new Res();
resourcesLoaded = true;
res.sprite_watermark.setPosition(width - res.sprite_watermark.getWidth() - 2, 2);
}
static void playSound(int soundID, float volume) {
switch (soundID) {
case ID.Sound.PLOP:
playPlopSound();
break;
case ID.Sound.GLASS:
playGlassBreakSound();
break;
case ID.Sound.SLOWDOWN:
playSlowDownSound();
break;
case ID.Sound.SPEEDUP:
playSpeedUpSound();
break;
case ID.Sound.HIT:
Res.sound_ballHit.play(volume, (float) Math.random() * .2f + .9f, 0);
break;
}
}
public static void playPlopSound() {
Res.sound_plop.play(1, (float) Math.random() * .4f + .8f, 0);
}
public static void playGlassBreakSound() {
Res.sound_glassBreak.play(1, (float) Math.random() * .4f + .9f, 0);
}
public static void playSlowDownSound() {
Res.sound_slowdown.play(1, 1, 0);
}
public static void playSpeedUpSound() {
Res.sound_speedup.play(1, 1, 0);
}
public static float getHypothenuse(float x, float y) {
return (float) Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
public static float distanceBetweenPoints(Vector2 v0, Vector2 v1) {
return (float) Math.sqrt(Math.pow(v0.x - v1.x, 2) + Math.pow(v0.y - v1.y, 2));
}
public static float getSum(float[] floats) {
float sum = 0;
for (float f : floats) {
sum += f;
}
return sum;
}
public static float angleBetweenPoints(Vector2 v0, Vector2 v1) {
return correctAtan2Output((float) Math.atan2(v1.y - v0.y, v1.x - v0.x));
}
public static float correctAtan2Output(float atan2Output) {
if (atan2Output >= 0) {
return atan2Output;
} else {
return (float) (Math.PI - Math.abs(atan2Output) + Math.PI);
}
}
public static boolean pointInRectangle(float x, float y, float bx, float by, float bw, float bh) {
return (x > bx && x < bx + bw && y > by && y < by + bh);
}
public static float interpolateAngle(float from, float to, float amount) {
float shortest_angle = (float) (((((to - from) % (Math.PI * 2)) + (Math.PI * 1.5f)) % (Math.PI * 2)) - (Math.PI));
return (float) (from + (shortest_angle * amount) % (Math.PI * 2));
}
/*
public static Vector2 intersectCircleLine(float m, float c, float r, float x, float y) {
float a_ = (float) (Math.pow(m, 2) + 1);
float b_ = 2 * (m * c - m * y - x);
float c_ = (float) (Math.pow(y, 2) - Math.pow(r, 2) + Math.pow(x, 2) - 2 * c * y + Math.pow(c, 2));
float D = (float) (Math.pow(b_, 2) - 4 * a_ * c_);
float x_ = (-b_ - (float) Math.sqrt(D)) / (2 * a_);
return new Vector2(x_, m * x_ + c);
}
*/
public static boolean intersectCircleLine(float xBegin, float yBegin, float xEnd, float yEnd, float x, float y, float r) {
Vector2 d = new Vector2(xEnd - xBegin, yEnd - yBegin);
Vector2 f = new Vector2(xBegin - x, yBegin - y);
float a = d.dot(d);
float b = 2 * f.dot(d);
float c = f.dot(f) - r * r;
float discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return false;
} else {
discriminant = (float) Math.sqrt(discriminant);
float t1 = (-b - discriminant) / (2 * a);
float t2 = (-b + discriminant) / (2 * a);
if (t1 >= 0 && t1 <= 1) {
return true;
}
if (t2 >= 0 && t2 <= 1) {
return true;
}
return false;
}
}
public Main setDevMode() {
noMusic = true;
return this;
}
}
|
Markdown | UTF-8 | 1,841 | 2.703125 | 3 | [] | no_license | ## Angular material datepicker

This small component is still in production it's a simple date picker based on the angular-material port of polymer by the people behind ionic
https://material.angularjs.org/
##Install
This component is bower and npm registered
```css
bower install material-date-picker
npm install material-date-picker
```
All the necessary files will be automatically included in your index.html if not add
```css
<link rel="stylesheet" href="bower_components/material-date-picker/build/styles/mbdatepicker.css/>
<script src="bower_components/material-date-picker/build/mbdatepicker.js"></script>
```
##Usage
###Attributes
```html
<mb-datepicker element-id='date1'
date-message=""
text-color="#EFEF23"
line-color="#DDFE66"
line-thickness="3"
date="date"
date-format="YYYY-MM-DD"></mb-datepicker>
```
With the following attributes you can adjust the text color or border color of the input without lifting a css finger
However if you want to adjust the datepicker inner-colors, as for now you have to override those in css.
An example is provided.
##Known issues
If you can't find the SVG images, look in the images map of the bower component and copy these to your own images map. I left this as an open option.
The datepicker is known to throw a JQuery light error because of the way the styles are applied to generate enabled or disabled dates.
It does not lag the performance, I find it to be ugly, it will be the next thing on my list to fix.
##Notes
The datepicker has changed enormously since the last commit, thinking no one used it I did not update the documents so here's an update
If you have an improvement or request please let me know or post a pull request
|
Go | UTF-8 | 2,781 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | package rabbitmq
import (
"net"
"time"
"github.com/jpillora/backoff"
"github.com/julienbreux/rabdis/pkg/logger"
"github.com/julienbreux/rabdis/pkg/rabbitmq/consumer"
"github.com/julienbreux/rabdis/pkg/rabbitmq/message"
"github.com/julienbreux/rabdis/pkg/url"
"github.com/streadway/amqp"
)
// RabbitMQ represents the RabbitMQ interface
type RabbitMQ interface {
Connect()
Disconnect() error
OnMessage(message.OnMessageHandler, ...consumer.Option)
}
// rabbitmq represents the internal rabbitmq structure
type rabbitmq struct {
o *Options
conn *amqp.Connection
consumers []consumer.Consumer
}
// New creates a new RabbitMQ instance
func New(opts ...Option) (RabbitMQ, error) {
o, err := newOptions(opts...)
if err != nil {
return nil, err
}
return &rabbitmq{
o: o,
}, nil
}
// Connect connects to the RabbitMQ server
func (r *rabbitmq) Connect() {
r.connect()
}
func (r *rabbitmq) connect() {
r.o.Logger.Info("rabbitmq: connecting")
b := &backoff.Backoff{}
attempts := 1
for {
var err error
url := url.Build("amqp", r.o.Username, r.o.Password, r.o.Host, r.o.Port, &r.o.VirtualHost)
conn, err := amqp.DialConfig(url, r.config())
if err == nil {
r.conn = conn
r.o.Logger.Info("rabbitmq: connected")
for _, c := range r.consumers {
_ = c.Start(r.conn)
}
break
}
r.o.Logger.Error(
"rabbitmq: failed to connect",
logger.F("attempts", attempts),
logger.E(err),
)
attempts++
time.Sleep(b.Duration())
}
r.watchConnectCloseAndReconnect()
}
func (r *rabbitmq) watchConnectCloseAndReconnect() {
go func() {
reason, ok := <-r.conn.NotifyClose(make(chan *amqp.Error))
r.conn = nil
if !ok {
r.o.Logger.Debug("rabbitmq: connection close properly")
return
}
r.o.Logger.Warn(
"rabbitmq: disconnected",
logger.F("reason", reason),
)
r.connect()
}()
}
// config returns RabbitMQ configuration
func (r *rabbitmq) config() amqp.Config {
connTimeout := time.Duration(r.o.ConnTimeout) * time.Second
return amqp.Config{
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, connTimeout)
},
Properties: amqp.Table{
"product": r.o.InstName,
"version": r.o.InstVersion,
},
}
}
// Disconnect disconnects from RabbitMQ
func (r *rabbitmq) Disconnect() error {
if r.conn == nil {
return nil
}
r.o.Logger.Info("rabbitmq: disconnecting")
err := r.conn.Close()
if err == nil {
r.o.Logger.Info("rabbitmq: disconnected")
return nil
}
r.o.Logger.Warn(
"rabbitmq: unable to stop",
logger.E(err),
)
return err
}
// OnMessage stores the on message receive handlers
func (r *rabbitmq) OnMessage(h message.OnMessageHandler, opts ...consumer.Option) {
c := consumer.New(h, opts...)
r.consumers = append(r.consumers, c)
}
|
Java | UTF-8 | 1,605 | 2.46875 | 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 dominiobroker;
import java.util.ArrayList;
/**
*
* @author javie
*/
public class Curso {
private ArrayList<Maestro>maestros;
private ArrayList<Alumno>alumnos;
private String fullName;
private String shortName;
private int id;
public Curso(ArrayList<Maestro> maestros, String fullName, String shortName, int id) {
this.maestros = maestros;
this.fullName = fullName;
this.shortName = shortName;
this.id = id;
}
public int getId() {
return id;
}
@Override
public String toString() {
return "Curso{" + "id=" + id + '}';
}
public void setId(int id) {
this.id = id;
}
public ArrayList<Maestro> getMaestros() {
return maestros;
}
public void setMaestros(ArrayList<Maestro> maestros) {
this.maestros = maestros;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public ArrayList<Alumno> getAlumnos() {
return alumnos;
}
public void setAlumnos(ArrayList<Alumno> alumnos) {
this.alumnos = alumnos;
}
}
|
C++ | UTF-8 | 662 | 2.96875 | 3 | [] | no_license | #include "student_data.h"
student_data::student_data(QString& in_student_id,QString& in_name,QString& in_sex,QString& in_nation,QString& in_department,QString& in_native_place)
{
this->student_id = in_student_id;
this->name = in_name;
this->sex = in_sex;
this->nation = in_nation;
this->department = in_department;
this->native_place = in_native_place;
}
QString student_data::return_data()
{
//用“|”分隔学生信息,后续可以直接切开以此保存
QString data = QString("%1|%2|%3|%4|%5|%6").arg(student_id).arg(name).arg(sex).arg(nation).arg(department).arg(native_place);
return data;
}
|
C++ | UTF-8 | 725 | 2.9375 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <stdint.h>
int main() {
std::vector<long> vec;
int n;
scanf("%d", &n);
vec.resize(n);
for (int i = 0; i < n; ++i) {
scanf("%ld", &vec[i]);
}
int negative = 0;
uint64_t ret = 0;
bool has_zero = false;
for (int i = 0; i < n; ++i) {
if (vec[i] > 0) {
ret += vec[i] - 1;
} else if (vec[i] < 0) {
negative += 1;
ret += -1 - vec[i];
} else { // 0
has_zero = true;
ret += 1;
}
}
if (negative % 2 == 1 && !has_zero) {
ret += 2;
}
std::cout << ret << std::endl;
return 0;
}
|
SQL | UTF-8 | 5,532 | 3.03125 | 3 | [] | no_license |
CREATE DATABASE IF NOT EXISTS hh_test;
\connect hh_test;
-- Enables heavy_hitters plugin and plpython2u plugin
CREATE EXTENSION IF NOT EXISTS plpython2u;
CREATE EXTENSION IF NOT EXISTS heavy_hitters;
-- Sample table, imagining data being collected for different sites
DROP TABLE IF EXISTS stats;
CREATE TABLE stats (
data_center_id integer PRIMARY KEY,
top_zones heavy_hitters
);
-- Tracking 10 entries for each center
INSERT INTO stats (data_center_id, top_zones) VALUES (1, heavy_hitters(10));
INSERT INTO stats (data_center_id, top_zones) VALUES (2, heavy_hitters(10));
-- Loading some initial data. Whenever possible, this
-- variant of the add_items function should be used.
UPDATE stats SET top_zones = add_items(top_zones,
ARRAY['a.com', 'b.com', 'c.com', 'd.com', 'e.com', 'f.com', 'g.com', 'h.com', 'i.com', 'j.com'],
ARRAY[15, 11, 10, 7, 6, 3, 2, 2, 1, 1]);
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
-- more hits: updating one item at a time just to show the evolution of the algorithm
UPDATE stats SET top_zones = add_item(top_zones, 'z.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'z.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'z.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'a.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'd.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'j.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'h.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'z.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'e.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'a.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'z.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'z.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'j.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'f.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'x.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
UPDATE stats SET top_zones = add_item(top_zones, 'b.com', 1) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
-- Mass update, all incremented by 1. In general, it is faster to use the variant of
-- this function that passes in two arrays, but this version is available for ease of use.
UPDATE stats SET top_zones = add_items(top_zones,
ARRAY['b.com', 'q.com', 'd.com', 'a.com', 'q.com', 'f.com', 'a.com', 'd.com',
'a.com', 'q.com', 'f.com', 'a.com', 'd.com', 'a.com', 'q.com', 'f.com', 'a.com',
'd.com', 'a.com', 'q.com', 'f.com', 'a.com', 'd.com', 'a.com', 'q.com', 'f.com',
'a.com', 'd.com', 'a.com', 'q.com', 'f.com', 'a.com', 'd.com', 'a.com', 'q.com',
'f.com', 'a.com', 'd.com', 'a.com', 'q.com', 'f.com', 'a.com', 'd.com', 'a.com',
'q.com', 'f.com', 'a.com', 'd.com', 'a.com', 'q.com', 'f.com', 'a.com']
) WHERE data_center_id=1;
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
-- Show all results
SELECT list_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
-- Show results in guaranteed order
SELECT list_ordered_heavy_hitters(top_zones) FROM stats WHERE data_center_id=1;
-- Same as above, but just show the zone
SELECT (list_ordered_heavy_hitters(top_zones)).item AS top_zones_ordered FROM stats WHERE data_center_id=1;
-- Same as above, but just show the top 5 zones
SELECT (list_ordered_heavy_hitters(top_zones)).item
AS top_zones_ordered
FROM stats
WHERE data_center_id=1
LIMIT 5;
-- Select all items that might have 7 or more hits
SELECT item AS items_maybe_over_7
FROM list_heavy_hitters(
(SELECT top_zones FROM stats WHERE data_center_id=1)
) WHERE high >= 7;
-- Select all items guaranteed to have 7 or more hits
SELECT item AS items_guaranteed_over_7
FROM list_heavy_hitters(
(SELECT top_zones FROM stats WHERE data_center_id=1)
) WHERE low >= 7;
-- Select the "grey area": items where we are not sure if they are over the threshold or not
SELECT item AS grey_area
FROM list_heavy_hitters(
(SELECT top_zones FROM stats WHERE data_center_id=1)
) WHERE high >= 7
AND low < 7;
|
Python | UTF-8 | 1,800 | 3.296875 | 3 | [] | no_license | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import random
style.use('fivethirtyeight')
#xs = np.array([1,2,3,4,5,6], dtype=np.float64)
#ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def create_dataset(hm, variance, step=2,correlation = False):
val = 1
ys = []
for i in range(hm):
y = val + random.randrange(-variance, variance)
ys.append(y)
if correlation and correlation == 'pos':
val+=step
elif correlation and correlation == 'neg':
val-=step
xs = [i for i in range(len(ys))]
return np.array(xs,dtype=np.float64), np.array (ys, dtype = np.float64)
def best_fit_slope(xs,ys):
m = ( ((mean(xs)*mean(ys)) - mean (xs*ys)) / ((mean(xs) * mean(xs)) - mean(xs**2)) )
return m
def best_fit_yintercept (m):
# b = mean(y) - m(mean(x))
b = mean(ys) - m * mean(xs)
return b
def predictay (x):
y = (m * x + b )
return y
def squared_error(ys_orig, ys_line):
return sum((ys_line-ys_orig)**2)
def coefficient_of_determination(ys_orig,ys_line):
ys_mean_line = [mean(ys_orig) for y in ys_orig]
squared_error_regr = squared_error(ys_orig, ys_line)
squared_error_y_mean = squared_error(ys_orig, ys_mean_line)
return 1 - (squared_error_regr / squared_error_y_mean)
xs, ys = create_dataset(40,80,2,correlation = 'pos')
m = best_fit_slope(xs,ys)
b = best_fit_yintercept(m)
regression_line = [(m*x) + b for x in xs]
predict_x = 45
predict_y = predictay(predict_x)
r_squared = coefficient_of_determination (ys, regression_line)
plt. scatter(predict_x, predict_y,color='red')
plt.scatter(xs,ys)
plt.plot(xs,regression_line)
print(m)
#plt.scatter(xs,ys)
#plt.show()
|
Java | UTF-8 | 337 | 3.25 | 3 | [] | no_license | import java.util.Scanner;
public class Odd {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number");
int n=s.nextInt();
int even=0;
for(int i=0;i<=n;i++)
{
if(i%2==0)
{
even=even+i;
}
}
System.out.println(even);
}
}
|
Python | UTF-8 | 138 | 3.75 | 4 | [] | no_license | def areYouPlayingBanjo(name):
if name[0].upper() == 'R':
return f'{name} plays banjo'
return f'{name} does not play banjo' |
Java | UTF-8 | 294 | 1.703125 | 2 | [] | no_license | package com.xjw.service.message;
import com.xjw.base.service.BaseServcie;
import com.xjw.entity.po.message.MessageUser;
import com.xjw.utility.BizException;
public interface MessageUserService extends BaseServcie<MessageUser>{
public void deleteById(Long id) throws BizException;
}
|
Java | UTF-8 | 3,046 | 2.234375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2013 IIT , NCSR Demokritos - http://www.iit.demokritos.gr,
* SciFY NPO - http://www.scify.org
*
* This product is part of the PServer Free Software.
* For more information about PServer visit http://www.pserver-project.org
*
* 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.
*
* If this code or its output is used, extended, re-engineered, integrated,
* or embedded to any extent in another software or hardware, there MUST be
* an explicit attribution to this work in the resulting source code,
* the packaging (where such packaging exists), or user interface
* (where such an interface exists).
*
* The attribution must be of the form
* "Powered by PServer, IIT NCSR Demokritos , SciFY"
*/
package pserver.utilities;
import pserver.WebServer;
import pserver.data.DBAccess;
import pserver.data.VectorMap;
/**
* This is a simple class that checks the client credentials of a request
*
* @author Nick Zorbas <nickzorb@gmail.com>
*
* @since 1.1
*/
public abstract class ClientCredentialsChecker {
/**
* Check whether there are valid clinet credentials in the query parameters
*
* @param dbAccess the pserver's database connection handler
* @param queryParam the current request's query parameters
* @return returnes whether the check was successful or not (true or false)
*/
public static boolean check(DBAccess dbAccess, VectorMap queryParam) {
int clntIdx = queryParam.qpIndexOfKeyNoCase("clnt");
if (clntIdx == -1) {
WebServer.win.log.error("-Missing client credentials");
return false;
}
String clientCredentials = (String) queryParam.getVal(clntIdx);
if (clientCredentials.indexOf('|') <= 0) {
WebServer.win.log.error("-Malformed client credentials \"" + clientCredentials + "\"");
return false;
}
String clientName = clientCredentials.substring(0, clientCredentials.indexOf('|'));
String clientPass = clientCredentials.replace(clientName, "").replace("|", "");
try {
dbAccess.connect();
boolean res = dbAccess.checkClientCredentials(clientName, clientPass);
if (res == false) {
WebServer.win.log.error("-Invalid client credentials \"" + clientCredentials + "\"");
}
return res;
} catch (Exception e) {
WebServer.win.log.error("-Database exception: " + e.getLocalizedMessage());
return false;
}
}
}
|
C++ | BIG5 | 953 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Polynomial
{
int p1,p2,p3;
public:
// Polynomial()
// {
// p1=0;
// p2=0;
// p3=0;
// }
Polynomial(int _p1=0,int _p2=0,int _p3=0); //w]غcl
void print_data()
{
cout<<p1<<"x^2";
judge(p2); //P_᭱O_Ʀr ܥ[W[ S X
if(p2!=0)
cout<<p2<<"x";
judge(p3);
if(p3!=0)
cout<<p3;
cout<<" = 0";
}
void judge(int x)
{
if(x>0)
cout<<" + ";
else
cout<<" ";
}
Polynomial operator+(Polynomial& p);
};
Polynomial::Polynomial(int _p1,int _p2,int _p3)
{
p1=_p1;
p2=_p2;
p3=_p3;
}
Polynomial Polynomial::operator+(Polynomial& p)
{
Polynomial ex3;
ex3.p1=p1+p.p1;
ex3.p2=p2+p.p2;
ex3.p3=p3+p.p3;
return ex3;
}
int main()
{
Polynomial ex1(10,20,40),ex2(5,8,-45),ex3;
ex1.print_data(),cout<<endl<<"[W"<<endl,ex2.print_data(),cout<<endl<<"G:";
ex3=ex1+ex2,ex3.print_data();
}
|
Java | UTF-8 | 1,734 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package com.octopus.utils.xml.auto.pointparses;
import com.octopus.utils.alone.StringUtils;
import com.octopus.utils.xml.XMLObject;
import com.octopus.utils.xml.auto.IPointParse;
import com.octopus.utils.xml.auto.XMLParameter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.List;
import java.util.Map;
/**
* User: wfgao_000
* Date: 15-10-15
* Time: 下午5:08
* case (v,[{"",""}])
*/
public class PointParseCase implements IPointParse {
transient static Log log = LogFactory.getLog(PointParseCase.class);
@Override
public String parse(String str, Map data,XMLObject obj) {
try{
String tm =str.substring("case(".length(), str.length() - 1);
int m = tm.indexOf(",");
String v = tm.substring(0,m);
String v2 = tm.substring(m+1);
List<List> l = StringUtils.convert2ListJSONObject(v2);
l = XMLParameter.getValueListFromMapDataByJsonMapExp(data,l,null);
if(null != l){
String def="";
for(int i=0;i<l.size();i++){
if(v.equals(l.get(i).get(0))){
if(l.get(i).size()>1)
return (String)l.get(i).get(1);
return "";
}
if("default".equals(l.get(i).get(0))){
if(l.get(i).size()>1)
def= (String)l.get(i).get(1);
}
}
if(StringUtils.isNotBlank(def))
return def;
}
}catch (Exception e){
log.error("PointParseCase ["+str+"]",e);
}
return str;
}
} |
Java | UTF-8 | 2,636 | 3.96875 | 4 | [
"MIT"
] | permissive | package calculator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try(Scanner sc = new Scanner(System.in)) {
System.out.println("Enter your first number");
int a = sc.nextInt();
System.out.println("Enter your second number");
int b = sc.nextInt();
System.out.println("Now the system calculate the sum");
int c = a + b;
System.out.println("First number is: " + a);
System.out.println("Second number is: " + b);
System.out.println("Sum is: " + c);
System.out.println("Enter your first number");
int ab = sc.nextInt();
System.out.println("Enter your second number");
int bc = sc.nextInt();
System.out.println("Now system calculate the difference");
int abc = ab - bc;
System.out.println("First number is: " + ab);
System.out.println("Second number is: " + bc);
System.out.println("Difference is: " + abc);
System.out.println("Enter your first number");
int ba = sc.nextInt();
System.out.println("Enter your second number");
int cb = sc.nextInt();
System.out.println("Now the system calculate the product");
int bac = ba * cb;
System.out.println("First number is: " + ba);
System.out.println("Second number is: " + cb);
System.out.println("Produc is: " + bac);
System.out.println("Enter your first number");
int ac = sc.nextInt();
System.out.println("Enter your second number");
int bb = sc.nextInt();
System.out.println("Now the system calculate the quotient");
int cba = ac / bb;
System.out.println("First number is: " + ac);
System.out.println("Second number is: " + bb);
System.out.println("Quotient is: " + cba);
System.out.println("Enter your first number");
int firstNumber = sc.nextInt();
System.out.println("Choose your operation +, -, * or /");
String operation = sc.next();
System.out.println("Enter your second number");
int secondNumber = sc.nextInt();
System.out.println("Now system is calculating");
int result = 0;
if(operation.equals("+")) {
result = firstNumber + secondNumber;
} else if(operation.equals("-")) {
result = firstNumber - secondNumber;
} else if(operation.equals("*")) {
result = firstNumber * secondNumber;
} else if(operation.equals("/")) {
result = firstNumber / secondNumber;
}
System.out.println("First number is: " + firstNumber);
System.out.println("Second number is: " + secondNumber);
System.out.println("The result is: " + result);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.