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
|
|---|---|---|---|---|---|---|---|
SQL
|
UTF-8
| 1,252
| 4.15625
| 4
|
[] |
no_license
|
-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes, like
-- these lines here.
DROP DATABASE IF EXISTS tournament;
CREATE DATABASE tournament;
\c tournament;
--Creating table for registered players
create table players (
id serial primary key,
name text);
--Creating table for tracking winners and losers
create table match (
match_id serial primary key,
winner int references players(id),
loser int references players(id)
);
create view standings as
--http://stackoverflow.com/questions/29936536/how-to-count-two-separate-columns-in-the-same-table-and-sum-them-into-a-new-colu
SELECT id, name,
COUNT(CASE id WHEN winner THEN 1 ELSE NULL END) AS wins,
COUNT(match_id) AS matches
FROM players
LEFT JOIN match ON id IN (winner, loser)
GROUP BY id, name;
|
Swift
|
UTF-8
| 269
| 2.578125
| 3
|
[] |
no_license
|
//
// NewsSource.swift
// NewsApp
//
// Created by Mohammad Azam on 6/30/21.
//
import Foundation
struct NewsSourceResponse: Decodable {
let sources: [NewsSource]
}
struct NewsSource: Decodable {
let id: String
let name: String
let description: String
}
|
JavaScript
|
UTF-8
| 4,556
| 2.59375
| 3
|
[] |
no_license
|
var express = require("express");
var router = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");
// INDEX - show all campgrounds.
router.get("/", function(req, res){
var perPage = 8;
var pageQuery = parseInt(req.query.page);
var pageNumber = pageQuery ? pageQuery : 1;
if(req.query.search){
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
// Get all campgrounds from DB.
Campground.find({name: regex}).skip((perPage * pageNumber) - perPage).limit(perPage).exec(function (err, allCampgrounds) {
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
Campground.count({name: regex}).exec(function (err, count) {
if (err) {
req.flash("error", "No campgrounds match that query, please try again.");
res.redirect("back");
} else {
res.render("campgrounds/index", {
campgrounds: allCampgrounds,
current: pageNumber,
pages: Math.ceil(count / perPage),
search: req.query.search,
page: "campgrounds"
});
}
});
}
});
} else {
// get all campgrounds from DB
Campground.find({}).skip((perPage * pageNumber) - perPage).limit(perPage).exec(function (err, allCampgrounds) {
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
Campground.count().exec(function (err, count) {
if (err) {
req.flash("error", err.message);
res.redirect("back");
} else {
res.render("campgrounds/index", {
campgrounds: allCampgrounds,
current: pageNumber,
pages: Math.ceil(count / perPage),
search: false,
page: "campgrounds"
});
}
});
}
});
}
});
//CREATE - add new campground to DB
router.post("/", middleware.isLoggedIn, function(req, res){
// add author to campground
req.body.campground.author = {
id: req.user._id,
username: req.user.username
};
// Create a new campground and save to DB
Campground.create(req.body.campground, function(err, newlyCreated){
if(err){
req.flash('error', err.message);
return res.redirect('back');
} else {
//redirect back to campgrounds page
res.redirect('/campgrounds/' + newlyCreated.id);
}
});
});
// NEW - show form to create new campground.
router.get("/new", middleware.isLoggedIn, function(req, res){
res.render("campgrounds/new");
});
// SHOW - shows more info about one campground.
router.get("/:id", function(req, res){
// Find the campground with provided ID.
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
// Render show template with that campground.
res.render("campgrounds/show", {campground: foundCampground});
}
});
});
// EDIT CAMPGROUND ROUTE.
router.get("/:id/edit", middleware.checkCampgroundOwnership, function(req, res){
Campground.findById(req.params.id, function(err, foundCampground){
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
//render show template with that campground
res.render("campgrounds/edit", {campground: foundCampground});
}
});
});
// UPDATE CAMPGROUND ROUTE
router.put("/:id", middleware.checkCampgroundOwnership, function(req, res){
Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err, campground){
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
req.flash("success","Successfully updated campground.");
res.redirect("/campgrounds/" + campground._id);
}
});
});
// DESTROY CAMPGROUND ROUTE.
router.delete("/:id", middleware.checkCampgroundOwnership, function(req, res){
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
req.flash("error", err.message);
res.redirect("/campgrounds");
} else {
req.flash("success", "Successfully deleted campground.");
res.redirect("/campgrounds");
}
});
});
function escapeRegex(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
module.exports = router;
|
TypeScript
|
UTF-8
| 152
| 2.578125
| 3
|
[] |
no_license
|
export type ITopic = 'Biologia' | 'Administração de Empresas' | 'Marketing Digital'
export interface ICard {
question: string;
answer: string;
}
|
JavaScript
|
UTF-8
| 3,465
| 3.15625
| 3
|
[] |
no_license
|
$(document).ready(function () {
$("#userBtn").click(function (e) {
e.preventDefault();
var formError = false;
var $oldPass = $("#oldPass");
var $newPass = $("#newPass");
var $reNewPass = $("#reNewPass");
$oldPass.removeClass('error').parent().attr('data-content', '');
$newPass.removeClass('error').parent().attr('data-content', '');
$reNewPass.removeClass('error').parent().attr('data-content', '');
if (!$oldPass.val()) {
$oldPass.addClass("error").parent().attr('data-content', 'Du må fylle inn gammelt passord.');
formError = true;
}
if (!$newPass.val()) {
$newPass.addClass("error").parent().attr('data-content', 'Du må fylle inn nytt passord.');
formError = true;
}
if (!$reNewPass.val()) {
$reNewPass.addClass("error").parent().attr('data-content', 'Du må repetere nytt passord.');
formError = true;
}
if ($newPass.val() != $reNewPass.val()) {
$reNewPass.addClass('error').parent().attr('data-content', 'Må samsvare med nytt passord.');
formError = true;
}
var errorMessage = validatePassword($newPass.val());
if (errorMessage != null) {
$newPass.addClass('error').parent().attr('data-content', errorMessage);
formError = true;
}
if (!formError) {
$('#userBtn').html(`<div class="typing_loader"></div>`);
var data = {"oldpass": $oldPass.val(), "newpass": $newPass.val()};
$.ajax({
url: "../rest/user/changepass",
type: 'POST',
data: data,
success: passwordChangeSuccess,
error: passwordChangeFailure,
});
}
})
});
function passwordChangeSuccess(data) {
$('#userBtn').text("Endre passord");
$("#popup-title").text("Suksess");
$("#popup-message").text("Ditt passord har nå blitt endret.");
$("#popup-btn2").hide();
$("#popup-btn1").text("Ok");
$(".popup").show();
$("#popup-btn1").click(function () {
$(".popup").hide();
})
}
function passwordChangeFailure(data) {
$('#userBtn').text("Endre passord");
$("#popup-title").text("En feil har oppstått");
$("#popup-message").text("Passordet som ble skrevet inn samsvarer ikke med ditt passord, skriv inn på nytt.");
$("#popup-btn2").hide();
$("#popup-btn1").text("Ok");
$(".popup").show();
$("#popup-btn1").click(function () {
$(".popup").hide();
})
}
function validatePassword(password) {
if (password.length < 8) {
return "Passordet må være minst 8 tegn";
}
if (password.toUpperCase() == password) {
// No lowercase letters
return "Passordet må ha både små og store bokstaver";
}
if (password.toLowerCase() == password) {
// No uppercase letters
return "Passordet må ha både små og store bokstaver";
}
if (getSpecialCharacterCount(password) < 2) {
return "Passordet må ha minst 2 spesialtegn";
}
return null;
}
function getSpecialCharacterCount(string) {
var specialChars = "0123456789<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var count = 0;
for (var i = 0; i < string.length; i++) {
if (specialChars.indexOf(string[i]) > -1) {
count++;
}
}
return count;
}
|
C++
|
UTF-8
| 1,492
| 3.4375
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
namespace ece309 {
class Object{
public:
virtual void print(){ printf("object!\n"); };
};
//Integer Object
class Integer: public Object {
public:
int data;
Integer(int x):data(x){}
void print(){
printf("%d\n", data);
}
};
//Doubles Object
class Doubles: public Object {
public:
double data;
Doubles(double x):data(x){}
void print() {
printf("%f\n", data);
}
};
//Double Strings
class Strings: public Object {
public:
char* data;
Strings(char *x): data(x){}
void print() {
printf("%s\n", data);
}
};
//List created here
class PList {
private:
class ListNode { //Node Created
private:
ListNode *next;
Object *data; //Moved to Public bc of access errors
public:
ListNode (Object *input, ListNode *n_value = NULL){
data = input;
next = n_value;
}
Object* getItem(){
return data;
}
ListNode* getNext(){
return next;
}
void setNext(ListNode *e){ next = e; }
};
public:
ListNode *head;
ListNode *tail;
PList(){
head = NULL;
tail = NULL;
}
class iterator {
public:
ListNode *node;
iterator(ListNode *n = NULL){
node = n;
}
Object* getItem() { return node->getItem();}
void increment() { node = node->getNext(); }
bool end() { return node==NULL; }
};
iterator begin();
void append(Object *a);
void removeAfter(iterator it);
void insertAfter(iterator it, Object *a);
};
}
|
Python
|
UTF-8
| 443
| 3.015625
| 3
|
[] |
no_license
|
# -*- coding: UTF-8 -*-
__author__ = 'zy'
__time__ = '2019/8/31 16:55'
import matplotlib.pyplot as plt
from matplotlib import cm
from numpy import linspace
start = 0.0
stop = 1.0
number_of_lines= 7
cm_subsection = linspace(start, stop, number_of_lines)
print(cm_subsection)
colors = [ cm.jet(x) for x in cm_subsection ]
print(colors)
for i, color in enumerate(colors):
plt.axhline(i, color=color)
plt.ylabel('Line Number')
plt.show()
|
C++
|
UTF-8
| 2,221
| 3.09375
| 3
|
[] |
no_license
|
#include <iostream>
#include <SDL2/SDL.h>
#include "sdl_screen.hpp"
sdl_screen::sdl_screen() {
width = 160;
height = 144;
window_title = "";
fps_limit = 60;
window = nullptr;
renderer = nullptr;
texture = nullptr;
current_frame = 0;
quit = false;
}
sdl_screen::~sdl_screen() {
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void sdl_screen::set_title(std::string title) {
SDL_SetWindowTitle(window,title.c_str());
}
bool sdl_screen::init() {
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cerr << SDL_GetError() << std::endl;
return false;
}
window = SDL_CreateWindow(window_title.c_str(),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
width, height,
SDL_WINDOW_OPENGL);
if (window == nullptr) {
std::cerr << SDL_GetError() << std::endl;
return false;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == nullptr) {
std::cerr << SDL_GetError() << std::endl;
return false;
}
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
if (texture == nullptr) {
std::cerr << SDL_GetError() << std::endl;
return false;
}
return true;
}
void sdl_screen::event_handler() {
//While there's events to handle
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN: std::cout << "A key is being pressed" << std::endl; break;
case SDL_QUIT: quit = true; break;
default: break;
}
}
}
bool sdl_screen::is_running() const {
return !quit;
}
void sdl_screen::render(unsigned char* screen_context) {
//Start the frame timer
fps.start();
// Drawing code goes here
SDL_UpdateTexture(texture, nullptr, screen_context,16);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
// Flip buffers
SDL_RenderPresent(renderer);
//Increment the frame counter
current_frame++;
//If we want to cap the frame rate
if (fps.get_ticks() < 1000 / fps_limit) {
//Sleep the remaining frame time
SDL_Delay((1000 / fps_limit) - fps.get_ticks());
}
}
|
Swift
|
UTF-8
| 2,995
| 2.546875
| 3
|
[] |
no_license
|
//
// TopOfertasViewController.swift
// YourMall
//
// Created by Juan Munhoes Junior on 7/19/16.
// Copyright © 2016 Hackatruck. All rights reserved.
//
import UIKit
class TopOfertasViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView:UITableView!
var listaOfertas:[Oferta] = [Oferta]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let o1 = Oferta(nome: "Lacoste", total: 100, descricao: "asudhua ushu adhud uah audu shau suahuduafubagjajs fja gjka fj aksjk ka dska kd agqkj wke am,s ag ,asf", url: "lacoste", categoria: "Roupas", preco: 200.00)
let o2 = Oferta(nome: "Calvin Klein", total: 99, descricao: " asjd saj d gja ng w qke qkd qk dkjqw dj ak g as, gm,a s,dam sdjq j s dan a ajs fajs djkq wdqdw, ga ,s fajdka d af asga skd adjk sakjasdu ahus hudauhhua uha ausdhuaushduhqwneq dk qwdkqw ddqdq", url: "ck", categoria: "Roupas", preco: 53.90)
listaOfertas.append(o1)
listaOfertas.append(o2)
self.tableView.estimatedRowHeight = 134
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return listaOfertas.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellOfertas", forIndexPath: indexPath) as! CellOfertas
let oferta = listaOfertas[indexPath.row]
if oferta.imagemUrl != ""{
cell.imgPerfil.image = UIImage(named: oferta.imagemUrl!)
}
cell.lblNomeLoja.text = oferta.nomeLoja
cell.lblCategoria.text = oferta.categoria
cell.lblDescricao.text = oferta.descricao
cell.lblValor.text = String(format: "R$ %.2f", oferta.preco)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
Java
|
UTF-8
| 452
| 1.921875
| 2
|
[] |
no_license
|
package com.edaisong.entity.req;
/*
* 骑士月账单请求参数
* */
public class AccountBillCReq {
private String monthInfo;//月信息 2015-08
private Integer clienterId;//商户ID
public String getMonthInfo() {
return monthInfo;
}
public void setMonthInfo(String monthInfo) {
this.monthInfo = monthInfo;
}
public Integer getClienterId() {
return clienterId;
}
public void setClienterId(Integer clienterId) {
this.clienterId = clienterId;
}
}
|
SQL
|
UTF-8
| 1,561
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
INSERT INTO Banks (BankName, City, NoAccounts, Security)
VALUES ('Loanshark Bank', 'Evanston', 100, 'very good'::SecurityLevel);
INSERT INTO Banks (BankName, City, NoAccounts, Security)
VALUES ('Loanshark Bank', 'Evanston', -5, 'excellent'::SecurityLevel);
INSERT INTO Banks (BankName, City, NoAccounts, Security)
VALUES ('Loanshark Bank', 'Evanston', 100, 'poor'::SecurityLevel);
INSERT INTO Skills (SkillId, Description)
VALUES (20, 'Guarding');
INSERT INTO Robbers (RobberId, Nickname, Age, NoYears)
VALUES (1, 'Shotgun', 70, 0);
INSERT INTO Robbers (RobberId, Nickname, Age, NoYears)
VALUES (333, 'Jail Mouse', 25, 35);
INSERT INTO HasSkills (RobberId, SkillId, Preference, Grade)
VALUES (333, 1, 1, 'B-');
INSERT INTO HasSkills (RobberId, SkillId, Preference, Grade)
VALUES (3, 20, 3, 'B+');
INSERT INTO HasSkills (RobberId, SkillId, Preference, Grade)
VALUES (1, 7, 1, 'A+');
INSERT INTO HasSkills (RobberId, SkillId, Preference, Grade)
VALUES (1, 2, 0, 'A');
INSERT INTO Robberies
VALUES ('NXP Bank', 'Chicago', '2009-01-08', 1000);
DELETE FROM Banks WHERE
BankName = 'PickPocket Bank' AND
City = 'Evanston' AND
NoAccounts = 2000 AND
Security = 'very good';
DELETE FROM Banks WHERE
BankName = 'Outside Bank' AND
City = 'Chicago' AND
NoAccounts = 5000 AND
Security = 'good';
DELETE FROM Robbers WHERE
RobberId = 1 AND
Nickname = 'Al Capone' AND
Age = 31 AND
NoYears = 2;
DELETE FROM Skills WHERE
SkillId = 1 AND
Description = 'Driving';
|
Swift
|
UTF-8
| 766
| 3.546875
| 4
|
[] |
no_license
|
//: [Previous](@previous)
/*
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
*/
class Solution {
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var prev: ListNode? = dummy
var current: ListNode? = head
while current != nil {
while current?.next?.val == current?.val {
current = current?.next
}
if prev?.next === current {
prev = prev?.next
} else {
prev?.next = current?.next
}
current = current?.next
}
return dummy.next
}
}
//: [Next](@next)
|
Java
|
UTF-8
| 4,460
| 2.578125
| 3
|
[] |
no_license
|
package com.java.springbootresth2basics.controllers;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.java.springbootresth2basics.entities.Author;
import com.java.springbootresth2basics.entities.Book;
import com.java.springbootresth2basics.exceptions.EntityNotFoundException;
import com.java.springbootresth2basics.services.AuthorService;
@RestController
public class AuthorController {
@Autowired
private AuthorService authorService;
@GetMapping("/authors")
public ResponseEntity<List<Author>> getAllAuthors() throws Exception{
List<Author> authors = authorService.retrieveAllAuthors();
if(authors.isEmpty()) {
//set an error message
throw new Exception("Unable to get authors");
}
return ResponseEntity.ok(authors);
}
@GetMapping("/authors/{id}")
public ResponseEntity<Author> getAuthor(@PathVariable int id) throws EntityNotFoundException, Exception{
Author author = authorService.retrieveAuthorByID(id)
.orElseThrow(() -> new EntityNotFoundException("id = " + id));
return ResponseEntity.ok(author);
}
@GetMapping("/authors/{id}/books")
public ResponseEntity<List<Book>> getBooksFromAuthor(@PathVariable int id) throws EntityNotFoundException, Exception{
try {
Optional<Author> authorOptional = authorService.retrieveAuthorByID(id);
List<Book> authorBooks = authorOptional.get().getBooks();
if(authorBooks.isEmpty()) {
throw new Exception("Unable to get books from author");
}
return ResponseEntity.ok(authorBooks);
}catch(EntityNotFoundException entityNotFound) {
throw new EntityNotFoundException("id = " + id);
}catch(Exception e) {
throw new Exception("Unable to get books from author");
}
}
//input - details of a new author
//output - CREATED and return the created URI
@PostMapping("/authors")
public ResponseEntity<Object> createNewAuthor(@Valid @RequestBody Author author) {
Author savedAuthor = authorService.saveAuthor(author);
/*1. define the URI location of the new user resource -> /authors/{id}:
How?
Take the request URI (/authors) and append the new author ID (savedAuthor.getId())
a. ServletUriComponentsBuilder
.fromCurrentRequest() -> returns the current request URI : /authors
b. .path("/{id}") -> append the "/{id}" to the current request URI ("/authors")
c. .buildAndExpand(savedAuthor.getId()) -> replace the append "{id}" by the new author ID
d. .toUri() -> convert the result into a URI
*/
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedAuthor.getId()).toUri();
/*ResponseEntity -> Allow to return the Response State Code of "201" along with the URI user resource created: /authors/{id}
*/
return ResponseEntity
.created(location)
.body(savedAuthor);
}
//update all existing author fields
@PutMapping("/authors/{id}")
public Author fullUpdateAuthor(@PathVariable int id, @Valid @RequestBody Author author) {
Author existingAuthor = authorService.retrieveAuthorByID(id)
.orElseThrow(() -> new EntityNotFoundException("id = " + id));
//update existingAuthor fields - change for a DTO
existingAuthor.setName(author.getName());
existingAuthor.setNationality(author.getNationality());
existingAuthor.setBirthdate(author.getBirthdate());
authorService.saveAuthor(existingAuthor);
return existingAuthor;
}
@DeleteMapping("/authors/{id}")
public void deleteAuthor(@PathVariable int id) {
authorService.deleteAuthor(id);
}
}
|
Java
|
UTF-8
| 1,860
| 2.765625
| 3
|
[] |
no_license
|
package events;
import java.util.ArrayList;
import java.util.Arrays;
import game.GameData;
import main.Common;
import map.MapManager;
import powerstruggle.PowerStruggle;
public class SocialDemocraticPlatform extends Card {
private static ArrayList<Integer> doable;
public static int target;
@Override
public void onEvent(int sp, String[] args) {
GameData.dec = new Decision(1, 106);
Common.spChannel(1).sendMessage(Common.spRole(1).getAsMention() + ", you have selected " + Common.countries[target] + ". You may now add 2 Communist Support to that country.").complete();
}
@Override
public boolean isPlayable(int sp) {
return true;
}
@Override
public String getId() {
return "106";
}
@Override
public String getName() {
return "Social Democratic Platform Adopted";
}
@Override
public int getOps() {
return 3;
}
@Override
public int getEra() {
return 2;
}
@Override
public int getAssociation() {
return 1;
}
@Override
public boolean isRemoved() {
return true;
}
@Override
public boolean isFormatted(int sp, String[] args) {
doable = new ArrayList<Integer>();
for (int i = 0; i<6; i++) {
if (PowerStruggle.retained[i]==-1) doable.add(i);
}
ArrayList<Character> a = new ArrayList<Character>();
a.addAll(Arrays.asList('e','p','c','h','r','b'));
if (args.length<2) return false;
char b = args[1].charAt(0);
if (a.indexOf(b)==-1) return false;
target = a.indexOf(b);
return doable.contains(target);
}
@Override
public String getDescription() {
return "The Communist selects a country where the Democrat holds power. Add 2 Communist Support to that country, then conduct a support check within that country.";
}
@Override
public String getArguments() {
return "Event: The country.\n"
+ "Decision 1: the influence to add.\n"
+ "Decision 2: the support check.";
}
}
|
Python
|
UTF-8
| 3,091
| 2.640625
| 3
|
[] |
no_license
|
import psycopg2
import json
import requests
from time import sleep
from backend.database import get_cursor, base_url
def create_dummy_prediction_fixtures():
cur = get_cursor()
#get list of stops
cur.execute("SELECT stopId FROM stops;")
stop_ids_tuples = cur.fetchall()
# THERE HAS GOT TO BE A BETTER WAY TO DO THIS
stop_ids = []
for stop_id in stop_ids_tuples:
stop_ids.append(stop_id[0])
cur.execute("SELECT to_regclass('public.predictions')")
predictionsExists = cur.fetchone()
print(predictionsExists[0])
if predictionsExists[0] != "predictions":
cur.execute("CREATE TABLE predictions(StopId VARCHAR(5), VehicleId VARCHAR(4), RouteName VARCHAR(5), PredictedDelayInSeconds INT, PredictedDeparture TIMESTAMP, PredictionDateTime TIMESTAMP)")
print("table created")
for stop_id in stop_ids:
# This is a hacky way to get stop id out of its tuple, look into this later
# print(base_url.format("stops/" + stop_id[0] + "/predictions"))
r = requests.get(base_url.format("stops/" + stop_id + "/predictions"))
sleep(.4
)
if r.status_code == 404:
continue
predictions = json.loads(r.text)
for prediction in predictions:
try:
cur.execute("INSERT INTO predictions VALUES ({StopId}, {VehicleId}, '{RouteName}', {PredictedDelayInSeconds}, '{PredictedDeparture}', '{PredictionDateTime}')"
.format(StopId=prediction["StopId"], VehicleId=prediction["VehicleId"], RouteName=prediction["RouteName"], PredictedDelayInSeconds=prediction["PredictedDelayInSeconds"], PredictedDeparture=prediction["PredictedDeparture"].replace("T", " "), PredictionDateTime=prediction["PredictionDateTime"].replace("T", " ")))
# This can probably be done away with once requests
except TypeError:
print("this throws if you have exceeded your 150 reqs/min limit")
sleep(60)
def populate_stops():
base_url = "https://api.actransit.org/transit/{}/?token=369BB8F6542E51FF57BC06577AFE829C"
cur = get_cursor()
# cur.execute("DROP TABLE IF EXISTS stops ;")
# Checks to see if it's been prefilled
cur.execute("SELECT to_regclass('public.stops')")
tableExists = cur.fetchone()
if tableExists[0] != "stops":
cur.execute("CREATE TABLE stops(stopId VARCHAR(5), name VARCHAR(100), geo GEOGRAPHY(POINT));")
print("stops table doesn't exist")
r = requests.get(base_url.format("stops"))
stops = json.loads(r.text)
for n in stops:
stop_id = str(n["StopId"])
name = n["Name"].replace("'","")
lat = n["Latitude"]
long = n["Longitude"]
insert_string = "INSERT INTO stops (stopID, name, geo) VALUES({stop_id}, '{name}', ST_SetSRID(ST_MakePoint({long}, {lat}), 4326))".format(stop_id=stop_id, name=name, long=long, lat=lat)
cur.execute(insert_string)
cur.execute("SELECT * FROM stops;")
print("stops populated")
|
C
|
GB18030
| 1,115
| 2.734375
| 3
|
[] |
no_license
|
#pragma once
#include "data_structure.h"
//һʱ
int set_timer(int* flag, int needed_time)
{
static int timer_end;
static int timer_start; //̬
if (*flag) {
timer_end = clock();
}
else {
timer_end = clock();
timer_start = clock();
(*flag)++; //־λ++
}
return(needed_time - (int)(double)((timer_end - timer_start) / CLOCKS_PER_SEC) > 0); //ûʱ
}
//ʼʱ
void Init_time()
{
Timer.rememder = Timer_loop;
Timer.end = Timer.start = clock();
Timer.text_rememder[0] = '6';
Timer.text_rememder[1] = '0';
Timer.text_rememder[2] = 's';
Timer.text_rememder[3] = 0;
return;
}
//¼ʱ
//@return 0ʱ
//@return 1
int Calc_time()
{
Timer.end = clock();
int old_remem = Timer.rememder;
Timer.rememder = Timer_loop - (int)(double)((Timer.end - Timer.start) / CLOCKS_PER_SEC);
if (Timer.rememder >= 0) {
Timer.text_rememder[1] = Timer.rememder % 10 + '0';
Timer.text_rememder[0] = Timer.rememder /10 + '0';
}
if (Game_modle == 3) return 1; //ϷģʽΪؿģʽ
return(Timer.rememder >= 0);
}
|
Java
|
UTF-8
| 4,757
| 2.484375
| 2
|
[] |
no_license
|
package com.example.firstwebapplication.generator.triple;
import com.example.firstwebapplication.generator.constraints.Constraint;
import com.example.firstwebapplication.generator.constraints.ConstraintCollection;
import com.example.firstwebapplication.generator.constraints.Mutation;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class TripleFactoryTest {
private final Constraint TRUNCATE_ZIP_CONSTRAINT = new Constraint(
"zip", Mutation.TRUNCATE_NUMBER_OF_CHARACTERS, "1");
private final Constraint REPLACE_CHARACTER_COUNCIL_PERSON_CONSTRAINT = new Constraint(
"council_person", Mutation.REPLACE_CHARACTER, "H", "A");
private ConstraintCollection constraintCollection;
@BeforeEach
void setUp() {
constraintCollection = new ConstraintCollection();
}
@AfterEach
void tearDown() {
constraintCollection = null;
}
@Test
void testMutateObjectIfRequiredByPredicateNoModify() {
String predicate = TRUNCATE_ZIP_CONSTRAINT.getPredicate();
String objectValue = "75074";
String expectedValue = "75074";
String actualValue = TripleFactory.mutateObjectIfRequiredByPredicate(
predicate, objectValue, null
);
assertEquals(expectedValue, actualValue);
actualValue = TripleFactory.mutateObjectIfRequiredByPredicate(
predicate, objectValue, constraintCollection
);
assertEquals(expectedValue, actualValue);
}
@Test
void testMutateObjectIfRequiredByPredicateSingleTriple() {
String predicate = TRUNCATE_ZIP_CONSTRAINT.getPredicate();
constraintCollection.addConstraint(TRUNCATE_ZIP_CONSTRAINT);
String objectValue = "75074";
String expectedModifiedValue = "7507";
String actualModifiedValue = TripleFactory.mutateObjectIfRequiredByPredicate(
predicate, objectValue, constraintCollection
);
assertEquals(expectedModifiedValue, actualModifiedValue);
}
@Test
void testMutateObjectIfRequiredByPredicateMultipleTriplesSameRule() {
String predicate = REPLACE_CHARACTER_COUNCIL_PERSON_CONSTRAINT.getPredicate();
constraintCollection.addConstraint(REPLACE_CHARACTER_COUNCIL_PERSON_CONSTRAINT);
// modify first triple
String objectValue1 = "Hh Ww";
String expectedModifiedValue1 = "Ah Ww";
String actualModifiedValue1 = TripleFactory.mutateObjectIfRequiredByPredicate(
predicate, objectValue1, constraintCollection
);
assertEquals(expectedModifiedValue1, actualModifiedValue1);
// modify second triple with the same rule
String objectValue2 = "H";
String expectedModifiedValue2 = "A";
String actualModifiedValue2 = TripleFactory.mutateObjectIfRequiredByPredicate(
predicate, objectValue2, constraintCollection
);
assertEquals(expectedModifiedValue2, actualModifiedValue2);
assertNotEquals(expectedModifiedValue2, actualModifiedValue1);
}
@Test
void testCreateListOfTriplesWithoutMappingToOntology() {
String[][] predicates = {
{
"zip",
""
},
{
"council_person",
""
},
{
"district_num",
""
}
};
for(String[] currentPair : predicates) {
String expectedPredicateName = currentPair[0];
String actualPredicateName = TripleFactory.mapPredicateWithOntology(
currentPair[0], currentPair[1]
);
assertEquals(expectedPredicateName, actualPredicateName);
}
}
@Test
void testCreateListOfTriplesWithMappingToOntology() {
String[][] predicates = {
{
"zip",
"zip_code"
},
{
"council_person",
"full_name"
},
{
"district_num",
"district_number"
}
};
for(String[] currentPair : predicates) {
String expectedPredicateName = currentPair[1];
String actualPredicateName = TripleFactory.mapPredicateWithOntology(
currentPair[0], currentPair[1]
);
assertEquals(expectedPredicateName, actualPredicateName);
}
}
}
|
C#
|
UTF-8
| 10,361
| 2.59375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace EIMS1
{
public partial class frmCourse : Form
{
string query;
string courCode;
public frmCourse()
{
InitializeComponent();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void frmCourse_Load(object sender, EventArgs e)
{
gboCourse.Left = (this.Width - gboCourse.Width) / 2;
gboCourse.Top = (this.Height - gboCourse.Height) / 2;
gboSearch.Visible = false;
gboData.Visible = false;
cboCourseCode.Visible = false;
GetCourseCode();
}
private void GetCourseCode()
{
if (cboCourseCode.Visible == true)
{
query = "UPDATE course SET Course_Code='" + cboCourseCode.Text + "', Course_Title='" + txtCourseName.Text + "', Description= '" + rtxtDescription.Text + "', Units='" + txtUnits.Text + "', Prog_Code='" + cboProgramCode.Text + "' WHERE Course_Code= '" + courCode + "'";
}
else
{
query = "INSERT INTO course(Course_Code, Course_Title, Description, Units, Prog_Code) VALUES('" + cboCourseCode.Text + "', '" + txtCourseName.Text + "', '" + rtxtDescription.Text + "', '" + txtUnits.Text + "', '" + cboProgramCode.Text + "')";
}
try
{
conn connect = new conn();
if (connect.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connect.connection);
//MySqlDataReader dataReader
cmd.ExecuteReader();
connect.CloseConnection();
MessageBox.Show("Record Successfully saved!", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Reset();
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void btnQuit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to exit?", "EIMS Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
private void btnReset_Click(object sender, EventArgs e)
{
Reset();
}
private void Reset()
{
txtCourseCode.Text="";
if (cboCourseCode.Visible == true)
{
cboCourseCode.Focus();
}
else
{
txtCourseCode.Focus();
}
txtCourseName.Text="";
txtUnits.Text="";
cboProgramCode.Text="";
rtxtDescription.Text="";
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtCourseCode.Text == "")
{
MessageBox.Show("Ensure all fields are filled", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtCourseCode.Focus();
}
else if ( txtCourseName.Text == "")
{
MessageBox.Show("Ensure all fields are filled", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtCourseName.Focus();
}
else if (txtUnits.Text == "")
{
MessageBox.Show("Ensure all fields are filled", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUnits.Focus();
}
else if (cboProgramCode.Text == "")
{
MessageBox.Show("Ensure all fields are filled", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
cboProgramCode.Focus();
}
else if (rtxtDescription.Text == "")
{
MessageBox.Show("Ensure all fields are filled", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
rtxtDescription.Focus();
}
if (cboCourseCode.Visible == true)
{
query = "UPDATE course SET Course_Code='" + cboCourseCode.Text + "', Course_Title='" + txtCourseName.Text + "', Description= '" + rtxtDescription.Text + "', Units='" + txtUnits.Text + "', Prog_Code='" + cboProgramCode.Text + "' WHERE Course_Code= '" + courCode + "'";
}
else{
conn connect = new conn();
query = "INSERT INTO course(Course_Code, Course_Title, Description, Units, Prog_Code ) VALUES('" + txtCourseCode.Text + "', '" + txtCourseName.Text + "', '" + rtxtDescription.Text + "', '" + txtUnits.Text + "', '" + cboProgramCode.Text + "' )";
//string query = "SELECT * FROM user WHERE Username='" + textUsername.Text.ToString() + "' AND Passsword='" + textPassword.Text.ToString() + "' AND Status=1";
//open connection
if (connect.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connect.connection);
cmd.ExecuteNonQuery();
connect.CloseConnection();
MessageBox.Show("Connection successful");
Reset();
}
}
}
private void cboCourseCode_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCourseCode.Text == "")
{
MessageBox.Show("Ensure that all fields are filled!", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
cboCourseCode.Focus();
}
else
{
conn connect = new conn();
if (connect.OpenConnection() == true)
{
query = "SELECT * FROM course WHERE Course_Code LIKE '" + cboCourseCode.Text + "' ORDER BY Course_Code ASC";
MySqlCommand cmd = new MySqlCommand(query, connect.connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
this.txtCourseName.Text = dataReader["Course_Title"].ToString();
this.txtUnits.Text= dataReader["Units"].ToString();
this.rtxtDescription.Text = dataReader["Description"].ToString();
this.cboProgramCode.Text = dataReader["Prog_Code"].ToString();
courCode = dataReader["Course_Code"].ToString();
}
connect.CloseConnection();
}
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
cboCourseCode.Visible = true;
cboCourseCode.Focus();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (cboCourseCode.Visible == false)
{
MessageBox.Show("Select Details to Edit");
cboCourseCode.Visible = true;
}
else if (MessageBox.Show("Are you sure you want to exit?", "EIMS Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
query = "DELETE FROM course WHERE Course_Code='" + cboCourseCode.Text + "'";
try
{
conn connect = new conn();
if (connect.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connect.connection);
cmd.ExecuteNonQuery();
connect.CloseConnection();
MessageBox.Show("Record Successfully deleted!", "EIMS Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Reset();
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
cboCourseCode.Visible = false;
txtCourseCode.Focus();
Reset();
}
private void btnDataQuit_Click(object sender, EventArgs e)
{
gboSearch.Visible = false;
}
private void btnSearch_Click(object sender, EventArgs e)
{
gboSearch.Visible = true;
txtSearch.Text = "";
cboCriteria.Text = "";
}
private void btnSearchQuit_Click(object sender, EventArgs e)
{
gboSearch.Visible = false;
txtSearch.Text = "";
cboCriteria.Text = "";
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
cboCourseCode.Visible = true;
cboCourseCode.Text = this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
courCode = this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
txtSearch.Visible = false;
gboData.Visible = false;
}
private void tbnAdvanceSearch_Click(object sender, EventArgs e)
{
}
}
}
|
Java
|
UTF-8
| 752
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package me.zhehua.firerooster.pipeline;
/**
* Created by Zhehua on 2017/3/21.
*/
public class ReadTask extends InTask {
@Override
public Message process(Message inputMessage) {
if (((Counter) sharedObj).num >= 300) {
Message endMsg = new Message(Message.STOP_TASK);
endMsg.setSourceTask(this);
processEndTaskMessage(endMsg);
return null;
}
long startTime = System.nanoTime();
while (System.nanoTime() - startTime < 200 * 1000 * 1000) {
}
Message msg;
synchronized(sharedObj) {
msg = new Message(Message.PROCESS, ((Counter) sharedObj).num);
((Counter) sharedObj).num += 1;
}
return msg;
}
}
|
Java
|
UTF-8
| 230
| 2.390625
| 2
|
[] |
no_license
|
package ArrayListSerializationDemo;
import java.io.Serializable;
public class Emp implements Serializable{
int eid;
String ename;
public Emp(int eid, String ename) {
super();
this.eid = eid;
this.ename = ename;
}
}
|
Python
|
UTF-8
| 1,746
| 3.28125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
from .shell import Shell
__copyright__ = 'Copyright (C) 2019, Nokia'
class AutoCompletableShell(Shell):
"""
Several shells support *tab autocompletion*. Any custom shell
implementation can inherit from this class in order to provide such
functionality.
Args:
cmd: part of a command.
autocompletion_trigger: characters that the user would press to trigger
autocompletion (for example ``'\\t'`` for bash)
timeout: how much time to wait (in seconds) for the shell prompt to
reappear after the tab completion
Autocompletion works in different ways for different shells. Furthermore in
some cases the autocompleted content just appears in the same line that the
user was typing the command while in other cases it is printed below this
line followed by a new prompt. The default implementation that can be
reused by Shell derivatives works by expecting the new prompt for a finite
amount of time. If the prompt does not appear then the implementation
assumes that autocompletion occured on the same line and returns as a
result any bytes printed to the terminal until the timeout occured.
"""
def get_command_auto_completion(self,
cmd,
timeout,
autocompletion_trigger):
self._send_input(cmd + autocompletion_trigger)
retval = self._read_until_prompt(timeout, suppress_timeout=True)
self._send_interrupt()
self._read_until_prompt(-1)
# Strip away terminal BEL (bell/alarm) if present
# Occasionally, BEL is printed if command can not be completed
return retval.strip('\x07')
|
Python
|
UTF-8
| 1,986
| 2.765625
| 3
|
[] |
no_license
|
import socket
import threading
import time
import bluetooth
bind_ip = "192.168.1.114"
bind_port = 46000
bluetooth_MAC = '98:D3:31:30:77:53'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
#listen on port 46000 with max connection baglog = 5
server.listen(30)
print "[*] Listening on %s:%d" % (bind_ip, bind_port)
def bt_connect(address, channel):
while(True):
try:
btSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
btSocket.connect((address, channel))
break
except:
btSocket.close()
print "Could not establish bluetooth connection: Retrying in 1s..."
time.sleep(1)
return btSocket
def bt_disconnect(bt_socket):
bt_socket.close()
def turn_off_lights():
switchSocket = bt_connect(bluetooth_MAC, 1)
switchSocket.send('0')
bt_disconnect(switchSocket)
def turn_on_lights():
switchSocket = bt_connect(bluetooth_MAC, 1)
switchSocket.send('1')
bt_disconnect(switchSocket)
# client handling thread
def handle_client(client_socket):
request = client_socket.recv(1024)
if request != '':
print "[*] Received: %s" % (request)
client_socket.send("ACK!")
client_socket.close()
request_params = request.splitlines()
path = request_params[0].split()[1]
if path == '/lights-on':
print path
turn_on_lights()
elif path == '/lights-off':
print path
turn_off_lights()
else:
client_socket.send("ACK!")
client_socket.close()
#Main server loop
while True:
client, addr = server.accept()
print "[*] Accepted connection from %s:%d" % (addr[0], addr[1])
#spin up client thread to pass off connection
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
|
Java
|
UTF-8
| 2,108
| 2.28125
| 2
|
[] |
no_license
|
package no.kantega.forum.search;
import no.kantega.forum.dao.ForumDao;
import no.kantega.forum.model.Post;
import no.kantega.search.api.IndexableDocument;
import no.kantega.search.api.index.ProgressReporter;
import no.kantega.search.api.provider.IndexableDocumentProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.BlockingQueue;
public class ForumSearchProvider implements IndexableDocumentProvider {
private final Logger log = LoggerFactory.getLogger(getClass());
private ProgressReporter progressReporter;
private ForumDao forumDao;
@Autowired
private ForumpostTransformer forumpostTransformer;
public void setForumDao(ForumDao forumDao) {
this.forumDao = forumDao;
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public ProgressReporter getProgressReporter() {
if(progressReporter == null){
progressReporter = new ProgressReporter(ForumpostTransformer.HANDLED_DOCUMENT_TYPE, getNumberOfDocuments());
}
return progressReporter;
}
private long getNumberOfDocuments() {
return forumDao.getAllPosts().size();
}
@Override
public void provideDocuments(BlockingQueue<IndexableDocument> indexableDocuments) {
try {
List<Post> allPosts = forumDao.getAllPosts();
for (Post post : allPosts) {
if(progressReporter==null || progressReporter.isFinished()){
break;
}
try {
IndexableDocument indexablePost = forumpostTransformer.transform(post);
indexableDocuments.put(indexablePost);
} catch (InterruptedException e) {
log.error("Interruped", e);
} finally {
progressReporter.reportProgress();
}
}
} finally {
progressReporter = null;
}
}
}
|
C++
|
UTF-8
| 563
| 3.375
| 3
|
[] |
no_license
|
#include "ex14.StrBlob.hpp"
#include <iostream>
using std::cout;
using std::endl;
int main() {
StrBlob strs{"one", "two", "three", "four"};
StrBlobPtr ptr(strs);
ConstStrBlobPtr cptr = strs.cbegin();
cout << "Test for *ptr ,which should be one" << endl;
cout << *ptr << endl;
cout << "Test for *cptr ,which should be one" << endl;
cout << *cptr << endl;
cout << "Test ptr->size() " << endl;
cout << ptr->size() << endl;
cout << "Test cptr->size() " << endl;
cout << cptr->size() << endl;
return 0;
}
|
C++
|
UTF-8
| 2,302
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include<iostream>
using namespace std;
//#include<conio.h>
#include<map>
struct nodes
{
// long long int clic;
// long long int len;
map<long long int,long long int> m;
struct nodes* next;
};
typedef struct nodes* list;
list insert(list l,long long int c,long long int le)
{
list temp=l;
int c1=0;
if(l==NULL)
{
l=new nodes;
l->m[c]=le;
// l->len=le;
l->next=NULL;
return l;
}
if(c>l->clic)
{
list newn=new nodes;
newn->clic=c;
newn->len=le;
newn->next=l;
temp=l;
while(temp!=NULL)
{
temp->clic+=le;
temp=temp->next;
}
return newn;
}
while(temp->next!=NULL)
{
if(temp->next->clic<c)
{
c1=1;
break;
}
temp=temp->next;
}
if(c1)
{
list newn=new nodes;
newn->clic=c;
newn->len=temp->len+le;
newn->next=temp->next;
temp->next=newn;
temp=newn->next;
while(temp!=NULL)
{
temp->len+=le;
temp=temp->next;
}
return l;
}
else
{
list newn=new nodes;
newn->clic=c;
newn->len=le;
newn->next=NULL;
temp->next=newn;
return l;
}
}
long long int calculate(list l,long long int k)
{
list temp=l;
long long int i=0,tot=0;
while(temp!=NULL&&i<k)
{
tot+=temp->len;
temp=temp->next;
i++;
}
return tot;
}
/*void print(list l,int j)
{
list temp=l;
cout<<" List "<<j+1<<" : ";
while(temp!=NULL)
{
cout<<"\n clic = "<<temp->clic<<" length = "<<temp->len<<"\n";
temp=temp->next;
}
}*/
int main()
{
long long int t,i,j;
long long int n,m,q,u,c,l,k,tot;
scanf("%lld",&t);
for(i=1;i<=t;i++)
{
scanf("%lld%lld%lld",&n,&m,&q);
list li[n];
for(j=0;j<n;j++)
li[j]=NULL;
for(j=0;j<m;j++)
{
scanf("%lld%lld%lld",&u,&c,&l);
li[u-1]=insert(li[u-1],c,l);
}
tot=0;
printf("Case #%lld:\n",i);
for(j=0;j<q;j++)
{
tot=0;
scanf("%lld",&k);
for(l=0;l<n;l++)
tot+=calculate(li[l],k);
printf("%lld\n",tot);
}
}
// getch();
return 0;
}
|
JavaScript
|
UTF-8
| 1,212
| 2.515625
| 3
|
[] |
no_license
|
export default class Song {
constructor(song) {
this.title = song.trackName
//Change 250x250 if you want a larger image
this.albumArt = song.artworkUrl60.replace(/60x60/g, "250x250")
this.artist = song.artistName
this.collection = song.collectionName
this.price = song.collectionPrice
this.preview = song.previewUrl
}
getTemplate() {
return `
<div class="col-xs-12 col-md-6 col-lg-4 col-xl-3">
<div class="card c-background">
<img src="${this.albumArt}" class="card-img-top card-h" alt="...">
<div class="card-body d-flex flex-column card-text vh100">
<audio controls class="justify-self-end audio-display" id="pause">
<source src="${this.preview}" type="audio/ogg">
Your browser does not support the audio element.
</audio>
<h3>Title: ${this.title}</h3>
<p>Album: ${this.collection}</p>
<p>Artist: ${this.artist}</p>
<p>Price: ${this.price}</p>
</div>
</div>
</div>
`
}
}
|
Java
|
UTF-8
| 3,179
| 2.59375
| 3
|
[] |
no_license
|
package com.ctco.testSchool;
import static org.hamcrest.core.Is.is;
import java.util.Arrays;
import com.ctco.testSchool.Member.type;
import org.junit.Assert;
import org.junit.Test;
public class WhiteBoxTesting {
Team myTeam = new Team();
@Test
public void testCanDeliverQualityPositiveHappyPath() {
Member first_qa = new Member(type.TEST);
myTeam.addMember(first_qa);
first_qa.setVelocity(0.5);
Story first_story = new Story();
first_story.setTestPoints(2);
Story second_story = new Story();
second_story.setTestPoints(3);
myTeam.backlog = Arrays.asList(first_story, second_story);
Assert.assertThat("Can't be delivered. Team velocity is less than Tess Points", myTeam.canDeliverQuality(), is(true));
}
// defect
@Test
public void testCanDeliverQualityNegative() {
Member first_qa = new Member(type.TEST);
myTeam.addMember(first_qa);
first_qa.setVelocity(0.5);
Story first_story = new Story();
first_story.setTestPoints(3);
Story second_story = new Story();
second_story.setTestPoints(3);
myTeam.backlog = Arrays.asList(first_story, second_story);
Assert.assertThat("Inccorect. Team velocity is less than Story points", myTeam.canDeliverQuality(), is(false));
}
@Test
public void testCanDeliverQualityPositiveNegativeValue() {
Member first_qa = new Member(type.TEST);
myTeam.addMember(first_qa);
first_qa.setVelocity(0.5);
Story first_story = new Story();
first_story.setTestPoints(-5);
Story second_story = new Story();
second_story.setTestPoints(-3);
myTeam.backlog = Arrays.asList(first_story, second_story);
Assert.assertThat("Can't be delivered. Team velocity is less than Story points", myTeam.canDeliverQuality(), is(true));
}
// Is it correct behaviour
@Test
public void testCanDeliverQualityPositiveWithoutStoryInBacklog() {
Member first_qa = new Member(type.TEST);
myTeam.addMember(first_qa);
first_qa.setVelocity(0.5);
Story first_story = new Story();
first_story.setTestPoints(5);
Story second_story = new Story();
second_story.setTestPoints(3);
myTeam.backlog = Arrays.asList();
Assert.assertThat("Can't be delivered. Team velocity is less than Story points", myTeam.canDeliverQuality(), is(true));
}
// Defect?
@Test
public void testCanDeliverQualityPositiveWithTwoTesters() {
Member first_qa = new Member(type.TEST);
first_qa.setVelocity(0.5);
myTeam.addMember(first_qa);
Member second_qa = new Member(type.TEST);
myTeam.addMember(second_qa);
second_qa.setVelocity(1.0);
Story first_story = new Story();
first_story.setTestPoints(5);
Story second_story = new Story();
second_story.setTestPoints(11);
myTeam.backlog = Arrays.asList(first_story,second_story);
Assert.assertThat("Can't be delivered. Team velocity is less than Story points", myTeam.canDeliverQuality(), is(false));
}
}
|
Python
|
UTF-8
| 1,403
| 3.609375
| 4
|
[] |
no_license
|
"""
Written by: S Divakar Bhat
Roll No: 18307R004
Title: CS763-Lab1-numpy-row_manipulation
"""
import argparse
import numpy as np
def permute_matrix(N):
eye = np.identity(N)
P = np.zeros((N,N))
if N%2==0:
idx = N//2
else:
idx = N//2+1
P[0::2] = eye[:idx]
P[1::2] = eye[idx:]
return P
def crop_array(arr_2d, offset_height, offset_width, target_height, target_width):
cropped_array = arr_2d[offset_height:offset_height+target_height,offset_width:offset_width+target_width]
return cropped_array
def pad_array(arr_2d, padder, pad_width):
m,n = np.shape(arr_2d)
padded_array = np.full((m+(2*pad_width),n+(2*pad_width)),padder)
padded_array[pad_width:m+pad_width,pad_width:n+pad_width]=arr_2d
return padded_array
def concat_array(arr_2d):
return np.hstack((arr_2d,arr_2d))
if __name__=='__main__':
parse = argparse.ArgumentParser('row_manipulation')
parse.add_argument('--N', type=int)
args = parse.parse_args()
P = permute_matrix(args.N)
print("Original array:\n",P)
cropped_array = crop_array(P,1,1,2,2)
print("\nCropped array:\n",cropped_array)
padded_array = pad_array(cropped_array,0.5,2)
print("\nPadded array:\n",padded_array)
concatenated_array = concat_array(padded_array)
print("\nConcatenated array: shape={}\n{}".format(np.shape(concatenated_array),concatenated_array))
|
C#
|
UTF-8
| 1,290
| 3.78125
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _04_GenericSwapMethodInteger
{
class GenericSwapMethodIntegerStartUp
{
static void Main(string[] args)
{
List<Box<int>> listOfBoxes = new List<Box<int>>();
int numberOfLines = int.Parse(Console.ReadLine());
for (int i = 0; i < numberOfLines; i++)
{
int intLine = int.Parse(Console.ReadLine());
Box<int> intBox = new Box<int>(intLine);
listOfBoxes.Add(intBox);
}
var swapIndxs = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
int index1 = swapIndxs[0];
int index2 = swapIndxs[1];
SwapInts(listOfBoxes, index1, index2);
foreach (Box<int> box in listOfBoxes)
{
Console.WriteLine(box);
}
}
private static void SwapInts<T>(List<Box<T>> listOfBoxes, int index1, int index2)
{
Box<T> tempBox = listOfBoxes[index1];
listOfBoxes[index1] = listOfBoxes[index2];
listOfBoxes[index2] = tempBox;
}
}
}
|
Markdown
|
UTF-8
| 23,813
| 3.59375
| 4
|
[
"Apache-2.0"
] |
permissive
|
# Basics, algorithms
Welcome to the first jupyter notebook! In this session, we won't go into too many minute details yet, but will cover the basics of machine learning. We've tried to keep it as simple as possible, also because many might only have little experience with python and/or programming a 'learning machine'. If it looks like you're gonna be through the content of this notebook in ten minutes or so, because you're already familiar with all of its concepts, then feel free to challenge yourself a little more by making your own adjustments to the code, diving deeper into advanced topics or doing some last-minute preparations for your group presentations.
## Setup
To allow the next code blocks to run smoothly, this section sets a couple of settings.
Some imports that we will be using:
```python
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
```
Set the random seed to a fixed number. This will guarantee that the notebook output is generated the same way for every run, otherwise the seed would be – random, as the name suggests.
```python
np.random.seed(42)
```
Set the numpy output precision for some prettier numbers:
```python
np.set_printoptions(precision=3, suppress=True)
```
Some figure plotting settings: increase the axis labels of our figures a bit.
```python
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
```
## Linear regression with the normal equation
Let's start with something simple: linear regression. As we've learnt before, we can use the _normal equation_ to calculate a prediction. In statistics, we usually label this as $\hat{\theta}$, because it is an estimator for the parameter vector $\theta$ of the model. The hat indicates that it's an estimator.
First we need to generate some random data.
```python
m = 100 # number of data points
X = 2 * np.random.rand(m, 1)
y = 3 + 4 * X + np.random.randn(m, 1)
```
And let's plot it to get an idea what we're looking at. Of course, we do things the proper way, and put labels on our axes!
```python
plt.plot(X, y, ".")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.axis([0, 2, 0, 15])
plt.show()
```

We can also print a few of the generated data values, just to get an idea what we're talking about. The following command shows us the first three entries of the object `X` that we just generated:
```python
X[0:3]
```
array([[0.749],
[1.901],
[1.464]])
And this shows us the first three corresponding entries in the object `y`:
```python
y[0:3]
```
array([[ 6.083],
[10.307],
[ 8.948]])
Looks good. Reminder: what is the normal equation? And what are `X` and `y`?
$$ \hat{\theta} = \left( \mathbf{X}^T \cdot \mathbf{X} \right)^{-1} \cdot \mathbf{X}^T \cdot \mathbf{y} $$
Quick refresher if your mathematics is a littley rusty:
* $\hat{\theta}$ is our estimator for the vector of parameter $\theta$. This is what we want to calculate!
* $\mathbf{x}^{(i)}$, beware that it's lower-case, is a vector which contains all features of the training instance with index i. In the data generated above, we only have one 'feature', which is called $x_1$. So, $\mathbf{x}^{(0)}$, the feature vector of instance number zero, includes one single value: the value of $x_1$ for that instance, as printed out with the commands above.
* $\mathbf{X}$, now it's upper-case, is a vector of _all feature vectors_ $\mathbf{x}^{(i)}$. To make things more confusing, the entries of $\mathbf{X}$ are actually not $\mathbf{x}^{(i)}$, but the transposed vectors $(\mathbf{x}^{(i)})^T$.
* $\mathbf{y}$ are the _true_ target values of the instances. So, this is also a vector with the same dimension as $\mathbf{X}$. But even in more complicated input data structures, every entry of the target vector will just be the one target value.
Now, what can we do with the normal equation? And what _is_ actually this $\theta$? It's our vector of model parameters. The above case is very simple: we would like to create a model that represents the data as well as possible. With just looking at the plot, and without too much thinking, it's obvious that there is some sort of linear dependence between $x_1$ and $y$.
How many parameters do we need to describe this model? Probably two: one for the linear dependence, and one _bias term_ to shift the entire model along the y axis. So, our $\theta$ in this case is just a vector of two entries, and the goal of 'linear regression' is to find the optimal values of the two. And actually, if you scroll back up for a bit, you can already see the linear dependence, when we generated the data:
$$ y(x_1) = 3 + 4 \cdot x_1 $$
But let's pretend we don't know that ... Without using any machine learning yet, we can just use the above normal equation to get estimators for the two values. For that, we can make use of numpy's `linalg.inv()` function to invert matrices. Essentially, we then just need to 'type' the above formula into python and let our computer do the rest. Easy, right?
One more step is necessary: we need to append an additional feature $x_0 = 1$ to all instances, because otherwise we would ignore the bias parameter in our calculation:
```python
X_b = np.c_[np.ones((m, 1)), X]
```
Cool. Now, here's the typed-out formula for calculating the normal equation. It only uses numpy functions, such as the matrix inversion, or the calculation of dot products:
```python
theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
```
How do we know it worked? One easy thing is to check what the values of the two parameters are:
```python
print("theta_0 = %.3f" % theta[0][0])
print("theta_1 = %.3f" % theta[1][0])
```
theta_0 = 3.215
theta_1 = 3.770
Ok, that's not perfect, but close. Where does the difference come from? Probably from the fact that our data 'only' consists of 100 data points. the more data points we use, the closer we get to the values that we used to generate the data with.
Maybe it is also useful to plot the prediction as a line into the plot. For that, we should first calculate the predictions for the value of `y` for all our instances:
```python
y_predict = X_b.dot(theta)
```
And now we can do the plotting:
```python
plt.plot(X, y, ".")
plt.plot(X, y_predict, "-", linewidth=2, label="Predictions")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.legend(loc="upper right", fontsize=14)
plt.axis([0, 2, 0, 15])
plt.show()
```

Great! As a quick summary: we generated random data in python, determined an appropriate model to represent that data (by eye-balling very carefully), and used the normal equation to get estimators for our model parameters. Now, let's start with some actual machine learning.
## Linear regression using batch gradient descent
Let's try and implement the first machine-learning algorithm to solve our linear-regression problem: batch gradient descent. Quick reminder: gradient descent is an iterative approach to find $\hat{\theta}$. Using the learning rate $\eta$, we adjust our estimates for $\theta$ in each learning step iteratively. The "direction" of adjustment is determined by the _gradient_ of the mean square error.
Maybe we should have a quick revision of the formula:
$$ \mathit{MSE}(\theta) = \frac{1}{m} \sum_{i=1}^{m} \left( \theta^T \cdot \mathbf{x}^{(i)} - y^{(i)} \right)^2 $$
Now, most of you will probably know that the gradient of this function just means taking the derivative of it with respect to $\theta_1,\dots,\theta_n$. To refresh your memory, let's write down the formula for the partial derivative as well:
$$ \frac{\partial}{\partial \theta_j} \mathit{MSE}(\theta) = \frac{2}{m} \sum_{i=1}^{m} \left( \theta^T \cdot \mathbf{x}^{(i)} - y^{(i)} \right) x_j^{(i)}$$
Then, the entire gradient is:
$$ \nabla_\theta \mathit{MSE}(\theta) = \frac{2}{m} \mathbf{X}^T \cdot \left( \mathbf{X} \cdot \theta - \mathbf{y} \right) $$
Now it's really just one last step missing: we need to calculate our predictions for $\theta$. For the very first step, we start with random values of $\theta$. Then, after calculating the gradient above for a step, we update the value of $\theta$ according to:
$$ \theta \rightarrow \theta - \eta \nabla_\theta \mathit{MSE}(\theta) $$
That wasn't too hard, was it? Writing this out with python is even easier. Let's start with setting a learning rate $\eta$:
```python
eta = 0.1
```
Then, we also need to decide how many steps of calculations we would like to perform:
```python
n_iterations = 1000
```
And initialise our $\theta$ with random values:
```python
theta = np.random.randn(2,1) # let's start with random values
```
Then, it's really just creating a small loop and implementing the calculation of the gradients, and then updating $\theta$:
```python
for iteration in range(n_iterations):
gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
theta = theta - eta * gradients
```
Cool, but did it do anything? We should probably check the values for $\theta$ once again:
```python
print("theta_0 = %.3f" % theta[0][0])
print("theta_1 = %.3f" % theta[1][0])
```
theta_0 = 3.215
theta_1 = 3.770
You might be surprised to see that these values basically are _exactly_ the same as those obtained with the normal equation. That's because our estimate, as much as before, completely depends on the data points we fed into the model. You can go to the earlier cells, change some of the parameters, and run the code again. Does anything change, for example when adjusting to use a larger/smaller dataset (the `m` parameter)?
Now, the implementation of batch gradient descent looks rather simple, but it's really not that obvious what happens in each step of the iteration. Remember: we look at the data points one thousand times, calculate some gradient one thousand times, update our estimate for $\theta$ one thousand times, and only see the final result of that final step.
Ignore the details of the following code (unless you're really interested of course). But here's what it does: we repeat the batch gradient descent method on the same dataset as before, but with different learning rates. When you execute the code, you'll see that the model with a very low learning rate only very slowly 'approaches' the dataset. The second one seems to be a lot faster in comparison. The third one, however, 'overshooots' the data with its very large learning rate. The model still converges, but it jumps around quite a bit.
```python
# Store the path of BGD, we'll need that later.
theta_path_bgd = []
def plot_gradient_descent(theta, eta, theta_path=None):
plt.plot(X, y, ".")
n_iterations = 1000
thetas = []
for iteration in range(n_iterations):
if iteration < 15:
y_predict = X_b.dot(theta)
plt.plot(X, y_predict, color='#ff7f0e', alpha=0.2+0.06*iteration)
gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
theta = theta - eta * gradients
thetas.append(theta)
# Again, this is just for later. If a path is provided,
# store it to visualise it in comparison to SGD and MBGD.
if theta_path is not None: theta_path.append(theta)
plt.xlabel("$x_1$", fontsize=18)
plt.axis([0, 2, 0, 15])
plt.title(r"$\eta = {}$".format(eta), fontsize=16)
return thetas
np.random.seed(42)
theta = np.random.randn(2,1)
plt.figure(figsize=(12,8))
plt.subplot(231)
plt.ylabel("$y$", rotation=0, fontsize=18)
predictions_002 = plot_gradient_descent(theta, eta=0.02)
plt.subplot(232)
predictions_010 = plot_gradient_descent(theta, eta=0.1, theta_path=theta_path_bgd)
plt.subplot(233)
predictions_040 = plot_gradient_descent(theta, eta=0.4)
plt.subplot(234)
plt.axis([0, 30, 0, 6])
plt.xlabel("$n_{iterations}$", fontsize=18)
plt.ylabel("$\\theta_0$, $\\theta_1$", fontsize=18)
plt.plot([i[0] for i in predictions_002])
plt.plot([i[1] for i in predictions_002])
plt.subplot(235)
plt.axis([0, 30, 0, 6])
plt.xlabel("$n_{iterations}$", fontsize=18)
plt.plot([i[0] for i in predictions_010])
plt.plot([i[1] for i in predictions_010])
plt.subplot(236)
plt.axis([0, 30, 0, 6])
plt.xlabel("$n_{iterations}$", fontsize=18)
plt.plot([i[0] for i in predictions_040])
plt.plot([i[1] for i in predictions_040])
plt.show()
```

Try out different learning rates and see what happens. You'll notice that – at very large rates – the model won't converge.
## Stochastic Gradient Descent
At this point, you'll probably know about the most problematic aspect of BGD already: we always evaluate the _entire_ dataset at every step of the training process. That's perfect for smaller datasets, because the model will usually find the 'best' estimate for $\theta$ possible (similar to what the normal equation does). However, this is not very feasible for huge datasets.
An alternative in that case is the _stochastic gradient descent_ (SGD) method. As opposed to batch gradient descent, the stochastic technique picks one instance from the dataset _randomly_ and adjusts the estimate for $\theta$ according to that instance. This means _a lot_ of jumping around, because we follow the randomness of individual instances. On the other hand, it's computationally very inexpensive. And if it's done right, it can still find the 'best' estimate possible. However, it will _never_ converge to that 'best' estimate per se. One common technique to overcome this problem is to adjust the learning rate according to a _schedule_ during the training process. That is, start with a high learning rate and decrease it constantly to help the model to 'settle' in the global minimum.
Back to hands-on experience. Let's first decide for how many _epochs_ we would like to evaluate. The idea for this is that, despite an instance being picked randomly at every step, we would still want to evaluate them in sets of a certain size (which is usually just the size of the training data). Once we did, we call that an epoch and jump to the next one.
```python
n_epochs = 50
```
Then, we should implement this learning-rate scheduling, because otherwise our model would not converge. Let's write a simple function to return a learning rate with two parameters:
```python
t0, t1 = 5, 50
def learning_schedule(t):
return t0 / (t + t1)
```
Once again, we'll have to initialise our $\theta$ randomly before the first calculation:
```python
theta = np.random.randn(2,1)
```
Then we can do the actual implementation of the loops:
```python
# Create a loop over the number of epochs.
for epoch in range(n_epochs):
# And a loop over the size of the training data.
for i in range(m):
# Pick a random instance: this function takes
# a random value in the range from 0 to m.
random_index = np.random.randint(m)
# Now, store this random instance and its target
# value into the variables xi and yi ...
xi = X_b[random_index:random_index+1]
yi = y[random_index:random_index+1]
# ... and calculate gradients and theta as before.
# Remember to calculate the value of the learning
# rate from the learning-rate schedule defined
# above (epoch * m + i) is just the number of the
# current training step over all epochs.
gradients = 2 * xi.T.dot(xi.dot(theta) - yi)
eta = learning_schedule(epoch * m + i)
theta = theta - eta * gradients
```
We should probably check the values for $\theta$ once again:
```python
print("theta_0 = %.3f" % theta[0][0])
print("theta_1 = %.3f" % theta[1][0])
```
theta_0 = 3.208
theta_1 = 3.742
Great, it worked! The result seems to be similar, but not the same as before. Try changing some of the parameters. For instance, increase the number of epochs. Will we eventually reach the values from before? Remember: once we reach one thousand (!) epochs, we will have seen the same number of instances as if we had done one thousand iteration steps in the BGD method. Another thing you could try: change the learning-rate schedule (for example: turn it off).
As an alternative, we can also use the _Scikit Learn_ library for stochastic gradient descent. Scikit Learn provides a plethora of functions and implementation of machine-learning models, and we will keep using it in more examples later. Of course, it might sometimes be helpful to implement algorithms yourself, but taking them from a library with dozens of experts working on them every day, doesn't sound too bad of an idea either.
For stochastic gradient descent, Scikit Learn provides a class called [SGDRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDRegressor.html). The good thing about this class is that we can just give it a bunch of parameters (many others will also be set by default), and then the class is ready to do exactly what we need.
First, we need to _import_ the class from Scikit Learn, then we can _instantiate_ it:
```python
from sklearn.linear_model import SGDRegressor
sgd_reg = SGDRegressor(max_iter=50, eta0=0.1, penalty=None)
```
We have already set a few parameters up there: we would like fifty epochs, and start with a learning rate $\eta$ of 0.1. The Scikit Learn implementation uses learning-rate scheduling by default. We also need to set `penalty` explicitly, because otherwise Scikit Learn would otherwise use $\ell_2$ regularisation.
Then, the only thing left is to perform the actual training, by giving it our training data (this will also show you all parameters of our model):
```python
sgd_reg.fit(X, y.ravel())
```
SGDRegressor(eta0=0.1, max_iter=50, penalty=None)
And what does it predict?
```python
print("theta_0: %.3f" % sgd_reg.intercept_[0])
print("theta_1: %.3f" % sgd_reg.coef_[0])
```
theta_0: 3.215
theta_1: 3.766
To visualise the randomness of SGD, let's create some plot again. Again, you may just ignore the details of the following code:
```python
theta_path_sgd = []
theta = np.random.randn(2,1)
n_epochs = 50
t0, t1 = 10, 50
def learning_schedule(t):
return t0 / (t + t1)
thetas = []
plt.figure(figsize=(12,6))
plt.subplot(121)
plt.plot(X, y, ".")
for epoch in range(n_epochs):
for i in range(m):
if epoch == 0 and i < 10:
y_predict = X_b.dot(theta)
plt.plot(X, y_predict, color='#ff7f0e', alpha=0.2+0.06*i)
random_index = np.random.randint(m)
xi = X_b[random_index:random_index+1]
yi = y[random_index:random_index+1]
gradients = 2 * xi.T.dot(xi.dot(theta) - yi)
eta = learning_schedule(epoch * m + i)
theta = theta - eta * gradients
thetas.append(theta)
if epoch == 0 and i < 200: theta_path_sgd.append(theta)
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.axis([0, 2, 0, 15])
plt.subplot(122)
plt.plot([i[0] for i in thetas])
plt.plot([i[1] for i in thetas])
plt.axis([0, 500, 1, 7])
plt.xlabel("$n_{iterations}$", fontsize=18)
plt.ylabel("$\\theta_0$, $\\theta_1$", fontsize=18)
plt.show()
```

## Mini-batch gradient descent
By 'taking the best of both worlds', the _mini-batch gradient descent_ might be the perfect compromise between BGD and SGD. Instead of taking all or just one instance, the gradient is evaluated on a _mini-batch_ of instances. This makes it a little more stable than SGD, especially with large mini-batches. And it allows for vectorisation optimisations in terms of computing. It has the same 'issue' as SGD, however, that it never stops at the optimal values for the estimators, but keeps jumping around the global minimum. Therefore, a good learning schedule is pivotal to implement this technique successfully.
Let's first fix some parameters: the number of epochs, and the size of the mini batches:
```python
n_epochs = 50
minibatch_size = 20
```
Then, implement learning-rate scheduling as before:
```python
t0, t1 = 200, 1000
def learning_schedule(t):
return t0 / (t + t1)
```
Make sure to initialise the values of $\theta$ randomly in the beginning:
```python
theta = np.random.randn(2,1)
```
A small helper function to give us randomly shuffled instances. We shuffle the instances for every new epoch to make sure we will always look at 'new' mini batches for every epoch. Otherwise, we would end up looking at all instances in the same order in all epochs.
```python
def shuffled_instances(m, X_b, y):
shuffled_indices = np.random.permutation(m)
return X_b[shuffled_indices], y[shuffled_indices]
```
Now we can do the actual looping:
```python
# Count the number of steps for the learning-rate schedule.
step = 0
# Loop over all epochs.
for epoch in range(n_epochs):
# Start off every epoch by shuffling around the instances.
X_b_shuffled, y_shuffled = shuffled_instances(m, X_b, y)
# Loop over all instances in mini batches.
for i in range(0, m, minibatch_size):
step += 1
# Before we can calculate the gradients, make sure we
# get the mini-batch subset of instances.
xi = X_b_shuffled[step:step+minibatch_size]
yi = y_shuffled[step:step+minibatch_size]
# Then, calculate the gradient and update theta as before.
gradients = 2/minibatch_size * xi.T.dot(xi.dot(theta) - yi)
eta = learning_schedule(step)
theta = theta - eta * gradients
```
And what are the predicted values of the parameters?
```python
print("theta_0: %.3f" % theta[0][0])
print("theta_1: %.3f" % theta[1][0])
```
theta_0: 3.179
theta_1: 3.507
The following code won't produce any output, but please run it quickly for the last part of this notebook.
```python
theta_path_mgd = []
n_iterations = 50
minibatch_size = 20
np.random.seed(42)
theta = np.random.randn(2,1)
t0, t1 = 200, 1000
def learning_schedule(t):
return t0 / (t + t1)
step = 0
for epoch in range(n_iterations):
shuffled_indices = np.random.permutation(m)
X_b_shuffled = X_b[shuffled_indices]
y_shuffled = y[shuffled_indices]
for i in range(0, m, minibatch_size):
step += 1
xi = X_b_shuffled[step:step+minibatch_size]
yi = y_shuffled[step:step+minibatch_size]
gradients = 2/minibatch_size * xi.T.dot(xi.dot(theta) - yi)
eta = learning_schedule(step)
theta = theta - eta * gradients
theta_path_mgd.append(theta)
```
## Comparing BGD, SGD and mini-batch GD
We're almost done, but let's quickly have a look at what the algorithms actually do in the parameter space. The following code produces a plot that points out every step the batch gradient descent, stochastic gradient descent, and mini-batch gradient descent methods took. Do you spot any differences?
```python
theta_path_bgd = np.array(theta_path_bgd)
theta_path_sgd = np.array(theta_path_sgd)
theta_path_mgd = np.array(theta_path_mgd)
plt.figure(figsize=(7,4))
plt.plot(theta_path_sgd[:, 0], theta_path_sgd[:, 1], "-s", linewidth=1, label="Stochastic")
plt.plot(theta_path_mgd[:, 0], theta_path_mgd[:, 1], "-+", linewidth=2, label="Mini-batch")
plt.plot(theta_path_bgd[:, 0], theta_path_bgd[:, 1], "-o", linewidth=3, label="Batch")
plt.legend(loc="upper left", fontsize=16)
plt.xlabel(r"$\theta_0$", fontsize=20)
plt.ylabel(r"$\theta_1$ ", fontsize=20, rotation=0)
plt.axis([1.0, 4.0, 2.5, 6.0])
plt.show()
```

```python
```
|
Shell
|
UTF-8
| 366
| 2.609375
| 3
|
[] |
no_license
|
#!/bin/bash
#Change Timezone in Linux
sudo mv /etc/localtime /etc/localtime.bk
sudo cp /usr/share/zoneinfo/Asia/Ho_Chi_Minh /etc/localtime
#Change Date and Time in Linux
#date MMDDhhmmYYYY
# Sync your system time and date with ntp (Network Time Protocol) over internet
sudo yum install -y ntp
sudo chkconfig ntpd on
sudo ntpdate pool.ntp.org
/etc/init.d/ntpd start
|
Java
|
UTF-8
| 14,295
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package info.mornlight.gw2s.android.app;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.*;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import info.mornlight.gw2s.android.R;
import info.mornlight.gw2s.android.model.item.Discipline;
import info.mornlight.gw2s.android.ui.ItemListAdapter;
import info.mornlight.gw2s.android.ui.ItemView;
import java.util.Arrays;
/**
* Created by alfred on 5/24/13.
*/
public class RecipesActivity extends BaseActivity {
protected RecipesFragment fragment;
@InjectView(R.id.menu)
protected ListView menu;
private ItemsMenuAdapter adapter;
@InjectView(R.id.drawer)
protected DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes_activity);
fragment = (RecipesFragment) getFragmentManager().findFragmentById(R.id.fragment);
ButterKnife.inject(this);
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.recipes);
initializeSlidingMenu();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recipes_activity, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.m_menu:
if(drawer.isDrawerOpen(menu)) {
drawer.closeDrawer(menu);
} else {
drawer.openDrawer(menu);
}
break;
}
return super.onOptionsItemSelected(item);
}
class ItemsMenuItem {
Discipline discipline;
String type;
String text;
ItemsMenuItem(Discipline discipline, String text) {
this.discipline = discipline;
this.text = text;
}
ItemsMenuItem(Discipline discipline, String type, String text) {
this.discipline = discipline;
this.text = text;
this.type = type;
}
}
class ItemsMenuView extends ItemView<ItemsMenuItem> {
private TextView text;
public ItemsMenuView(View view) {
super(view);
text = (TextView) view.findViewById(R.id.text);
}
@Override
public void update(ItemsMenuItem item) {
super.update(item);
text.setText(item.text);
}
}
class ItemsMenuAdapter extends ItemListAdapter<ItemsMenuItem, ItemsMenuView> {
public ItemsMenuAdapter(LayoutInflater inflater) {
super(0, inflater);
}
@Override
protected ItemsMenuView createView(int position, View view) {
return new ItemsMenuView(view);
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
@SuppressWarnings("unchecked")
ItemsMenuView view = convertView != null ? (ItemsMenuView) convertView.getTag() : null;
ItemsMenuItem item = getItem(position);
if (view == null || view.getItem().type != item.type) {
if(item.type == null) {
convertView = inflater.inflate(R.layout.slidingmenu_group, null);
} else {
convertView = inflater.inflate(R.layout.slidingmenu_item, null);
}
view = createView(position, convertView);
convertView.setTag(view);
}
update(position, view, getItem(position));
return convertView;
}
}
/*
use this to get all llRecipe discipline and types from database
select distinct type, discipline from gw2s_recipes join gw2s_recipes_disciplines on gw2s_recipes.id=gw2s_recipes_disciplines.id order by discipline
*/
private void initializeSlidingMenu() {
//ListView menuView = (ListView) getLayoutInflater().inflate(R.layout.items_activity_sliding_menu, null);
ItemsMenuItem[] menuItems = new ItemsMenuItem[] {
new ItemsMenuItem(Discipline.Armorsmith, getString(R.string.armorsmith)),
new ItemsMenuItem(Discipline.Armorsmith, "Bag", getString(R.string.bag)),
new ItemsMenuItem(Discipline.Armorsmith, "Boots", getString(R.string.boots)),
new ItemsMenuItem(Discipline.Armorsmith, "Bulk", getString(R.string.bulk)),
new ItemsMenuItem(Discipline.Armorsmith, "Coat", getString(R.string.coat)),
new ItemsMenuItem(Discipline.Armorsmith, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Armorsmith, "Gloves", getString(R.string.gloves)),
new ItemsMenuItem(Discipline.Armorsmith, "Helm", getString(R.string.helm)),
new ItemsMenuItem(Discipline.Armorsmith, "Insignia", getString(R.string.insignia)),
new ItemsMenuItem(Discipline.Armorsmith, "Leggings", getString(R.string.leggings)),
new ItemsMenuItem(Discipline.Armorsmith, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Armorsmith, "Shoulders", getString(R.string.shoulders)),
new ItemsMenuItem(Discipline.Armorsmith, "UpgradeComponent", getString(R.string.upgrade_component)),
new ItemsMenuItem(Discipline.Artificer, getString(R.string.artificer)),
new ItemsMenuItem(Discipline.Artificer, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Artificer, "Consumable", getString(R.string.consumable)),
new ItemsMenuItem(Discipline.Artificer, "Focus", getString(R.string.focus)),
new ItemsMenuItem(Discipline.Artificer, "Inscription", getString(R.string.inscription)),
new ItemsMenuItem(Discipline.Artificer, "Potion", getString(R.string.potion)),
new ItemsMenuItem(Discipline.Artificer, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Artificer, "Scepter", getString(R.string.scepter)),
new ItemsMenuItem(Discipline.Artificer, "Staff", getString(R.string.staff)),
new ItemsMenuItem(Discipline.Artificer, "Trident", getString(R.string.trident)),
new ItemsMenuItem(Discipline.Artificer, "UpgradeComponent", getString(R.string.upgrade_component)),
new ItemsMenuItem(Discipline.Chef, getString(R.string.chef)),
new ItemsMenuItem(Discipline.Chef, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Chef, "Dessert", getString(R.string.dessert)),
new ItemsMenuItem(Discipline.Chef, "Dye", getString(R.string.dye)),
new ItemsMenuItem(Discipline.Chef, "Feast", getString(R.string.feast)),
new ItemsMenuItem(Discipline.Chef, "IngredientCooking", getString(R.string.ingredient_cooking)),
new ItemsMenuItem(Discipline.Chef, "Meal", getString(R.string.meal)),
new ItemsMenuItem(Discipline.Chef, "Seasoning", getString(R.string.seasoning)),
new ItemsMenuItem(Discipline.Chef, "Snack", getString(R.string.snack)),
new ItemsMenuItem(Discipline.Chef, "Soup", getString(R.string.soup)),
new ItemsMenuItem(Discipline.Huntsman, getString(R.string.huntsman)),
new ItemsMenuItem(Discipline.Huntsman, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Huntsman, "Consumable", getString(R.string.consumable)),
new ItemsMenuItem(Discipline.Huntsman, "Inscription", getString(R.string.inscription)),
new ItemsMenuItem(Discipline.Huntsman, "LongBow", getString(R.string.longbow)),
new ItemsMenuItem(Discipline.Huntsman, "Pistol", getString(R.string.pistol)),
new ItemsMenuItem(Discipline.Huntsman, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Huntsman, "Rifle", getString(R.string.rifle)),
new ItemsMenuItem(Discipline.Huntsman, "ShortBow", getString(R.string.short_bow)),
new ItemsMenuItem(Discipline.Huntsman, "Speargun", getString(R.string.spear_gun)),
new ItemsMenuItem(Discipline.Huntsman, "Torch", getString(R.string.torch)),
new ItemsMenuItem(Discipline.Huntsman, "UpgradeComponent", getString(R.string.upgrade_component)),
new ItemsMenuItem(Discipline.Huntsman, "Warhorn", getString(R.string.warhorn)),
new ItemsMenuItem(Discipline.Jeweler, getString(R.string.jeweler)),
new ItemsMenuItem(Discipline.Jeweler, "Amulet", getString(R.string.amulet)),
new ItemsMenuItem(Discipline.Jeweler, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Jeweler, "Earring", getString(R.string.earring)),
new ItemsMenuItem(Discipline.Jeweler, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Jeweler, "Ring", getString(R.string.ring)),
new ItemsMenuItem(Discipline.Jeweler, "UpgradeComponent", getString(R.string.upgrade_component)),
new ItemsMenuItem(Discipline.Leatherworker, getString(R.string.leatherworker)),
new ItemsMenuItem(Discipline.Leatherworker, "Bag", getString(R.string.bag)),
new ItemsMenuItem(Discipline.Leatherworker, "Boots", getString(R.string.boots)),
new ItemsMenuItem(Discipline.Leatherworker, "Bulk", getString(R.string.bulk)),
new ItemsMenuItem(Discipline.Leatherworker, "Coat", getString(R.string.coat)),
new ItemsMenuItem(Discipline.Leatherworker, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Leatherworker, "Gloves", getString(R.string.gloves)),
new ItemsMenuItem(Discipline.Leatherworker, "Helm", getString(R.string.helm)),
new ItemsMenuItem(Discipline.Leatherworker, "Insignia", getString(R.string.insignia)),
new ItemsMenuItem(Discipline.Leatherworker, "Leggings", getString(R.string.leggings)),
new ItemsMenuItem(Discipline.Leatherworker, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Leatherworker, "Shoulders", getString(R.string.shoulders)),
new ItemsMenuItem(Discipline.Leatherworker, "UpgradeComponent", getString(R.string.upgrade_component)),
new ItemsMenuItem(Discipline.Tailor, getString(R.string.tailor)),
new ItemsMenuItem(Discipline.Tailor, "Bag", getString(R.string.bag)),
new ItemsMenuItem(Discipline.Tailor, "Boots", getString(R.string.boots)),
new ItemsMenuItem(Discipline.Tailor, "Bulk", getString(R.string.bulk)),
new ItemsMenuItem(Discipline.Tailor, "Coat", getString(R.string.coat)),
new ItemsMenuItem(Discipline.Tailor, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Tailor, "Gloves", getString(R.string.gloves)),
new ItemsMenuItem(Discipline.Tailor, "Helm", getString(R.string.helm)),
new ItemsMenuItem(Discipline.Tailor, "Insignia", getString(R.string.insignia)),
new ItemsMenuItem(Discipline.Tailor, "Leggings", getString(R.string.leggings)),
new ItemsMenuItem(Discipline.Tailor, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Tailor, "Shoulders", getString(R.string.shoulders)),
new ItemsMenuItem(Discipline.Tailor, "UpgradeComponent", getString(R.string.upgrade_component)),
new ItemsMenuItem(Discipline.Weaponsmith, getString(R.string.weaponsmith)),
new ItemsMenuItem(Discipline.Weaponsmith, "Axe", getString(R.string.axe)),
new ItemsMenuItem(Discipline.Weaponsmith, "Component", getString(R.string.component)),
new ItemsMenuItem(Discipline.Weaponsmith, "Consumable", getString(R.string.consumable)),
new ItemsMenuItem(Discipline.Weaponsmith, "Dagger", getString(R.string.dagger)),
new ItemsMenuItem(Discipline.Weaponsmith, "Greatsword", getString(R.string.great_sword)),
new ItemsMenuItem(Discipline.Weaponsmith, "Hammer", getString(R.string.hammer)),
new ItemsMenuItem(Discipline.Weaponsmith, "Harpoon", getString(R.string.harpoon)),
new ItemsMenuItem(Discipline.Weaponsmith, "Inscription", getString(R.string.inscription)),
new ItemsMenuItem(Discipline.Weaponsmith, "Mace", getString(R.string.mace)),
new ItemsMenuItem(Discipline.Weaponsmith, "Refinement", getString(R.string.refinement)),
new ItemsMenuItem(Discipline.Weaponsmith, "Shield", getString(R.string.shield)),
new ItemsMenuItem(Discipline.Weaponsmith, "Sword", getString(R.string.sword)),
new ItemsMenuItem(Discipline.Weaponsmith, "UpgradeComponent", getString(R.string.upgrade_component)),
};
adapter = new ItemsMenuAdapter(getLayoutInflater());
adapter.setItems(Arrays.asList(menuItems));
menu.setAdapter(adapter);
menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ItemsMenuItem item = adapter.getItem(position);
onMenuItemClick(item);
}
});
}
private void onMenuItemClick(ItemsMenuItem item) {
drawer.closeDrawer(menu);
fragment.setFilter(item.discipline, item.type);
fragment.refresh();
}
}
|
Java
|
UTF-8
| 338
| 1.78125
| 2
|
[] |
no_license
|
package com.cognitive.newswizard.service.repository;
import java.util.List;
import com.cognitive.newswizard.service.repository.projection.CountRawFeedEntryByPeriodProjection;
public interface RawFeedEntryAggregationRepository {
List<CountRawFeedEntryByPeriodProjection> countRawFeedEntryByPeriod(final Long start, final Long end);
}
|
Swift
|
UTF-8
| 1,833
| 2.90625
| 3
|
[] |
no_license
|
//
// DetailView.swift
// Movie App
//
// Created by protodimbo on 12.05.2021.
//
import UIKit
protocol DetailViewDelegate: AnyObject {
func setupTableViewDelegate() -> UITableViewDelegate
func setupTableViewDataSource() -> UITableViewDataSource
}
final class DetailView: UIView {
// MARK: - Public properties
weak var delegate: DetailViewDelegate? {
didSet {
setupDelegate()
}
}
// MARK: - Private Properties
private(set) var detailTableView: UITableView = {
let table = UITableView()
table.register(
DetailPhotosScrollViewTableViewCell.self,
forCellReuseIdentifier: DetailPhotosScrollViewTableViewCell.identifier
)
table.register(DetailTitleTableViewCell.self, forCellReuseIdentifier: DetailTitleTableViewCell.identifier)
table.register(DetailInfoTableViewCell.self, forCellReuseIdentifier: DetailInfoTableViewCell.identifier)
table.backgroundColor = .systemBackground
return table
}()
// MARK: - View life cycle
override func layoutSubviews() {
backgroundColor = .systemBackground
addSubview(detailTableView)
detailTableView.anchor(
top: topAnchor,
bottom: bottomAnchor,
leading: leadingAnchor,
trailing: trailingAnchor
)
}
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private methods
private func setupDelegate() {
detailTableView.delegate = delegate?.setupTableViewDelegate()
detailTableView.dataSource = delegate?.setupTableViewDataSource()
}
}
|
Python
|
UTF-8
| 4,967
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
from unittest import TestCase
from rest_orm import errors, fields, models
class FieldsTestCase(TestCase):
def test_deserialize_deeply_nested_field(self):
"""Test deserializing a heavily nested field."""
field = fields.AdaptedField('[x][y][z]')
value = field.deserialize({'x': {'y': {'z': 'value'}}})
self.assertTrue(value == 'value')
def test_deserialize_list_item(self):
"""Test deserializing a list item."""
field = fields.AdaptedField('[1]')
value = field.deserialize([1, 2, 3])
self.assertTrue(value == 2)
def test_validate_required(self):
"""Test validating a missing value when required is `True`."""
field = fields.AdaptedField('[x]', required=True)
try:
field.deserialize({'z': 1})
self.assertTrue(False)
except KeyError:
self.assertTrue(True)
def test_replace_missing_value(self):
"""Test replacing a missing value with the specified default."""
field = fields.AdaptedField('[key]', missing='value')
value = field.deserialize({'x': 1})
self.assertTrue(value == 'value')
def test_nullable_field(self):
"""Test skipping validation when field is `None`."""
field = fields.AdaptedDate('[key]', nullable=True)
value = field.deserialize({'key': None})
self.assertTrue(value is None)
def test_validate_deserialized_value(self):
"""Test validating a deserialized value."""
def validate_input(value):
if value > 10:
return
raise errors.AdapterError('Invalid value.')
field = fields.AdaptedField('[x]', validate=validate_input)
try:
field.deserialize({'x': 5})
self.assertTrue(False)
except errors.AdapterError:
self.assertTrue(True)
value = field.deserialize({'x': 11})
self.assertTrue(value == 11)
def test_adapted_boolean_deserialization(self):
"""Test deserializing boolean field."""
field = fields.AdaptedBoolean('[x]')
value = field.deserialize({'x': 1})
self.assertTrue(value is True)
value = field.deserialize({'x': 'hello'})
self.assertTrue(value is True)
value = field.deserialize({'x': True})
self.assertTrue(value is True)
value = field.deserialize({'x': 0})
self.assertTrue(value is False)
value = field.deserialize({'x': ''})
self.assertTrue(value is False)
def test_adapted_date_deserialization(self):
"""Test deserializing date field."""
field = fields.AdaptedDate('[x]')
value = field.deserialize({'x': '2015-01-01'})
self.assertTrue(value.year == 2015)
self.assertTrue(value.month == 1)
self.assertTrue(value.day == 1)
field = fields.AdaptedDate('[x]', date_format='%m/%d/%Y')
value = field.deserialize({'x': '01/01/2015'})
self.assertTrue(value.year == 2015)
self.assertTrue(value.month == 1)
self.assertTrue(value.day == 1)
def test_adapted_decimal_deserialization(self):
"""Test deserializing decimal field."""
from decimal import Decimal
field = fields.AdaptedDecimal('[x]')
value = field.deserialize({'x': '12.50'})
self.assertTrue(value == 12.50)
self.assertTrue(isinstance(value, Decimal))
def test_adapted_integer_deserialization(self):
"""Test deserializing integer field."""
field = fields.AdaptedInteger('[x]')
value = field.deserialize({'x': '1'})
self.assertTrue(value == 1)
def test_adapted_function_deserialization(self):
"""Test deserializing function field."""
field = fields.AdaptedFunction(lambda x: 'value', path='[x]')
value = field.deserialize({'x': 'anything'})
self.assertTrue(value == 'value')
def test_adapted_list_deserialization(self):
"""Test deserializing list field."""
field = fields.AdaptedList('[x]')
value = field.deserialize({'x': 1})
self.assertTrue(value == [1])
value = field.deserialize({'x': ['hi']})
self.assertTrue(value == ['hi'])
def test_adapted_nested_deserialization(self):
"""Test deserializing nested field."""
class Test(models.AdaptedModel):
number = fields.AdaptedInteger('[y]')
field = fields.AdaptedNested(Test, path='[x]')
value = field.deserialize({'x': {'y': 1}})
self.assertTrue(isinstance(value, Test))
self.assertTrue(value.number == 1)
def test_adapted_string_deserialization(self):
"""Test deserializing string field."""
field = fields.AdaptedString('[x]')
value = field.deserialize({'x': 1})
self.assertTrue(value == '1')
value = field.deserialize({'x': True})
self.assertTrue(value == 'True')
|
PHP
|
UTF-8
| 7,647
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
namespace App\Models\Entity;
use Swoft\Db\Model;
use Swoft\Db\Bean\Annotation\Column;
use Swoft\Db\Bean\Annotation\Entity;
use Swoft\Db\Bean\Annotation\Id;
use Swoft\Db\Bean\Annotation\Required;
use Swoft\Db\Bean\Annotation\Table;
use Swoft\Db\Types;
/**
* 动态信息表
* @Entity()
* @Table(name="mallbuilder_sns")
* @uses MallbuilderSns
*/
class MallbuilderSns extends Model
{
/**
* @var int $id ID
* @Id()
* @Column(name="id", type="integer")
*/
private $id;
/**
* @var int $originalId 原ID
* @Column(name="original_id", type="integer", default=0)
*/
private $originalId;
/**
* @var int $originalMemberId 原会员ID
* @Column(name="original_member_id", type="integer", default=0)
*/
private $originalMemberId;
/**
* @var int $originalStatus 原状态
* @Column(name="original_status", type="tinyint", default=0)
*/
private $originalStatus;
/**
* @var int $memberId 会员ID
* @Column(name="member_id", type="integer")
* @Required()
*/
private $memberId;
/**
* @var string $memberName 会员名称
* @Column(name="member_name", type="string", length=100)
* @Required()
*/
private $memberName;
/**
* @var string $title 标题
* @Column(name="title", type="string", length=500)
*/
private $title;
/**
* @var string $content 内容
* @Column(name="content", type="text", length=65535)
* @Required()
*/
private $content;
/**
* @var string $img 图片
* @Column(name="img", type="text", length=65535)
*/
private $img;
/**
* @var int $type 2 pic 3pro 4shop
* @Column(name="type", type="tinyint", default=1)
*/
private $type;
/**
* @var int $createTime 添加时间
* @Column(name="create_time", type="integer")
* @Required()
*/
private $createTime;
/**
* @var int $status 状态
* @Column(name="status", type="tinyint", default=0)
*/
private $status;
/**
* @var int $privacy 隐私可见度 0所有人可见 1好友可见 2仅自己可见
* @Column(name="privacy", type="tinyint", default=0)
*/
private $privacy;
/**
* @var int $commentCount 评论数
* @Column(name="comment_count", type="integer", default=0)
*/
private $commentCount;
/**
* @var int $copyCount 转发数
* @Column(name="copy_count", type="integer", default=0)
*/
private $copyCount;
/**
* ID
* @param int $value
* @return $this
*/
public function setId(int $value)
{
$this->id = $value;
return $this;
}
/**
* 原ID
* @param int $value
* @return $this
*/
public function setOriginalId(int $value): self
{
$this->originalId = $value;
return $this;
}
/**
* 原会员ID
* @param int $value
* @return $this
*/
public function setOriginalMemberId(int $value): self
{
$this->originalMemberId = $value;
return $this;
}
/**
* 原状态
* @param int $value
* @return $this
*/
public function setOriginalStatus(int $value): self
{
$this->originalStatus = $value;
return $this;
}
/**
* 会员ID
* @param int $value
* @return $this
*/
public function setMemberId(int $value): self
{
$this->memberId = $value;
return $this;
}
/**
* 会员名称
* @param string $value
* @return $this
*/
public function setMemberName(string $value): self
{
$this->memberName = $value;
return $this;
}
/**
* 标题
* @param string $value
* @return $this
*/
public function setTitle(string $value): self
{
$this->title = $value;
return $this;
}
/**
* 内容
* @param string $value
* @return $this
*/
public function setContent(string $value): self
{
$this->content = $value;
return $this;
}
/**
* 图片
* @param string $value
* @return $this
*/
public function setImg(string $value): self
{
$this->img = $value;
return $this;
}
/**
* 2 pic 3pro 4shop
* @param int $value
* @return $this
*/
public function setType(int $value): self
{
$this->type = $value;
return $this;
}
/**
* 添加时间
* @param int $value
* @return $this
*/
public function setCreateTime(int $value): self
{
$this->createTime = $value;
return $this;
}
/**
* 状态
* @param int $value
* @return $this
*/
public function setStatus(int $value): self
{
$this->status = $value;
return $this;
}
/**
* 隐私可见度 0所有人可见 1好友可见 2仅自己可见
* @param int $value
* @return $this
*/
public function setPrivacy(int $value): self
{
$this->privacy = $value;
return $this;
}
/**
* 评论数
* @param int $value
* @return $this
*/
public function setCommentCount(int $value): self
{
$this->commentCount = $value;
return $this;
}
/**
* 转发数
* @param int $value
* @return $this
*/
public function setCopyCount(int $value): self
{
$this->copyCount = $value;
return $this;
}
/**
* ID
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* 原ID
* @return int
*/
public function getOriginalId()
{
return $this->originalId;
}
/**
* 原会员ID
* @return int
*/
public function getOriginalMemberId()
{
return $this->originalMemberId;
}
/**
* 原状态
* @return int
*/
public function getOriginalStatus()
{
return $this->originalStatus;
}
/**
* 会员ID
* @return int
*/
public function getMemberId()
{
return $this->memberId;
}
/**
* 会员名称
* @return string
*/
public function getMemberName()
{
return $this->memberName;
}
/**
* 标题
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* 内容
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* 图片
* @return string
*/
public function getImg()
{
return $this->img;
}
/**
* 2 pic 3pro 4shop
* @return mixed
*/
public function getType()
{
return $this->type;
}
/**
* 添加时间
* @return int
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* 状态
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* 隐私可见度 0所有人可见 1好友可见 2仅自己可见
* @return int
*/
public function getPrivacy()
{
return $this->privacy;
}
/**
* 评论数
* @return int
*/
public function getCommentCount()
{
return $this->commentCount;
}
/**
* 转发数
* @return int
*/
public function getCopyCount()
{
return $this->copyCount;
}
}
|
Python
|
UTF-8
| 309
| 3.28125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 5 14:18:30 2017
@author: lenovo
"""
"""
五角星的绘制。绘制一个红色的五角星图形
"""
from turtle import*
fillcolor("red")
begin_fill()
while True:
forward(200)
right(144)
if abs(pos())<1:
break
end_fill()
|
Python
|
UTF-8
| 68
| 3.015625
| 3
|
[] |
no_license
|
import cmath
z = -17
z = z ** (1 / 2)
cmath.sqrt(z)
print(z)
|
Java
|
UTF-8
| 1,036
| 2.296875
| 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 glucosabajocontrol;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
/**
*
* @author W10USER
*/
public class RecoAlimenticiaDP {
String Paciente;
String Alimento;
Date fechaReco;
public RecoAlimenticiaDP(String Paciente, String alimento, Date fechaReco)
{
this.Paciente = Paciente;
this.Alimento = alimento;
this.fechaReco = fechaReco;
}
public void RecomendacionAlimenticia()
{
}
public boolean Guardar() throws IOException, SQLException
{
boolean var = false;
RecoAlimenticiaMD reco = new RecoAlimenticiaMD();
System.out.println(Paciente + " " + Alimento + " " + fechaReco);
var = reco.insertarRecomendacion(Paciente,Alimento,fechaReco);
return var;
}
}
|
C#
|
UTF-8
| 770
| 3.125
| 3
|
[] |
no_license
|
using System;
using System.Reflection;
using CarsPro;
namespace DoReflection
{
class Program
{
static void Main(string[] args)
{
Type mtype = typeof(Car);
Type mytype2 = Type.GetType("CarsPro.LadaSedan,Cars", false, true);
Car newCar = new LadaSedan("model1", "red", 3, "Lada");
if (mytype2 == newCar.GetType())
{
Console.WriteLine("types is equal!!!");
}
MemberInfo[] mInfo = mytype2.GetMembers();
foreach (var item in mInfo)
{
Console.WriteLine($"{item.DeclaringType} {item.MemberType} {item.Name}");
}
Console.ReadKey();
}
}
}
|
PHP
|
UTF-8
| 2,039
| 2.59375
| 3
|
[] |
no_license
|
<?php
declare(strict_types = 1);
namespace Tests\Importers;
use PHPUnit\Framework\TestCase;
/**
* @covers Email
*/
final class FactoryTest extends TestCase {
public function providergetImporter() {
return [
['\\Importers\\CSV', false, 'data.csv'],
['\\Importers\\CSV', false, 'data.CSV'], //check case sensitivity
['\\Importers\\CSV', false, 'data.CsV'],
[null, true, 'data.CsVchunked'],
['\\Importers\\XML', false, 'data.xml'],
['\\Importers\\Yaml', false, 'data.yml'],
['\\Importers\\Yaml', false, 'data.yaml'],
[null, true, 'data.json'],
[null, false, 'data.sausages'],
];
}
/**
* @dataProvider providergetImporter
*/
public function testgetImporter($expectedClass, bool $expectException, string $fileName) {
if ($expectException) {
$this->expectException('\Importers\ImporterException');
}
$importer = \Importers\Factory::getImporter($fileName);
if (!is_null($expectedClass)) {
$this->assertInstanceOf($expectedClass, $importer);
} else {
$this->assertNull($expectedClass, $importer);
}
}
public function providergetFileType()
{
return [
['csv','bob.csv'],
['yaml','bob.yaml'],
['xml','/path/to/data.xml'],
['json','/bonkers.path/to/data.file.json'],
['','bobcsv']
];
}
/**
* @dataProvider providergetFileType
* @param string $expected
* @param string $fileName
*/
public function testgetFileType(string $expected, string $fileName)
{
$sut = $this->createMock('\Importers\Factory');
$class = new \ReflectionClass($sut);
$method = $class->getMethod('getFileType');
$method->setAccessible(true);
$handle = $method->invokeArgs($sut, [$fileName]);
$this->assertSame($expected, $handle);
}
}
|
JavaScript
|
UTF-8
| 2,421
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
const express = require('express')
const app = express()
const port = 3001
app.use(express.json());
treeInfo = {
heap: 31496,
ssid: "",
ap_address: "192.168.4.1",
pin: 2,
leds: 10,
current: 10,
current_index: 10,
current_name: "Multiple Falling Stars",
random: true,
override_index: -1,
"sequences": [
"Cylon",
"Rocket",
"Falling Star",
"Rainbow",
"Stripes",
"Theatre Chase",
"Fade",
"Colour Wipe",
"Rocket Both Ends",
"Heartbeats",
"Multiple Falling Stars",
"Fire"
]
};
ringInfo = {
heap: 34664,
ssid: "",
ap_address: "192.168.4.1",
pin: 5,
leds: 24,
current: 3,
current_index: 0,
current_name: "Rainbow",
random: false,
override_index: -1,
sequences: [
"Rainbow",
"Fade",
"Colour Wipe",
"Rocket Both Ends",
"Heartbeats",
"Multiple Falling Stars",
"Fire"
]
};
app.get('/', function (req, res) {
res.send('hello world')
});
app.get('/get', (req, res) => {
console.log("getting " + req.query.what);
if(req.query.what == "tree"){
res.json(treeInfo);
}else if(req.query.what == "ring"){
res.json(ringInfo);
}
});
app.post('/set', (req, res) => {
console.log("setting " + req.query.what + " " + req.body);
if(req.query.what == "tree"){
treeInfo.current_index = req.body.current_index;
treeInfo.random = req.body.random;
treeInfo.override_index = req.body.override_index;
treeInfo.sequences = req.body.sequences;
res.json(treeInfo);
}else if(req.query.what == "ring"){
ringInfo.current_index = req.body.current_index;
ringInfo.random = req.body.random;
ringInfo.override_index = req.body.override_index;
ringInfo.sequences = req.body.sequences;
res.json(ringInfo);
}
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
setInterval(() => {
if(treeInfo.override_index === -1){
treeInfo.current_index++;
if(treeInfo.current_index >= treeInfo.sequences.length){
treeInfo.current_index = 0;
}
treeInfo.current = treeInfo.current_index;
}
if(ringInfo.override_index === -1){
ringInfo.current_index++;
if(ringInfo.current_index >= ringInfo.sequences.length){
ringInfo.current_index = 0;
}
ringInfo.current = ringInfo.current_index;
}
console.log(treeInfo.current_index, ringInfo.current_index);
}, 2000);
|
Python
|
UTF-8
| 1,350
| 3.359375
| 3
|
[] |
no_license
|
import copy
with open("inputs/input11.txt", "r") as f:
layout = [list(x) for x in f.read().splitlines()]
def neighbours(x,y,layout):
n = []
for i in range(max(0, x - 1), min(len(layout), x + 2)):
for j in range(max(0, y - 1), min(len(layout[0]), y + 2)):
if not (i == x and j == y):
n += [layout[i][j]]
return n
def new_state (ns, old_state):
if ns.count("#") == 0 and (old_state == "L"):
return "#"
elif ns.count("#") >= 4 and (old_state == "#"):
return "L"
else:
return old_state
def debug_print(layout): #Function for debugging
for row in layout:
for s in row:
print(s, end="")
print("")
converged = False
old_layout = copy.deepcopy(layout)
new_layout = copy.deepcopy(layout)
while not converged:
converged = True
for i in range(0,len(old_layout)):
for j in range(0, len(old_layout[0])):
ns = neighbours(i,j,old_layout)
old = old_layout[i][j]
new = new_state(ns, old)
if new != old:
converged = False
new_layout[i][j] = new
old_layout = copy.deepcopy(new_layout)
count = 0
for i in range(len(new_layout)):
for j in range(len(new_layout[0])):
if new_layout[i][j] == "#":
count += 1
print(count)
|
JavaScript
|
UTF-8
| 346
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
const input=require("readline-sync")
const time=input.questionInt("enter time:-")
if (time >= 5 && time <= 6) {
console.log("sleep well");
}
else if (time >=6 && time <= 7) {
console.log("Morning Exercise");
}
else if(time > 7 && time < 8.30){
console.log("Break+Breakfast");
}
else if ( time > 8.30 && time < 12){
console.log("Study");
}
|
Go
|
UTF-8
| 665
| 2.90625
| 3
|
[] |
no_license
|
package register
import (
"actor"
)
// register Actor implementation
type RegisterActor struct {
*actor.Actor
}
//Start register instance
func Start() *RegisterActor {
r := &RegisterActor{actor.NewActor()}
st := &Register{
index: make(map[actor.Pid]*actor.Actor),
}
r.Spawn(st)
return r
}
//Set Actor on Register
func (r *RegisterActor) Set(a *actor.Actor) (err error) {
_, err = r.Send(r.GetPid(), "Set", a.GetPid(), a)
return
}
//Get Actor from PID on register
func (r *RegisterActor) Get(p actor.Pid) (a *actor.Actor, err error) {
res, err := r.Send(r.GetPid(), "Get", p)
if err != nil {
return nil, err
}
return res.(*actor.Actor), nil
}
|
C++
|
UTF-8
| 973
| 2.59375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#pragma once
#include <saiga/config.h>
#include "saiga/util/glm.h"
#include "saiga/geometry/aabb.h"
#include "saiga/geometry/sphere.h"
#include "saiga/geometry/triangle.h"
#include "saiga/geometry/plane.h"
namespace Saiga {
using glm::min;
using glm::max;
class SAIGA_GLOBAL Ray
{
public:
vec3 direction;
vec3 origin;
vec3 dirfrac;
public:
Ray(const vec3 &dir = vec3(0, 0, 0), const vec3 &ori = vec3(0, 0, 0));
//[output] t: distance between ray origin and intersection
bool intersectAabb(const AABB &bb, float &t) const;
bool intersectTriangle(const Triangle &s, float &t, bool &back) const;
bool intersectPlane(const Plane& p, float &t) const;
vec3 getAlphaPosition(float alpha) const { return origin+alpha*direction;}
SAIGA_GLOBAL friend std::ostream& operator<<(std::ostream& os, const Ray& dt);
};
}
|
Java
|
UTF-8
| 985
| 2.15625
| 2
|
[] |
no_license
|
package com.fram.codingassignment.mvp.portfoliochart.model;
import com.fram.codingassignment.mvp.base.usecase.RequestValues;
import com.fram.codingassignment.mvp.portfoliochart.domain.UcFilterPortfolioData;
import java.util.List;
/**
* Created by thaile on 6/4/17.
*/
public class FilterPortfolioRequest implements RequestValues {
private final UcFilterPortfolioData.FilterMode filterMode;
private final List<Portfolio> originData;
private final int currentMonth;
public FilterPortfolioRequest(UcFilterPortfolioData.FilterMode filterMode, List<Portfolio> originData, int currentMonth) {
this.filterMode = filterMode;
this.originData = originData;
this.currentMonth = currentMonth;
}
public UcFilterPortfolioData.FilterMode getFilterMode() {
return filterMode;
}
public List<Portfolio> getOriginData() {
return originData;
}
public int getCurrentMonth() {
return currentMonth;
}
}
|
C++
|
UTF-8
| 3,159
| 2.875
| 3
|
[] |
no_license
|
#include "coins.h"
#include "main.h"
Coins::Coins(float x, float y, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = 0;
this->radius = 0.2;
this->d=0;
this->status=0;
// this->speed = speed;
// yspeed = 0;
GLfloat vertex_buffer_data[500];
int sides = 50;
float angle = (2*3.14159)/sides;
for(int i =0; i < sides;i++)
{
vertex_buffer_data[9*i] = 0.0f;
vertex_buffer_data[9*i + 1] = 0.0f;
vertex_buffer_data[9*i + 2] = 0.0f;
vertex_buffer_data[9*i + 3] = radius*cos(i*angle);
vertex_buffer_data[9*i + 4] = radius*sin(i*angle) ;
vertex_buffer_data[9*i + 5] = 0.0f;
vertex_buffer_data[9*i + 6] = radius*cos((i+1)*angle);
vertex_buffer_data[9*i + 7] = radius*sin((i+1)*angle);
vertex_buffer_data[9*i + 8] = 0.0f;
}
// vertex_buffer_data[450] = 0.2f;
// vertex_buffer_data[451] = 0.0f;
// vertex_buffer_data[452] = 0.0f;
// vertex_buffer_data[453] = -0.2f;
// vertex_buffer_data[454] = 0.0f;
// vertex_buffer_data[455] = 0.0f;
// vertex_buffer_data[456] = -0.2f;
// vertex_buffer_data[457] = -0.5f;
// vertex_buffer_data[458] = 0.0f;
// vertex_buffer_data[459] = 0.2f;
// vertex_buffer_data[460] = 0.0f;
// vertex_buffer_data[461] = 0.0f;
// vertex_buffer_data[462] = 0.2f;
// vertex_buffer_data[463] = -0.5f;
// vertex_buffer_data[464] = 0.0f;
// vertex_buffer_data[465] = -0.2f;
// vertex_buffer_data[466] = -0.5f;
// vertex_buffer_data[467] = 0.0f;
this->object = create3DObject(GL_TRIANGLES, 3*(sides), vertex_buffer_data, color, GL_FILL);
}
void Coins::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0));
// No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate
// rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object);
}
void Coins::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
void Coins::set_value(int z) {
this->status = 1;
}
void Coins::tick() {
this->rotation += speed;
// this->position.x -= this->speed;
// this->position.y -= this->speed;
}
int Coins::collision(Character character,Mirror mirror)
{
float x = this->position.x;
float y = this->position.y;
float pl_x_min = character.position.x-0.2;
float pl_x_max = character.position.x+0.25;
float pl_y_min = character.position.y-0.5;
float pl_y_max = character.position.y+0.2;
if((x+0.2>=pl_x_min&&x+0.2<=pl_x_max)||(x-0.2>=pl_x_min&&x-0.2<=pl_x_max))
{
if((y+0.2>=pl_y_min&&y+0.2<=pl_y_max)||(y-0.2>=pl_y_min&&y-0.2<=pl_y_max))
{
this->status=1;
return 1;
// character.change_hel();
}
}
return 0;
}
|
Java
|
UTF-8
| 5,909
| 2.3125
| 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 workloadgenerator;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author YC
*/
public class XMLWriter
{
public XMLWriter()
{
}
public static Document creatXML(wgWorkload w)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
/*創建Workload根元素*/
Element workloadElement = doc.createElement(w.getWorkloadHeader());
doc.appendChild(workloadElement);
workloadElement.setAttribute(w.getMaximumUtilizationHeader(), String.valueOf(w.getMaximumUtilization()));
workloadElement.setAttribute(w.getActualUtilizationHeader(), String.valueOf(w.getActualUtilization()));
workloadElement.setAttribute(w.getMaximumCriticalSectionRatioHeader(), String.valueOf(w.getMaxCriticalSectionRatio()));
workloadElement.setAttribute(w.getActualCriticalSectionRatioHeader(), String.valueOf(w.getActualCriticalSectionRatio()));
workloadElement.setAttribute(w.getTaskNumberHeader(), String.valueOf(w.getTaskNumber()));
workloadElement.setAttribute(w.getResourcesNumberHeader(), String.valueOf(w.getResourcesNumber()));
workloadElement.setAttribute(w.getFrequencyHeader(), String.valueOf(w.getFrequency()));
/*創建Resources*/
for(wgResources r : w.getResourcesSet())
{
Element resourcesElement = doc.createElement(r.getResourcesHeader());
resourcesElement.setAttribute(r.getIDHeader(),String.valueOf(r.getID()));
resourcesElement.setAttribute(r.getResourceAmountHeader(),String.valueOf(r.getResourceAmount()));
workloadElement.appendChild(resourcesElement);
}
for(wgTask t : w.getTaskSet())
{
Element taskElement = doc.createElement(t.getTaskHeader());
taskElement.setAttribute(t.getIDHeader(),String.valueOf(t.getID()));
Element enterTime = doc.createElement(t.getEnterTimeHeader());
enterTime.appendChild(doc.createTextNode(String.valueOf(t.exporeEnterTime())));
taskElement.appendChild(enterTime);
Element period = doc.createElement(t.getPeriodHeader());
period.appendChild(doc.createTextNode(String.valueOf(t.exporePeriod())));
taskElement.appendChild(period);
Element relativeDeadline = doc.createElement(t.getRelativeDeadlineHeader());
relativeDeadline.appendChild(doc.createTextNode(String.valueOf(t.exporeRelativeDeadline())));
taskElement.appendChild(relativeDeadline);
Element computationAmount = doc.createElement(t.getComputationAmountHeader());
computationAmount.appendChild(doc.createTextNode(String.valueOf(t.exporeComputationAmount())));
taskElement.appendChild(computationAmount);
if(t.getCriticalSectionSet().size()>0)
{
Element criticalSections= doc.createElement(t.getCriticalSectionSet().getCriticalSectionSetHeader());
taskElement.appendChild(criticalSections);
for(wgCriticalSection cs : t.getCriticalSectionSet())
{
Element criticalSection= doc.createElement(cs.getCriticalSectionHeader());
// taskElement.appendChild(criticalSection);
criticalSection.setAttribute(cs.getResourceIDHeader(),String.valueOf(cs.getResources().getID()));
criticalSection.setAttribute(cs.getStartTimeHeader(),String.valueOf(cs.exporeStartTime()));
criticalSection.setAttribute(cs.getEndTimeHeader(),String.valueOf(cs.exporeEndTime()));
criticalSections.appendChild(criticalSection);
// Element resources = doc.createElement(cs.getResourceIDHeader());
// resources.appendChild(doc.createTextNode(String.valueOf(cs.getResources().getID())));
// criticalSection.appendChild(resources);
//
// Element startTime = doc.createElement(cs.getStartTimeHeader());
// startTime.appendChild(doc.createTextNode(String.valueOf(cs.exporeStartTime())));
// criticalSection.appendChild(startTime);
//
// Element endTime = doc.createElement(cs.getEndTimeHeader());
// endTime.appendChild(doc.createTextNode(String.valueOf(cs.exporeEndTime())));
// criticalSection.appendChild(endTime);
}
}
workloadElement.appendChild(taskElement);
}
return doc;
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
return null;
}
}
|
C#
|
UTF-8
| 516
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
using System.Collections.Generic;
namespace Discord
{
/// <summary>
/// Represents a component object used in <see cref="Modal"/>s.
/// </summary>
public class ModalComponent
{
/// <summary>
/// Gets the components to be used in a modal.
/// </summary>
public IReadOnlyCollection<ActionRowComponent> Components { get; }
internal ModalComponent(List<ActionRowComponent> components)
{
Components = components;
}
}
}
|
Java
|
UTF-8
| 2,602
| 1.851563
| 2
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
/*
* Copyright 2016 Goldman Sachs.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.gs.dmn.runtime.interpreter;
import org.junit.Test;
public abstract class CL2SDMNInterpreterTest<NUMBER, DATE, TIME, DATE_TIME, DURATION> extends AbstractDMNInterpreterTest<NUMBER, DATE, TIME, DATE_TIME, DURATION> {
@Override
protected String getDMNInputPath() {
return "tck/cl2";
}
@Override
protected String getTestCasesInputPath() {
return getDMNInputPath();
}
@Test
public void testCL2() {
doSingleModelTest("0001-input-data-string");
doSingleModelTest("0002-input-data-number");
doSingleModelTest("0003-input-data-string-allowed-values");
doSingleModelTest("0004-simpletable-U");
doSingleModelTest("0005-simpletable-A");
doSingleModelTest("0006-simpletable-P1");
doSingleModelTest("0007-simpletable-P2");
doSingleModelTest("0008-LX-arithmetic");
doSingleModelTest("0009-invocation-arithmetic");
doSingleModelTest("0010-multi-output-U");
doSingleModelTest("0100-feel-constants");
doSingleModelTest("0101-feel-constants");
doSingleModelTest("0102-feel-constants");
doSingleModelTest("0105-feel-math");
doSingleModelTest("0106-feel-ternary-logic");
doSingleModelTest("0107-feel-ternary-logic-not");
doSingleModelTest("0108-first-hitpolicy");
doSingleModelTest("0109-ruleOrder-hitpolicy");
doSingleModelTest("0110-outputOrder-hitpolicy");
doSingleModelTest("0111-first-hitpolicy-singleoutputcol");
doSingleModelTest("0112-ruleOrder-hitpolicy-singleinoutcol");
doSingleModelTest("0113-outputOrder-hitpolicy-singleinoutcol");
doSingleModelTest("0114-min-collect-hitpolicy");
doSingleModelTest("0115-sum-collect-hitpolicy");
doSingleModelTest("0116-count-collect-hitpolicy");
doSingleModelTest("0117-multi-any-hitpolicy");
doSingleModelTest("0118-multi-priority-hitpolicy");
doSingleModelTest("0119-multi-collect-hitpolicy");
}
}
|
Markdown
|
UTF-8
| 878
| 2.90625
| 3
|
[] |
no_license
|
---
layout: post-layout.njk
title: Played around with event emitters
date: 2020-07-14
tags: ['100days']
---
<!-- Excerpt Start -->
This is another one of those things that I use *all* the time and took for granted. Turns out they're pretty cool.
<!-- Excerpt End -->
Events listeners are pretty common is JS, whether it's listening for a click on a button, or listening for a change in an input value. I was working on my Pomodoro app again and ran into issues bridging the gap between the two seperates components of it - the timer, and the todo list. To solve this, I learned about event emitters, then implemented some basic ones for when the timer ended, and for when a task was completed. All that's left to do is to put it all together and we're good to go :)
Todays session was on the short end on account of a work social, but day 4 and we're still going strong. (Yay!)
|
PHP
|
UTF-8
| 6,913
| 2.75
| 3
|
[] |
no_license
|
--TEST--
s60_calendar repeat test.
--FILE--
<?php
function my_assert_handler($file, $line, $code)
{
$lines = file($file);
echo "\nFailure:".trim($lines[$line-1])."\n";
}
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
define('HOUR', 3600);
define('DAY', HOUR*24);
define('WEEK', DAY*7);
define('NOW', time());
function get_db_repeat($repeat) {
$db = s60_calendar_open("ctest.db", "n");
$c = $db->add_entry(S60_CALENDAR_TYPE_MEETING);
$c->set_content("test_cont");
$c->set_location("test_loca");
$c->set_start_end_time(NOW, NOW + HOUR);
$c->set_repeat($repeat);
$c->set_repeat($c->repeat());
$c->commit();
return $db;
}
function repeat_daily() {
echo "daily repeat\n";
$db = get_db_repeat(array(
"type"=>"daily",
"start"=>NOW,
"end"=>NOW + WEEK*2,
"interval"=>2));
// Assert that the repeated entry is found
// every second day, total of 8 instances.
$pwd = -1;
$wd = 0;
$count = 0;
for ($t = NOW; $t < NOW+WEEK*3; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
if ($pwd !== -1) { assert ($wd === $pwd+2); }
$pwd = $wd;
}
$wd = $wd + 1;
}
assert ($count === 8);
echo "done\n";
}
function repeat_daily_exceptions() {
echo "daily repeat + exceptions\n";
$db = get_db_repeat(array(
"type"=>"daily",
"start"=>NOW,
"end"=>NOW + WEEK*2,
"interval"=>2,
"exceptions"=>array(NOW+DAY*4, NOW+DAY*6)));
// Assert that the repeated entry is found
// on specific days: 0,2,8,10,12,14
$ds = array();
$wd = 0;
for ($t = NOW; $t < NOW+WEEK*3; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$ds[] = $wd;
}
$wd = $wd + 1;
}
assert ($ds == array(0,2,8,10,12,14));
echo "done\n";
}
function repeat_daily_remove() {
echo "daily repeat + remove instances\n";
$db = get_db_repeat(array(
"type"=>"daily",
"start"=>NOW,
"end"=>NOW + WEEK*3,
"interval"=>1));
// Remove some past instances, some specific
// day instances and some future instances
$inst = $db->find_instances_day(NOW + DAY*2);
$inst[0]->remove(S60_CALENDAR_REMOVE_PAST);
$inst = $db->find_instances_day(NOW + DAY*4);
$inst[0]->remove();
$inst = $db->find_instances_day(NOW + DAY*6);
$inst[0]->remove();
$inst = $db->find_instances_day(NOW + DAY*12);
$inst[0]->remove(S60_CALENDAR_REMOVE_FUTURE);
// Assert that the repeated entry is found
// on specific days: 3,5,7,8,9,10,11
$ds = array();
$wd = 0;
for ($t = NOW; $t < NOW+WEEK*4; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$ds[] = $wd;
}
$wd = $wd + 1;
}
assert ($ds == array(3,5,7,8,9,10,11));
echo "done\n";
}
function repeat_weekly() {
echo "weekly repeat\n";
$db = get_db_repeat(array(
"type"=>"weekly",
"start"=>NOW,
"end"=>NOW + WEEK*5,
"interval"=>2,
"days"=>array(5)));
// Assert that the repeated entry is found
// on 3 days, all the same weekday
$pwd = -1;
$wd = 0;
$count = 0;
for ($t = NOW; $t < NOW+WEEK*15; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
if ($pwd !== -1) { assert ($wd === $pwd); }
$pwd = $wd;
}
$wd = ($wd + 1) % 7;
}
assert ($count === 3);
echo "done\n";
}
function repeat_weekly_forever() {
echo "weekly repeat forever\n";
$db = get_db_repeat(array(
"type"=>"weekly",
"start"=>NOW,
"interval"=>2,
"days"=>array(5)));
// Assert that the repeated entry is found
// on 8 days, all the same weekday.
// Just testing 15 weeks since that's almost forever..
$pwd = -1;
$wd = 0;
$count = 0;
for ($t = NOW; $t < NOW+WEEK*15; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
if ($pwd !== -1) { assert ($wd === $pwd); }
$pwd = $wd;
}
$wd = ($wd + 1) % 7;
}
assert ($count === 8);
echo "done\n";
}
function repeat_monthly_by_dates() {
echo "monthly by dates repeat\n";
$db = get_db_repeat(array(
"type"=>"monthly_by_dates",
"start"=>NOW,
"end"=>NOW + WEEK*14,
"days"=>array(0, 14),
"interval"=>1));
// Assert that the repeat entry has instances
// only on days 1 and 15, and number of them between 5-8
$count = 0;
for ($t = NOW; $t < NOW+WEEK*22; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
assert (date("j", $t) == 1 || date("j", $t) == 15);
}
}
assert ($count > 4 && $count < 9); // XXX I didn't really think this through
echo "done\n";
}
function repeat_monthly_by_days() {
// XXX test may fail...
echo "monthly by days repeat\n";
$db = get_db_repeat(array(
"type"=>"monthly_by_days",
"start"=>NOW,
"end"=>NOW + WEEK*12 - DAY,
"days"=>array(array("week"=>2, "day"=>4)),
"interval"=>1));
// Assert that the repeated entry is found
// on fridays and there is at least 20 days
// between each instance. 3 instances total.
$pwd = -1;
$wd = 0;
$count = 0;
for ($t = NOW; $t < NOW+WEEK*22; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
assert (date("w", $t) == 5);
if ($pwd !== -1) { assert ($wd > $pwd+20); }
$pwd = $wd;
}
$wd = $wd + 1;
}
assert ($count === 3);
echo "done\n";
}
function repeat_yearly_by_date() {
echo "yearly by date repeat\n";
$db = get_db_repeat(array(
"type"=>"yearly_by_date",
"start"=>NOW-10,
"end"=>NOW + WEEK*120,
"interval"=>1));
// Assert that the repeat entry has 3 instances,
// on different years but on same days.
$count = 0;
$pt = -1;
for ($st = NOW; $st < NOW+WEEK*220; $st += DAY*365) {
for ($t = $st-DAY*4; $t < $st+DAY*4; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
if ($pt !== -1) { assert (date("j", $t) == date("j", $pt)); }
$pt = $t;
//assert (date("j", $t) == 1 || date("j", $t) == 15);
}
}
}
assert ($count === 3);
echo "done\n";
}
function repeat_yearly_by_day() {
echo "yearly by day repeat\n";
$db = get_db_repeat(array(
"type"=>"yearly_by_day",
"start"=>NOW-10,
"end"=>NOW + WEEK*120,
"days"=>array("month"=>7, "week"=>-1, "day"=>0),
"interval"=>1));
// Assert that the repeat entry has 2-3 instances,
// on different years but on same weekday and near the end of month.
$count = 0;
for ($st = NOW; $st < NOW+WEEK*220; $st += DAY*365) {
for ($t = $st-DAY*30; $t < $st+DAY*30; $t += DAY) {
if (count($db->find_instances_day($t)) !== 0) {
$count++;
assert ((int)date("N", $t) === 1);
assert ((int)date("j", $t) > 22);
}
}
}
assert ($count >= 2 && $count <= 3);
echo "done\n";
}
repeat_daily(); sleep(1);
repeat_daily_exceptions(); sleep(1);
repeat_daily_remove(); sleep(1);
repeat_weekly(); sleep(1);
repeat_monthly_by_dates(); sleep(1);
repeat_monthly_by_days(); sleep(1);
repeat_yearly_by_date(); sleep(1);
repeat_yearly_by_day(); sleep(1);
echo 'ok';
?>
--EXPECTF--
daily repeat
done
daily repeat + exceptions
done
daily repeat + remove instances
done
weekly repeat
done
monthly by dates repeat
done
monthly by days repeat
done
yearly by date repeat
done
yearly by day repeat
done
ok
|
Java
|
UTF-8
| 2,374
| 2.296875
| 2
|
[] |
no_license
|
package backend.ServiceImpl;
import backend.Dao.BookDao;
import backend.Dao.CartDao;
import backend.Dao.OrderDao;
import backend.Dao.OrderItemDao;
import backend.Entity.Cart;
import backend.Entity.Order;
import backend.Entity.OrderItem;
import backend.Service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
OrderDao orderDao;
@Autowired
CartDao cartDao;
@Autowired
BookDao bookDao;
@Autowired
OrderItemDao orderItemDao;
@Override
public List<Order> findAllOrder(){
List<Order> orderList = orderDao.findAll();
for(Order order : orderList){
order.getUser().setPassword("");
order.getUser().setEmail("");
}
return orderList;
}
@Override
public List<Order> findAllOrderByUsernameAndStatus(String username){
List<Order> orderList = orderDao.findAllByUserAndStatus(username, 0);
for(Order order : orderList){
order.getUser().setPassword("");
order.getUser().setEmail("");
}
return orderList;
}
@Override
public Boolean submitOrder(String username){
List<Cart> cartList = cartDao.getUserCart(username);
if(cartList.isEmpty()) return false;
for(Cart cart: cartList){
if(cart.getNum() > cart.getBook().getNum())
return false;
}
Order order = new Order();
order.setUser(cartList.get(0).getUser());
order.setStatus(0);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = df.format(new Date());
order.setTime(dateTime);
orderDao.saveOrder(order);
for(Cart cart: cartList){
OrderItem orderItem = new OrderItem();
orderItem.setOrder_id(order.getOrder_id());
orderItem.setBook(cart.getBook());
orderItem.setNumber(cart.getNum());
orderItemDao.saveItem(orderItem);
cartDao.deleteCart(cart.getBook(),cart.getUser());
bookDao.setBookNum(cart.getBook(),cart.getBook().getNum() - cart.getNum());
}
return true;
}
}
|
C#
|
UTF-8
| 4,630
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Globalization;
using System.IO;
using System.Linq;
namespace Memento.Helpers
{
class BackupPath
{
private string _base;
private string _month;
private string _day;
private string _time;
private string _customLabel;
private DateTime _timestamp;
private BackupPath() { }
public BackupPath ApplyLabel(string newLabel)
{
return new BackupPath
{
_month = _month,
_day = _day,
_time = _time,
_base = _base,
_timestamp = _timestamp,
_customLabel = newLabel
};
}
public string GetLabel()
{
return string.IsNullOrEmpty(_customLabel) ? LabelFromTimestamp(_timestamp) : _customLabel;
}
public bool IsSameIgnoreLabel(BackupPath other)
{
return _base == other._base
&& _month == other._month
&& _day == other._day
&& _time == other._time
&& _timestamp == other._timestamp;
}
public static BackupPath FromDateTime(DateTime timestamp, string savesFolder)
{
return new BackupPath
{
_month = timestamp.ToString("yyyy-MM"),
_day = timestamp.ToString("dd"),
_time = timestamp.ToString("HH.mm.ss"),
_base = savesFolder,
_timestamp = timestamp,
_customLabel = ""
};
}
public static string LabelFromTimestamp(DateTime timestamp)
{
return timestamp.ToString("d MMM yyyy HH:mm:ss");
}
public static BackupPath FromPath(string path)
{
if (path == null)
{
return null;
}
string[] tokens = path.Split('\\');
if (tokens.Length < 4)
{
return null;
}
string basePath = string.Join("\\",tokens.Take(tokens.Length - 3).ToArray());
Array.Reverse(tokens);
BackupPath result = new BackupPath
{
_time = tokens[0],
_day = tokens[1],
_month = tokens[2],
_base = basePath
};
(result._time, result._customLabel) = SplitTimeAndLabel(result._time);
DateTime? timePart = ParseDatePart(result._time, "HH.mm.ss", "HH.mm.ss_manual", "HH.mm.ss_restore");
DateTime? dayPart = ParseDatePart(result._day, "dd");
DateTime? monthPart = ParseDatePart(result._month, "yyyy-MM");
if (!timePart.HasValue || !dayPart.HasValue || !monthPart.HasValue)
{
return null;
}
result._timestamp = new DateTime(
monthPart.Value.Year,
monthPart.Value.Month,
dayPart.Value.Day,
timePart.Value.Hour,
timePart.Value.Minute,
timePart.Value.Second);
return result;
}
public override string ToString()
{
string result = Path.Combine(_base, _month);
result = Path.Combine(result, _day);
result = Path.Combine(result, _time);
if (!string.IsNullOrEmpty(_customLabel))
{
result += $" - {_customLabel}";
}
return result;
}
private static (string time, string label) SplitTimeAndLabel(string timeLabelPart)
{
int indexOfMinus = timeLabelPart.IndexOf('-');
if (indexOfMinus < 0)
{
return (timeLabelPart, "");
}
else
{
string time = timeLabelPart.Substring(0, indexOfMinus);
string label = timeLabelPart.Substring(indexOfMinus);
if (label.Length > 0)
{
label = label.Substring(1);
}
return (time.Trim(), label.Trim());
}
}
private static DateTime? ParseDatePart(string part, params string[] patterns)
{
foreach (string pattern in patterns)
{
DateTime result;
if (DateTime.TryParseExact(part, pattern, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
}
return null;
}
}
}
|
Markdown
|
UTF-8
| 4,482
| 2.9375
| 3
|
[] |
no_license
|
# ApiClient
A C# .NET Core API Client library for connecting to and consuming data from APIs.


# Installation
Add the `ApiClient.Common` package to your project (depends on the `ApiClient.Utilities` project):
```
dotnet add package ApiClient.Common
```
Follow the usage instructions below to get started.
# Usage
The `ApiClient` library provides several types of connections for different uses.
## Basic Connection
A `BasicConnection` object is appropriate for an API that does not require any authentication.
### Setting up a Basic Connection
1. Set up your configuration object.
```
// Set the URL
var url = new Uri("https://postman-echo.com"); // The Base URL of the API
// Configure your response/request types using the built-in `ResponseType` and `RequestType`
// helpers.
var responseType = ResponseType.PlainText; // Choose from `Json`, `PlainText`, or `Html` types.
var requestType = RequestType.Json; // Choose from `Json` or `Form` types.
// Pass the base URL and response/request types to the `BasicConnectionConfig` constructor.
var basicConnectionConfig = new BasicConnectionConfig(url, responseType, requestType);
```
2. Pass your configuration object to the `ConnectionFactory.GetConnection(...)` method to instantiate a new connection object. The `ConnectionFactory` returns the proper connection type based on the configuration passed in.
```
IConnection basicConnection = ConnectionFactory.GetConnection(basicConnectionConfig);
```
3. Send a GET or POST request and save the response in a `Response` object.
```
// For example: Sends a POST request to https://postman-echo.com/post with no additional headers
// and "This is my body" as the response body.
Response basicConnectionResponse =
basicConnection.Post("/post", null, "This is my body");
```
4. Read back the properties inside of your `Response` object. `Message` contains the response message, and `StatusCode` contains the HTTP status code.
```
Console.WriteLine(
"**Basic connection test**\n" +
String.Format("The status code: {1}\nThe response: {0}",
basicConnectionResponse.Message,
basicConnectionResponse.StatusCode)
);
```
## Basic Auth Connection
A `BasicAuthConnection` object is appropriate for an API that requires only basic HTTP authentication. Basic HTTP authentication requires sending a Base-64-encoded string that contains an encoded version of the username/password pair. The `BasicAuthConnection` object handles encoding and appending this header to all of your requests.
### Setting up a Basic Auth Connection
This process is very similar to setting up a `BasicConnection` object. This time, we pass additional username and password parameters to the configuration constructor.
1. Set up your configuration object.
```
string username = "postman";
string password = "password";
var basicAuthConfig =
new BasicAuthConnectionConfig(url, responseType, requestType, username, password);
```
2. Pass your configuration object to the `ConnectionFactory.GetConnection(...)` method to instantiate a new connection object. The `ConnectionFactory` once again returns the proper connection type based on the configuration passed in.
```
IConnection basicAuthConnection = ConnectionFactory.GetConnection(basicAuthConfig);
```
3. Send a GET or POST request and save the response in a `Response` object.
```
// For example: Sends a GET request to https://postman-echo.com/basic-auth with no additional
// headers and an empty response body.
Response basicAuthResponse = basicAuthConnection.Get("/basic-auth", null);
```
# Contributing
Contributing by creating issues and pull requests is encouraged.
## DOs and DON'Ts
- DO follow the coding style. Look around the codebase and try to mirror what you see.
- DO create issues and foster discussion.
- DO reference issues in your pull request (I.E. "Fixes #123") so that it will be automatically closed when/if the pull request is merged in.
- DO create pull requests against the develop branch.
- DON'T make large surprise pull requests. File an issue and start a discussion. We should work together on a solution before you invest time in a large un-vetted pull request.
- DON'T create pull requests against the master branch.
|
C#
|
UTF-8
| 339
| 3.1875
| 3
|
[] |
no_license
|
public static T SafeProcessing<T>(Action<T> action, Action<T> onFail)
where T: new()
{
var t = Activator.CreateInstance<T>();
try
{
a(t);
}
catch (Exception e)
{
//Log e
onFail(t);
}
return t;
}
|
Python
|
UTF-8
| 149
| 3.59375
| 4
|
[] |
no_license
|
name="john"
print "Hello %s!" % name
age=25
print "Hello %s, you are %d years old" %(name, age)
list2=[1,2,3]
print 'this is a list: %s' % list2
|
Markdown
|
UTF-8
| 2,253
| 2.53125
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
# <a name="response-compression-sample-application-aspnet-core-1x"></a>响应压缩示例应用程序 (ASP.NET Core 1.x)
此示例演示如何使用 ASP.NET Core 1.x 响应的压缩中间件来压缩 HTTP 响应中的。 此示例演示 Gzip 和自定义压缩的文本和图像响应的提供程序,并演示如何添加压缩的 MIME 类型。 有关 ASP.NET Core 2.x 示例,请参阅[响应压缩示例应用程序 (ASP.NET Core 2.x)](https://github.com/aspnet/Docs/tree/master/aspnetcore/performance/response-compression/samples/2.x)。
## <a name="examples-in-this-sample"></a>此示例中的示例
* `GzipCompressionProvider`
* `text/plain`
* **/** -将压缩为 927 字节的 2,044 字节乱数假文文本文件响应
* **/testfile1kb.txt** -1,033 将压缩为 47 个字节的字节的文本文件响应
* **/ 渗透**-每次间隔 1 秒作为单个字符发出的响应
* `image/svg+xml`
* **/banner.svg** -9,707 将压缩为 4,459 字节的字节的可缩放向量图形 (SVG) 图像响应
* `CustomCompressionProvider`<br>演示如何实现与中间件使用的自定义压缩提供程序
当请求包括`Accept-Encoding`标头,该示例添加`Vary: Accept-Encoding`到响应的标头。 `Vary`标头会指示缓存维护的响应的替代值为基础的多个副本`Accept-Encoding`,因此需压缩 (gzip) 和未压缩的版本存储在缓存中的系统可以接受压缩或未压缩的响应。
## <a name="using-the-sample"></a>使用示例
1. 使请求使用[Fiddler](http://www.telerik.com/fiddler), [Firebug](http://getfirebug.com/),或[Postman](https://www.getpostman.com/)到应用程序而不`Accept-Encoding`标头并记下响应有效负载,响应大小和响应标头。
1. 添加`Accept-Encoding: gzip`标头并记下压缩的响应大小和响应标头。 请参阅删除,响应大小和`Content-Encoding: gzip`响应标头包含示例应用。 要查看在响应正文的乱数假文或**testfile1kb.txt**响应,你将看到文本是压缩且不可读。
1. 添加`Accept-Encoding: mycustomcompression`标头并记下响应标头。 `CustomCompressionProvider`是一个空实现,实际上不会压缩响应,但您可以创建自定义压缩流包装器`CreateStream()`方法。
|
Java
|
UTF-8
| 2,605
| 2.421875
| 2
|
[] |
no_license
|
package ec.com.jnegocios.api;
import java.security.Principal;
import java.util.Collection;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ec.com.jnegocios.entity.Tag;
import ec.com.jnegocios.service.tag.TagService;
import ec.com.jnegocios.util.AppHelper;
import ec.com.jnegocios.util.JSONResponse;
@RestController
@RequestMapping(AppHelper.PREFIX_TAG)
public class TagController {
@Autowired
private TagService serviceTag;
/**
* END POINT GET ALL USER'S TAGS
* /tags
*/
@GetMapping(produces = AppHelper.JSON)
public ResponseEntity<Collection<Tag>> findTagsByUserAuth (Principal auth) {
Collection<Tag> tags = serviceTag.findByUsername(auth.getName());
return ResponseEntity
.ok(tags);
}
/**
* END POINT GET BY ID
* /tags/:id
*/
@GetMapping(value="/{id}", produces = AppHelper.JSON)
public ResponseEntity<Tag> show (@PathVariable Integer id) {
return ResponseEntity
.status(HttpStatus.OK)
.body(serviceTag.findById(id));
}
/**
* END POINT POST NEW USER'S TAG
* /tags
*/
@PostMapping(produces = AppHelper.JSON)
public ResponseEntity<Tag> save (@Valid @RequestBody Tag tag, Principal auth)
{
Tag _tag = this.serviceTag.save(tag, auth.getName());
return ResponseEntity
.status(HttpStatus.CREATED)
.body(_tag);
}
/**
* END POINT UPDATE USER'S TAG
* /tags/:id
*/
@RequestMapping(value="/{id}", method = {RequestMethod.PATCH, RequestMethod.PUT}, produces = AppHelper.JSON)
public ResponseEntity<Tag> update (@Valid @RequestBody Tag tag, @PathVariable int id)
{
Tag _tag = this.serviceTag.update(tag, id);
return ResponseEntity
.ok(_tag);
}
/**
* END POINT DELETE TAG
* /tags/:id
*/
@RequestMapping(value="/{id}", method = RequestMethod.DELETE, produces = AppHelper.JSON)
public ResponseEntity<?> destroy (@PathVariable int id)
{
this.serviceTag.delete(id);
return ResponseEntity.ok( JSONResponse.fromGeneralTemplate(
AppHelper.PREFIX_TAG.concat("/" + String.valueOf(id)),
"Tag eliminado.",
200).getBody() );
}
}
|
Java
|
UTF-8
| 4,934
| 2.484375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cestarcollege.beans;
import com.cestar.dBUtil.ConnectionManager;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* @author saira
*/
@ManagedBean
@SessionScoped
public class index implements Serializable{
String errorMessage;
int id; //to store pure login ID
String psw, name;
Student aStudent;
Admin aAdmin;
String[] splitArray; //Used to split given string into login type and ID
String idString; //To store the complete ID string from the user
ArrayList<Student> listStudents = new ArrayList<>();
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPsw() {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student getaStudent() {
return aStudent;
}
public void setaStudent(Student aStudent) {
this.aStudent = aStudent;
}
public Admin getaAdmin() {
return aAdmin;
}
public void setaAdmin(Admin aAdmin) {
this.aAdmin = aAdmin;
}
public String[] getSplitArray() {
return splitArray;
}
public void setSplitArray(String[] splitArray) {
this.splitArray = splitArray;
}
public String getIdString() {
return idString;
}
public void setIdString(String idString) {
this.idString = idString;
}
public ArrayList<Student> getListStudents() {
return listStudents;
}
public void setListStudents(ArrayList<Student> listStudents) {
this.listStudents = listStudents;
}
public String login() {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
splitArray = idString.split("/");
id = Integer.parseInt(splitArray[1]);
try {
connection =ConnectionManager.getConnection();
if (splitArray[0].equalsIgnoreCase("student")) {
System.out.println(id);
ps=connection.prepareStatement("select * from CESTAR_STUDENT where id=?");
ps.setInt(1,id);
rs=ps.executeQuery();
if (rs.next()) {
if (rs.getString("password").equals(psw)) {
aStudent=new Student(id, rs.getString("name"), psw, rs.getString("program"), rs.getString("term"), rs.getString("gender"), rs.getString("address"),rs.getString("email"));
return "login_s.xhtml";
} else {
errorMessage = "Incorrect password!";
return "index_error.xhtml";
}
} else {
errorMessage = "Incorrect Student ID!";
return "index_error.xhtml";
}
} else {
ps=connection.prepareStatement("select * from CESTAR_ADMIN where id=?");
ps.setInt(1, id);
rs=ps.executeQuery();
if (rs.next()) {
if (rs.getString(2).equals(psw)) {
aAdmin = new Admin(id, psw);
return "login.xhtml";
} else {
errorMessage = "Incorrect password!";
return "index_error.xhtml";
}
} else {
errorMessage = "Incorrect Faculty ID!";
return "index_error.xhtml";
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
errorMessage = "";
return "index_error.xhtml";
}
public String logout() {
aStudent = null;
idString = null;
psw = null;
return "index.xhtml";
}
}
|
C#
|
UTF-8
| 13,985
| 2.703125
| 3
|
[] |
no_license
|
//===============================================================
// Copyright (C) 2010-2013 皖仪科技研发中心
// 文件名: CurveFitting.cs
// 日期:2013/10/10
// 描述:曲线拟合算法
// 版本:1.00
// 修改历史纪录
// 版本 修改时间 修改人 修改内容
//==============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
namespace Wayee.ResultAnalyzer
{
#region 最小二乘法拟合
public class CLeastSquareFitting
{
protected class CoeffMatrix
{
/// <summary>
///超定方程系数矩阵
/// </summary>
public double[,] AA;
/// <summary>
/// 法方程系数矩阵
/// </summary>
public double[,] MM;
/// <summary>
/// 方程右端向量
/// </summary>
public double[] eq;
}
#region 计算系数矩阵
/// <summary> 建立超定方程组和法方程组</summary>
/// <param name="pList">数据点列表</param>
/// <param name="order">待拟合的多项式次数</param>
/// <param name="zeroPassage">是否过零点</param>
/// <returns>返回建立的方程组系数矩阵</returns>
protected static CoeffMatrix CreateCoeffMatrix(List<PointF> point_list, int order, bool zeroPassage)
{
if (point_list == null)
return null;
if (order < 1)
return null;
CoeffMatrix _coeff_matrix = new CoeffMatrix();
if (zeroPassage == false)
order += 1;
_coeff_matrix.AA = new double[point_list.Count, order];
_coeff_matrix.MM = new double[order, order];
_coeff_matrix.eq = new double[order];
//构建超定方程组系数矩阵
if (zeroPassage)
{
for (int i = 0; i < point_list.Count; i++)
{
_coeff_matrix.AA[i, 0] = point_list[i].X;
}
}
else
{
for (int i = 0; i < point_list.Count; i++)
{
_coeff_matrix.AA[i, 0] = 1.0;
}
}
for (int j = 1; j < order; j++)
{
for (int i = 0; i < point_list.Count; i++)
{
_coeff_matrix.AA[i, j] = _coeff_matrix.AA[i, j - 1] * point_list[i].X;
}
}
//构建法方程系数矩阵
double _sum;
for (int i = 0; i < order; i++)
{
//计算系数矩阵
for (int j = 0; j <= i; j++)
{
_sum = 0.0;
for (int l = 0; l < point_list.Count; l++)
{
_sum += (_coeff_matrix.AA[l, i] * _coeff_matrix.AA[l, j]);
}
_coeff_matrix.MM[i, j] = _sum;
_coeff_matrix.MM[j, i] = _sum;
}
//计算右端向量
_sum = 0.0;
for (int l = 0; l < point_list.Count; l++)
{
_sum += (_coeff_matrix.AA[l, i] * point_list[l].Y);
}
_coeff_matrix.eq[i] = _sum;
}
return _coeff_matrix;
}
#endregion
#region 线性方程求解
/// <summary>高斯消元法解线性方程组</summary>
/// <param name="A">线性方程组系数矩阵/法方程构造矩阵</param>
/// <param name="xx">解向量</param>
/// <param name="isZero">是否过零点</param>
/// <returns>是否有解</returns>
protected static List<double> GaussianElimination(CoeffMatrix coeff_matrix, bool zeroPassage)
{
if ((coeff_matrix == null) || (coeff_matrix.MM == null) || (coeff_matrix.eq == null))
return null;
//系数矩阵维数
int lengthRow = coeff_matrix.MM.GetLength(0);
int lengthColumn = coeff_matrix.MM.GetLength(1);
int lengthSolution = coeff_matrix.eq.Length;
#region 矩阵打印,测试时使用
//高斯消元前打印矩阵
for (int i = 0; i < lengthRow; i++)
{
for (int j = 0; j < lengthColumn; j++)
{
Debug.Write(coeff_matrix.MM[i, j].ToString().PadLeft(10));
}
Debug.WriteLine("\n");
}
//打印解向量
for (int i = 0; i < lengthSolution; i++)
{
Debug.Write(coeff_matrix.eq[i].ToString().PadLeft(10));
}
Debug.WriteLine("\n");
#endregion
//是否超定方程
if (lengthRow < lengthColumn)
{
Debug.WriteLine("The linear equalitions are no solution!");
}
for (int k = 0; k < lengthRow; k++)
{
if (coeff_matrix.MM[k, k] == 0)
{
Debug.WriteLine("The linear equalitions are no solution!");
}
for (int i = k + 1; i < lengthRow; i++)
{
coeff_matrix.MM[i, k] = coeff_matrix.MM[i, k] / coeff_matrix.MM[k, k];
for (int j = k + 1; j < lengthColumn; j++)
{
coeff_matrix.MM[i, j] = coeff_matrix.MM[i, j] - coeff_matrix.MM[i, k] * coeff_matrix.MM[k, j];
}
coeff_matrix.eq[i] = coeff_matrix.eq[i] - coeff_matrix.MM[i, k] * coeff_matrix.eq[k];
}
}
coeff_matrix.eq[lengthSolution - 1] = coeff_matrix.eq[lengthSolution - 1] / coeff_matrix.MM[lengthRow - 1, lengthColumn - 1];
for (int i = lengthColumn - 2; i >= 0; i--)
{
for (int j = i + 1; j < lengthRow; j++)
{
coeff_matrix.eq[i] = coeff_matrix.eq[i] - coeff_matrix.MM[i, j] * coeff_matrix.eq[j];
}
coeff_matrix.eq[i] = coeff_matrix.eq[i] / coeff_matrix.MM[i, i];
}
List<double> _coeff_list = new List<double>();
if (zeroPassage)
{
_coeff_list.Add(0);
}
for (int i = 0; i < lengthColumn; i++)
{
_coeff_list.Add(coeff_matrix.eq[i]);
}
#region 矩阵打印,测试时使用
Debug.WriteLine("高斯消元后矩阵:");
for (int i = 0; i < lengthRow; i++)
{
for (int j = 0; j < lengthColumn; j++)
{
Debug.Write(coeff_matrix.MM[i, j].ToString().PadLeft(20));
}
Debug.WriteLine("\n");
}
//打印解向量
for (int i = 0; i < coeff_matrix.eq.Length; i++)
{
Debug.WriteLine(coeff_matrix.eq[i]);
}
#endregion
return _coeff_list;
}
#endregion
#region 计算相关系数
/// <summary>计算相关系数</summary>
/// <param name="point_list">点列表</param>
/// <returns>相关系数</returns>
public static double ComputeCorrelationCoeff(List<PointF> point_list)
{
if ((point_list == null) || (point_list.Count == 0))
return 0;
double _sumX = 0, _sumY = 0;
double _Sxx = 0, _Sxy = 0, _Syy = 0;
double _averX = 0, _averY = 0;
foreach (PointF _point in point_list)
{
_sumX += _point.X;
_sumY += _point.Y;
}
_averX = _sumX / point_list.Count;
_averY = _sumY / point_list.Count;
double _deltaX = 0, _deltaY = 0;
foreach (PointF pf in point_list)
{
_deltaX = pf.X - _averX;
_deltaY = pf.Y - _averY;
_Sxy += _deltaX * _deltaY;
_Sxx += _deltaX * _deltaX;
_Syy += _deltaY * _deltaY;
}
return Math.Abs(_Sxy / (Math.Sqrt(_Sxx) * Math.Sqrt(_Syy)));//|r|
}
#endregion
#region 计算决定系数
/// <summary>计算决定系数</summary>
/// <param name="pList">点列表</param>
/// <param name="rList">系数列表</param>
/// <returns>决定系数</returns>
public static double ComputeDeterminationCoeff(List<PointF> point_list, List<double> coeff_list)
{
if ((point_list == null) || (point_list.Count == 0))
return 0;
if ((coeff_list == null) || (coeff_list.Count == 0))
return 0;
double _sumY = 0;
for (int i = 0; i < point_list.Count; i++)
{
_sumY += point_list[i].Y;
}
double _averY = _sumY / point_list.Count;
double _RSS = 0;
double _Syy = 0;
for (int i = 0; i < point_list.Count; i++)
{
double _estiY = 0;
for (int j = 0; j < coeff_list.Count; j++)
{
_estiY += coeff_list[j] * Math.Pow(point_list[i].X, j);
}
_RSS += Math.Pow(point_list[i].Y - _estiY, 2);
_Syy += Math.Pow(point_list[i].Y - _averY, 2);
}
if (_Syy == 0)
{
return 1;
}
return (1 - _RSS / _Syy);
}
#endregion
#region 计算拟合系数
/// <summary>
/// 建立超定方程组和法方程组
/// </summary>
/// <param name="pList">数据点列表</param>
/// <param name="rank">待拟合的多项式次数</param>
/// <param name="isZero">是否过零点</param>
/// <param name="r2">线性拟合度</param>
/// <returns>返回拟合系数</returns>
public static List<Double> Fitting(List<PointF> point_list, int order, bool zeroPassage)
{
CoeffMatrix _coeff_matrix = CreateCoeffMatrix(point_list, order, zeroPassage);
return GaussianElimination(_coeff_matrix, zeroPassage);
}
#endregion
#region 获取拟合公式
/// <summary>
/// 获取拟合表达式
/// </summary>
/// <param name="param"></param>
/// <param name="isLog"></param>
/// <param name="isZero"></param>
/// <returns></returns>
public static string GetFormula(List<double> coeff, int order)
{
try
{
if ((coeff == null) || (coeff.Count <= 0)) return null;
foreach (double _v in coeff)
{
if (Double.IsNaN(_v)) return null;
}
String _formula_str = null;
string exinf = "";
if (order == 1)
{
if (coeff[0] != 0)
exinf = (coeff[0] > 0 ? " + " : " - ") + Math.Abs(coeff[0]).ToString();
_formula_str = "Y = " + coeff[1].ToString() + "X" + exinf;
}
else if (order > 1)
{
_formula_str = "Y = " + coeff[coeff.Count - 1].ToString() + "X^" + order;
for (int i = coeff.Count - 2; i >= 0; i--)
{
if (coeff[i] == 0) continue;
exinf = (coeff[i] > 0 ? " + " : " - ") + Math.Abs(coeff[i]).ToString();
switch (i)
{
case 0:
_formula_str += exinf;
break;
case 1:
_formula_str += exinf + "X";
break;
default:
_formula_str += exinf + "X^" + i;
break;
}
}
}
return _formula_str;
}
catch (System.Exception ex)
{
Debug.WriteLine(ex);
return null;
}
}
#endregion
}
#endregion
#region 对数拟合
public class CLogFitting : CLeastSquareFitting
{
public static List<Double> Fitting(List<PointF> point_list, bool zeroPassage)
{
if ((point_list == null) || (point_list.Count == 0))
return null;
List<PointF> _log_point_list = new List<PointF>();
foreach (PointF _point in point_list)
{
_log_point_list.Add(new PointF((float)Math.Log10(_point.X), (float)Math.Log10(_point.Y)));
}
CoeffMatrix _coeff_matrix = CreateCoeffMatrix(_log_point_list, 1, zeroPassage);
List<double> _coefficients = GaussianElimination(_coeff_matrix, zeroPassage);
return _coefficients;
}
public static string GetFormula(List<double> coeff)
{
if ((coeff == null) || (coeff.Count != 2))
return null;
//
foreach (double _value in coeff)
{
if (Double.IsNaN(_value)) return null;
}
return "ln(Y) = " + coeff[1].ToString("f1") + "ln(X) + " + ((coeff[0] == 0) ? "" : coeff[0].ToString("f1"));
}
}
#endregion
}
|
SQL
|
UTF-8
| 5,564
| 3.21875
| 3
|
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 80012
Source Host : localhost:3306
Source Database : eat
Target Server Type : MYSQL
Target Server Version : 80012
File Encoding : 65001
Date: 2019-01-28 13:20:15
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for admin
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`pwd` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES ('1', 'mr', 'pbkdf2:sha256:50000$TkExX9Jm$d63477853a17dcaedcd52be4b6213ebb74b61a12456762ac19d6b7dfb559aa57');
-- ----------------------------
-- Table structure for alembic_version
-- ----------------------------
DROP TABLE IF EXISTS `alembic_version`;
CREATE TABLE `alembic_version` (
`version_num` varchar(32) NOT NULL,
PRIMARY KEY (`version_num`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of alembic_version
-- ----------------------------
INSERT INTO `alembic_version` VALUES ('9de4a4f0b761');
-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`addtime` datetime DEFAULT NULL,
`order_num` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `ix_category_addtime` (`addtime`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of category
-- ----------------------------
INSERT INTO `category` VALUES ('1', '东北菜', '2018-11-19 17:35:33', '1');
INSERT INTO `category` VALUES ('2', '川菜', '2018-11-19 17:41:20', '2');
INSERT INTO `category` VALUES ('3', '湘菜', '2018-11-19 17:47:45', '3');
-- ----------------------------
-- Table structure for food
-- ----------------------------
DROP TABLE IF EXISTS `food`;
CREATE TABLE `food` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`addtime` datetime DEFAULT NULL,
`cate_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cate_id` (`cate_id`),
KEY `ix_food_addtime` (`addtime`),
CONSTRAINT `food_ibfk_1` FOREIGN KEY (`cate_id`) REFERENCES `category` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of food
-- ----------------------------
INSERT INTO `food` VALUES ('3', '第三鲜', '2018-11-28 16:42:50', '1');
INSERT INTO `food` VALUES ('4', '土豆炖粉条', '2018-11-28 16:42:58', '1');
INSERT INTO `food` VALUES ('5', '翠花酸菜', '2018-11-28 16:43:11', '1');
INSERT INTO `food` VALUES ('6', '水煮鱼', '2018-11-28 17:52:56', '2');
INSERT INTO `food` VALUES ('7', '麻婆豆腐', '2018-11-28 17:53:20', '2');
INSERT INTO `food` VALUES ('8', '四川火锅', '2018-11-28 17:53:28', '2');
INSERT INTO `food` VALUES ('9', '回锅肉', '2018-11-28 17:54:04', '2');
INSERT INTO `food` VALUES ('10', '毛血旺', '2018-11-28 17:54:23', '2');
INSERT INTO `food` VALUES ('11', '口水鸡', '2018-11-28 17:54:38', '2');
INSERT INTO `food` VALUES ('12', '剁椒鱼头', '2018-12-03 18:03:37', '3');
INSERT INTO `food` VALUES ('13', '锅包肉', '2018-12-04 10:57:39', '2');
INSERT INTO `food` VALUES ('14', '麻辣烫', '2018-12-04 10:57:55', '2');
INSERT INTO `food` VALUES ('25', '干锅茶树菇', '2018-12-11 13:19:09', '3');
INSERT INTO `food` VALUES ('26', '东安子鸡', '2018-12-11 13:25:52', '3');
INSERT INTO `food` VALUES ('27', '猪肉炖粉条', '2018-12-21 13:22:26', '1');
INSERT INTO `food` VALUES ('28', '锅包肉', '2018-12-21 13:22:57', '1');
-- ----------------------------
-- Table structure for record
-- ----------------------------
DROP TABLE IF EXISTS `record`;
CREATE TABLE `record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`food` varchar(255) DEFAULT NULL,
`number` int(11) DEFAULT NULL,
`addtime` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `ix_record_addtime` (`addtime`),
CONSTRAINT `record_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of record
-- ----------------------------
INSERT INTO `record` VALUES ('10', '8', '水煮鱼', '1', '2018-12-23 10:12:57');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`openid` varchar(50) DEFAULT NULL,
`nickname` varchar(100) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
`avatar` varchar(200) DEFAULT NULL,
`addtime` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `phone` (`phone`),
KEY `ix_user_addtime` (`addtime`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('8', 'oVAL60CQxQ1sxIE-r4AT21p-3_eg', '冯春龙', null, 'https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKGibzXbuZbwxEcKQBbOEVQGHmsC1HsLRc1Qk5jLSQf2ichmQr1kshDtFOnzgb3cvNjUpK7HX2OX5cw/132', '2018-12-17 16:43:43');
|
Java
|
UTF-8
| 988
| 2.421875
| 2
|
[] |
no_license
|
package org.courseapi.course;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.courseapi.topic.Topic;
@Entity
public class Course {
public Course() {
}
public Course(String id,String name,String url) {
super();
this.id=id;
this.name = name;
this.url=url;
}
@Id
private String id;
private String name;
private String url;
@ManyToOne
private Topic topic;
@JsonIgnore
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
C
|
UTF-8
| 1,488
| 3.4375
| 3
|
[] |
no_license
|
/* Shows how to write a simple command-line interpreter. The parent accepts user comands and
* forks a child process to execute those commands.
*
* Author: Naga Kandasamy
* Date created: 1/4/2009
* Date modified: 6/23/2018
*
* Compile the code as follows: gcc simple_interpreter.c -o simple_interpreter -std=c99 -Wall
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#define BUF_LEN 256
int
main (int argc, char **argv)
{
char buffer[BUF_LEN];
int pid;
int status;
printf ("$ "); /* Simulate a shell prompt */
while ((fgets(buffer, BUF_LEN, stdin)) != NULL){
buffer[strlen(buffer) - 1] = '\0'; /* Null terminate the string */
if (!strcmp(buffer, "quit")){
printf ("Bye bye. \n");
exit (0);
}
if ((pid = fork ()) < 0){
perror ("Fork");
exit (0);
}
else if (pid == 0){ /* Child code */
/* Execute the program supplied by the user.
* Note: our ultra-simple design won't work if the supplied program requires command-line arguments
* */
execlp (buffer, buffer, (char *) NULL);
exit (0);
}
/* Parent code */
if((pid = waitpid (pid, &status, 0)) < 0)
printf ("Error executing shell command! \n");
printf ("$ ");
}
}
|
Python
|
UTF-8
| 579
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
import threading
class StoppableThread(threading.Thread):
"""Basic Stoppable Thread Wrapper
Adds event for stopping the execution
loop and exiting cleanly."""
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.stop_event = threading.Event()
self.daemon = True
def start(self):
if not self.is_alive():
self.stop_event.clear()
threading.Thread.start(self)
def stop(self):
if self.is_alive():
self.stop_event.set()
self.join()
|
Java
|
UTF-8
| 1,749
| 2.109375
| 2
|
[] |
no_license
|
package com.target.pages;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import com.target.domainObject.User;
import com.target.pages.identifiers.TargetListGiftGiverPageElements;
public class TargetListGiftGiverPage extends AbstractPage{
private TargetListGiftGiverPageElements elements;
public TargetListGiftGiverPage(WebDriver driver) {
super(driver);
}
@Override
public void setPageElement(Object pageElement){
this.elements = (TargetListGiftGiverPageElements) pageElement;
}
public void verifyUserIsOnListGiftGiver(User user) {
waitUntil(50, ExpectedConditions.presenceOfElementLocated(By.id(elements.getListNameId())));
Assert.assertTrue(elements.getListOwnerName().getText().contains(user.getFirstName()));
}
public void clickOnAddToCartFromTargetListGiftGiver() {
elements.getAddToCartButtonIdFromTargetListGiftGiver().click();
}
public void selectsTheITemForListOwner() {
waitUntil(50, ExpectedConditions.presenceOfElementLocated(By.id(elements.getThisItemIsForOverlayId())));
elements.getListOwnerId().click();
}
public void clicksOnAddToCartOnThisItemIsForOverlay() {
WebElement addToCartButton = elements.getAddToCartButton();
waitUntil(50,ExpectedConditions.visibilityOf(addToCartButton));
addToCartButton.click();
}
public void getListGiftGiverPDPUrl() {
// waitUntil(50, ExpectedConditions.presenceOfElementLocated(By.id(elements.getListNameId())));
elements.getListGiftGiverViewURL().click();
}
public void verifyTargetListsPageOfUnSignedUserIsLoaded() {
}
}
|
C++
|
UTF-8
| 424
| 2.921875
| 3
|
[] |
no_license
|
#include<future>
#include<iostream>
#include<chrono>
#include<thread>
int test()
{
int n=100;
std::this_thread::sleep_for(std::chrono::seconds(5));
return n;
}
int test1()
{
int n = 200;
std::this_thread::sleep_for(std::chrono::seconds(5));
return n;
}
int main1()
{
{
using namespace std;
shared_future<int>rust(async(test));
cout << test1() + rust.get() << endl;
}
return 0;
}
|
TypeScript
|
UTF-8
| 478
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import {
ReducerDictionary,
handleSimpleReducerUpdates,
createReducer,
} from "../state/ReduxUtils";
import { ShopActionTypes } from "./ShopActions";
export interface ShopState {
shopOrigin: string;
}
export const shopInitialState: ShopState = { shopOrigin: undefined };
const reducers: ReducerDictionary<ShopState> = {
...handleSimpleReducerUpdates([ShopActionTypes.SHOP_LOAD]),
};
export const shopReducer = createReducer<ShopState>(shopInitialState, reducers);
|
C++
|
UTF-8
| 2,764
| 2.546875
| 3
|
[] |
no_license
|
#ifndef QMCCONVCHECKER_HH_
#define QMCCONVCHECKER_HH_
#include <vector>
#include <cmath>
#include <cfloat>
#include <cassert>
#include "mcuncert/QMCUncertaintyCalculator.hh"
#include "AbsConvergenceChecker.hh"
class QMCConvChecker : public AbsConvergenceChecker
{
public:
// This class constructor has the following input arguments:
// double dt which is the maximum time we allow for our integration,
// unsigned nDeltaJes that says how many DeltaJes are being integrated,
// double tol that is the relative error tolerance at which the
// integration will stop if the bound on the error is smaller, and
// double perc which is the percentage of DeltaJes that need to satisfy tol.
//
// Input arguments qmcuncert_m_min, qmcuncert_l_star, and qmcuncert_r_lag
// are passed to the constructor of QMCUncertaintyCalculator.
//
inline QMCConvChecker(const double dt, const unsigned nDeltaJes,
const double tol, const double perc,
const unsigned qmcuncert_m_min,
const unsigned qmcuncert_l_star,
const unsigned qmcuncert_r_lag)
: qmcuncer_(nDeltaJes, mcuncert::QMCUncertaintyCalculator(
qmcuncert_m_min, qmcuncert_l_star, qmcuncert_r_lag)),
tmax_(dt),
reltol_(tol),
pertol_(perc),
jesNumbersize_(nDeltaJes)
{
assert(jesNumbersize_);
}
inline virtual ~QMCConvChecker() {}
inline virtual ConvergenceStatus check(
const double timeElapsed,
const std::vector<std::vector<npstat::StatAccumulator> >& ) const
{
unsigned converged = 0;
for (unsigned ijes = 0; ijes < jesNumbersize_; ++ijes)
if (myRelUncert(ijes) < reltol_)
++converged;
if (static_cast<double>(converged)/jesNumbersize_ > pertol_)
return CS_CONVERGED;
else if (timeElapsed >= tmax_)
return CS_OUT_OF_TIME;
else
return CS_CONTINUE;
}
inline virtual void accumulate(const unsigned i, const double value)
{
qmcuncer_.at(i).addPoint(value);
}
inline virtual double getRelUncertainty(const unsigned i) const
{
assert(i < jesNumbersize_);
return myRelUncert(i);
}
private:
QMCConvChecker();
inline double myRelUncert(const unsigned ijes) const
{
const double absmean = fabs(qmcuncer_[ijes].mean());
return qmcuncer_[ijes].meanUncertainty()/(absmean + DBL_EPSILON);
}
std::vector<mcuncert::QMCUncertaintyCalculator> qmcuncer_;
double tmax_;
double reltol_;
double pertol_;
unsigned jesNumbersize_;
};
#endif // QMCCONVCHECKER_HH_
|
Shell
|
UTF-8
| 15,464
| 3.703125
| 4
|
[] |
no_license
|
#!/bin/bash
# Git Pushy Simple Build Deployment Framework
#
# @link http://gitpushy.com
# @author Micon Frink & Friends <frink@frinknet.com>
# @copyright (c) 2013 - FRINKnet and the Expatriated Lemurs of Borneo
# Licenced under the MIT license see - http://lemurs.mit-license.org/
gitpushy-branch-name() {
local branch_name=$(git symbolic-ref -q HEAD)
echo ${branch_name##refs/heads/}
}
gitpushy-build() {
# check pushy status
[ $PUSHY_STATUS != 0 ] && return $PUSHY_STATUS
local IO_CMD=gitpushy-$1-build.command
local IO_OUT=gitpushy-$1-build.output
local IO_ERR=gitpushy-$1-build.error
echo "GitPushy - Building $PUSHY_REPO:$PUSHY_BRANCH at $HOSTNAME:$PUSHY_BUILD_DIR"
# build rsync command (complex because we honor gitattributes
PUSHY_SYNC="rsync -a --exclude='.git*' $(gitpushy-cat .gitattributes|grep export-ignore|cut -d' ' -f1|tr '\n' '\0' | xargs -0 -I {} echo "--exclude='{}'" | tr '\n' ' ')"
# Rsync files to PUSHY_STAGE_DIR
if [ $PUSHY_REMOTE = 0 ]; then
PUSHY_SYNC="$PUSHY_SYNC "'"$PUSHY_BUILD_DIR"'" '$PUSHY_STAGE_DIR/'"
else
PUSHY_SYNC="$PUSHY_SYNC --rsh='ssh -p$PUSHY_PORT' "'"$PUSHY_BUILD_DIR/"'" '$PUSHY_USER@$PUSHY_SERVER:$PUSHY_STAGE_DIR/'"
fi
# prepare pushy build script
echo "$PUSHY_ENV" > $IO_CMD
echo "PUSHY_TRIGGER='$1'" >> $IO_CMD
echo "PUSHY_STATUS='$PUSHY_STATUS'" >> $IO_CMD
echo 'cd "$PUSHY_BUILD_DIR" > /dev/null' >> $IO_CMD
echo '[ $? != 0 ] && echo "directory does not exist - $PUSHY_BUILD_DIR" >&2 && exit 404' >> $IO_CMD
echo "git reset --hard HEAD > /dev/null" >> $IO_CMD
gitpushy-script build $1 >> $IO_CMD
echo "$PUSHY_SYNC" >> $IO_CMD
echo 'exit $PUSHY_STATUS' >> $IO_CMD
# show commands run if verbosity is set
[ $PUSHY_VERBOSE != 0 ] && cat $IO_CMD | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-$1-build: {}"
# run pushy build srcipts
(cat $IO_CMD | bash) 1> >(tee $IO_OUT) 2> >(tee $IO_ERR) | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - .gitpushy-$1-build - {}"
# capture execution status
PUSHY_STATUS=${PIPESTATUS[0]}
[ $PUSHY_STATUS = 0 ] && [ -s gitpushy-$1-build.error ] && PUSHY_STATUS=500
# return pushy status
return $PUSHY_STATUS
}
gitpushy-stage() {
# check pushy status
[ $PUSHY_STATUS != 0 ] && return $PUSHY_STATUS
local IO_CMD=gitpushy-$1-stage.command
local IO_OUT=gitpushy-$1-stage.output
local IO_ERR=gitpushy-$1-stage.error
echo "GitPushy - Staging $PUSHY_REPO:$PUSHY_BRANCH in $PUSHY_SERVER:$PUSHY_STAGE_DIR"
# prepare pushy stage script
echo "$PUSHY_ENV" > $IO_CMD
echo "PUSHY_TRIGGER='$1'" >> $IO_CMD
echo "PUSHY_STATUS='$PUSHY_STATUS'" >> $IO_CMD
echo 'cd "$PUSHY_STAGE_DIR" > /dev/null' >> $IO_CMD
echo '[ $? != 0 ] && echo "directory does not exist - $PUSHY_STAGE_DIR" >&2 && exit 404' >> $IO_CMD
gitpushy-script stage $1 >> $IO_CMD
echo 'exit $PUSHY_STATUS' >> $IO_CMD
# show commands run if verbosity is set
[ $PUSHY_VERBOSE != 0 ] && cat $IO_CMD | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-$1-stage: {}"
# run pushy stage scripts
if [ $PUSHY_REMOTE = 0 ]; then
(cat $IO_CMD | bash) 1> >(tee $IO_OUT) 2> >(tee $IO_ERR) | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - .gitpushy-$1-stage - {}"
else
(cat $IO_CMD | ssh -p $PUSHY_PORT $PUSHY_USER@$PUSHY_SERVER bash) 1> >(tee $IO_OUT) 2> >(tee $IO_ERR) | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - .gitpushy-$1-stage - {}"
fi
# capture exit status
PUSHY_STATUS=${PIPESTATUS[0]}
[ $PUSHY_STATUS = 0 ] && [ -s gitpushy-$1-stage.error ] && PUSHY_STATUS=500
# return pushy status
return $PUSHY_STATUS
}
gitpushy-deploy() {
# check pushy status
[ $PUSHY_STATUS != 0 ] && return $PUSHY_STATUS
local IO_CMD=gitpushy-$1-deploy.command
local IO_OUT=gitpushy-$1-deploy.output
local IO_ERR=gitpushy-$1-deploy.error
echo "GitPushy - Deploying $PUSHY_REPO:$PUSHY_BRANCH to $PUSHY_SERVER:$PUSHY_DEPLOY_DIR"
#prepare pushy deploy script
echo "$PUSHY_ENV" > $IO_CMD
echo "PUSHY_TRIGGER='$1'" >> $IO_CMD
echo "PUSHY_STATUS='$PUSHY_STATUS'" >> $IO_CMD
echo 'cd "$PUSHY_DEPLOY_DIR"' >> $IO_CMD
echo 'if [ $? != 0 ]; then' >> $IO_CMD
echo 'echo "Deploying to blank directory: $PUSHY_DEPLOY_DIR"' >> $IO_CMD
echo 'elif [ -n "$PUSHY_DEPLOY_BACKUP" ]; then' >> $IO_CMD
echo 'tar czf "$PUSHY_DEPLOY_BACKUP" .' >> $IO_CMD
echo 'fi' >> $IO_CMD
echo 'rm -rf $PUSHY_DEPLOY_DIR' >> $IO_CMD
echo 'cd "$PUSHY_STAGE_DIR"' >> $IO_CMD
echo '[ $? != 0 ] && echo "No stage directory: $PUSHY_STAGE_DIR" >&2 && exit 404' >> $IO_CMD
echo 'rsync -a --exclude='gitpushy-*' "$PUSHY_STAGE_DIR/" "$PUSHY_DEPLOY_DIR/"' >> $IO_CMD
echo 'cd "$PUSHY_DEPLOY_DIR"' >> $IO_CMD
echo '[ $? != 0 ] && echo "Deployment failed to $PUSHY_DEPLOY_DIR" >&2 && exit 404' >> $IO_CMD
gitpushy-script deploy $1 >> $IO_CMD
echo 'exit $PUSHY_STATUS' >> $IO_CMD
# show commands run if verbosity is set
[ $PUSHY_VERBOSE != 0 ] && cat $IO_CMD | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-$1-deploy: {}"
# run pushy deploy scripts
if [ $PUSHY_REMOTE = 0 ]; then
(cat $IO_CMD | bash) 1> >(tee $IO_OUT) 2> >(tee $IO_OUT) | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - .gitpushy-$1-deploy - {}"
else
(cat $IO_CMD | ssh -p $PUSHY_PORT $PUSHY_USER@$PUSHY_SERVER bash) 1> >(tee $IO_OUT) 2> >(tee $IO_ERR) | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - .gitpushy-$1-deploy - {}"
fi
# capture exit status
PUSHY_STATUS=${PIPESTATUS[0]}
[ $PUSHY_STATUS = 0 ] && [ -s gitpushy-$1-deploy.error ] && PUSHY_STATUS=500
# return pushy status
return $PUSHY_STATUS
}
gitpushy-trigger() {
# check pushy status
[ $PUSHY_STATUS != 0 ] && return $PUSHY_STATUS
# prepare pushy config script
PUSHY_CONFIG="$(gitpushy-script config $1)"
PUSHY_CUSTOM="$(gitpushy-script custom $1)"
PUSHY_TRIGGER="$1"
# return 404 if script doesnt exist
[ -z "$PUSHY_CONFIG$PUSHY_CUSTOM" ] && return 404
# run config scripts for deployment
eval "$PUSHY_CONFIG" 1> >(tee gitpushy-$1-config.output) 2> >(tee gitpushy-$1-config.error)> >(tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-$1-config: {}")
# capture exit status
PUSHY_STATUS=$?
[ $PUSHY_STATUS = 0 ] && [ -s gitpushy-$1-config.error ] && PUSHY_STATUS=500
# set pushy remote vs local
[ "$PUSHY_SERVER" != "$(hostname)" ] && PUSHY_REMOTE=1
# setup pushy environment variables
export PUSHY_ENV="
PUSHY_BUILD_DIR="$(echo "$PUSHY_BUILD_DIR" | sed 's/^~/$HOME/')"
PUSHY_STAGE_DIR="$(echo "$PUSHY_STAGE_DIR" | sed 's/^~/$HOME/')"
PUSHY_DEPLOY_DIR="$(echo "$PUSHY_DEPLOY_DIR" | sed 's/^~/$HOME/')"
PUSHY_DEPLOY_BACKUP="$(echo "$PUSHY_DEPLOY_BACKUP" | sed 's/^~/$HOME/')"
PUSHY_VERBOSE='$PUSHY_VERBOSE'
PUSHY_SERVER='$PUSHY_SERVER'
PUSHY_REMOTE='$PUSHY_REMOTE'
PUSHY_BRANCH='$PUSHY_BRANCH'
PUSHY_PORT='$PUSHY_PORT'
PUSHY_USER='$PUSHY_USER'
PUSHY_REPO='$PUSHY_REPO'
"
# show commands run if verbosity is set
[ $PUSHY_VERBOSE != 0 ] && echo "$PUSHY_CONFIG" | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-$1-config: - {}"
# show environment if verbosity is set
[ $PUSHY_VERBOSE != 0 ] && echo "$PUSHY_ENV" | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-environment - {}"
# run deployment scripts
if [ $PUSHY_STATUS != 0 ]; then
local DEPLOYMENT_RUN="$1 config"
elif [ -n "$PUSHY_CUSTOM" ]; then
local DEPLOYMENT_RUN="$1 custom script"
echo "GitPushy - Calling $DEPLOYMENT_RUN"
echo "----------"
# show commands run if verbosity is set
[ $PUSHY_VERBOSE != 0 ] && echo "$PUSHY_CUSTOM" | tr '\n' '\0' | xargs -0 -I {} echo "GitPushy - gitpushy-$1-custom: {}"
# run custom script
(eval "$PUSHY_CUSTOM" 1> >(tee gitpushy-$1-custom.output) 2> >(tee gitpushy-$1-custom.error))
# capture exit status
PUSHY_STATUS=$?
[ $PUSHY_STATUS = 0 ] && [ -s gitpushy-$1-custom.error ] && PUSHY_STATUS=500
echo "----------"
elif [ -n "$PUSHY_DEPLOY_DIR" ]; then
local DEPLOYMENT_RUN="$1 deployment"
echo "GitPushy - Calling $DEPLOYMENT_RUN"
gitpushy-build $1
gitpushy-stage $1
gitpushy-deploy $1
else
local DEPLOYMENT_RUN="$1 config"
echo "GitPushy - Loaded $1 configuration"
return;
fi
# echo status
if [ $PUSHY_STATUS = 0 ]; then
echo "GitPushy - Completed $DEPLOYMENT_RUN"
else
echo "GitPushy - Exited $DEPLOYMENT_RUN with status $PUSHY_STATUS"
fi
# return pushy status
return $PUSHY_STATUS
}
gitpushy-push-branch() {
# Export pushy variables to main environment
export PUSHY_DEPLOY_BACKUP="~/$PUSHY_REPO-$(date +%Y%m%d-%H%M%S).tgz"
export PUSHY_DEPLOY_DIR=""
export PUSHY_BUILD_DIR="/tmp/pushy-$1-build.$RANDOM$RANDOM"
export PUSHY_STAGE_DIR="~/pushy-staging-$PUSHY_REPO-$1"
export PUSHY_VERBOSE=0
export PUSHY_STATUS=0
export PUSHY_REMOTE=0
export PUSHY_BRANCH="$1"
export PUSHY_SERVER="$HOSTNAME"
export PUSHY_TRIGGERS=()
export PUSHY_TRIGGER=""
export PUSHY_PORT=22
export PUSHY_USER=$(whoami)
export PUSHY_REPO="$PUSHY_REPO"
# check if branch exists
[ -z "$PUSHY_BRANCH" ] && "BRANCH was not passed to gitpushy-push-branch" && return 1
[ ! -f $GIT_DIR/refs/heads/$PUSHY_BRANCH ] && echo "$PUSHY_BRANCH does not exist in $PUSHY_REPO" && return 1
# check if this branch has gitpushy data
[ ! -f $GIT_DIR/hooks/gitpushy-$PUSHY_BRANCH-branch ] && [ -z "$(gitpushy-script config main;gitpushy-script custom main)" ] && echo "GitPushy - Uncofigured branch $PUSHY_REPO:$PUSHY_BRANCH" && return 0
# remember current repo settings
local REPO_DIR=$GIT_DIR
local REPO_BARE=$PWD
# make a switch to clean local clone
gitpushy-clone-temp $PUSHY_BUILD_DIR
[ $? != 0 ] && echo "GitPushy - Failed to clone repo to $PUSHY_BUILD_DIR" >&2 && return $?
# reorient git
export GIT_DIR=$PUSHY_BUILD_DIR/.git
# Process GitPushy Branch Hooks
if [ -f $REPO_BARE/hooks/gitpushy-$PUSHY_BRANCH-branch ]; then
echo "GitPushy - Custom GitPushy Hook: pushy-$PUSHY_BRANCH-branch"
# run branch hook
(source $REPO_BARE/hooks/gitpushy-$PUSHY_BRANCH-branch 1> >(tee gitpushy-$PUSHY_BRANCH-branch.output) 2> >(tee gitpushy-$PUSHY_BRANCH-branch.error))
# capture exit status
PUSHY_STATUS=$?
[ -s gitpushy-$PUSHY_BRANCH-branch.error ] && PUSHY_STATUS=500
else
# run main trigger
gitpushy-trigger main
# loop through addtional triggers
[ $PUSHY_STATUS = 0 ] && for PUSHY_TRIGGER in ${PUSHY_TRIGGERS[@]}; do
gitpushy-trigger $PUSHY_TRIGGER
done
fi
# clean up after deploy
gitpushy-clean-temp $PUSHY_BUILD_DIR
# reset git orientation
export GIT_DIR=$REPO_DIR
cd $REPO_BARE
return $PUSHY_STATUS
}
gitpushy-push-replicate() {
[ -z "$1" ] && return 402
[ "$(gitpushy-committer)" = "GitPushy" ] && return 401
local SERVER=""
for SERVER in $@; do
if gitpushy-server-is-local $SERVER; then
continue
elif git status 1>/dev/null 2>/dev/null; then
echo "GitPushy - Syncronizing $1"
git remote add $1 ssh://$PUSHY_USER@$1:$PUSHY_PORT/$PUSHY_REPO
git checkout -b $1 1>/dev/null 2>/dev/null
git fetch $1 1>/dev/null 2>/dev/null
if [ $? != 0 ]; then
echo "GitPushy - Failed to fetch ssh://$PUSHY_USER@$1:$PUSHY_PORT/$PUSHY_REPO"
elif git merge --no-commit $1/$PUSHY_BRANCH $1 1>/dev/null 2>/dev/null; then
git commit --author="GitPushy <$PUSHY_USER@$PUSHY_SERVER>" --allow-empty -am "Auto-merged from $1 on $PUSHY_SERVER" 1>/dev/null 2>/dev/null
git push $1 $1:$PUSHY_BRANCH 1>/dev/null 2>/dev/null
if [ $? = 0 ]; then
echo "GitPushy - Syncronization complete!"
else
echo "GitPushy - Failed syncronize to $1 with status $?"
fi
else
git merge --abort 1>/dev/null 2>/dev/null
echo "GitPushy - Cannot resolve merge conficts with remote $1 $PUSHY_BRANCH"
fi
git checkout $PUSHY_BRANCH 1>/dev/null 2>/dev/null
fi
done
}
gitpushy-clone-temp() {
local CLONE_STATUS=0
[ -z "$PUSHY_BRANCH" ] && PUSHY_BRANCH=$(gitpushy-branch-name)
[ -z "$1" ] && echo "GitPushy - No build directory specified" && local CLONE_STATUS=404
if [ $CLONE_STATUS = 0 ]; then
# make a clean local clone
(rm -rf $1; git clone -b $PUSHY_BRANCH . $1) >/dev/null
local CLONE_STATUS=${PIPESTATUS[0]}
# switch to clone
cd $1
fi
if [ $CLONE_STATUS != 0 ]; then
echo "GitPushy - Exited cloning $1 with status $CLONE_STATUS"
fi
# return pushy status
return $CLONE_STATUS
}
gitpushy-clean-temp() {
local CLEAN_STATUS=0
[ -z "$1" ] && echo "GitPushy - No build directory specified" && local CLEAN_STATUS=404
[ $PUSHY_STATUS != 0 ] && echo "GitPushy - Leaving build directory $1" && return 500
if [ $CLEAN_STATUS = 0 ]; then
(rm -rf $1) >/dev/null
local CLEAN_STATUS=${PIPESTATUS[0]}
# switch to clone
[ -n "$PUSHY_BARE" ] && cd $PUSHY_BARE
fi
# echo status
if [ $CLEAN_STATUS != 0 ]; then
echo "GitPushy - Exited clean-up $1 with status $CLEAN_STATUS"
fi
# return pushy status
return $CLEAN_STATUS
}
gitpushy-script() {
[ -z "$PUSHY_BRANCH" ] && PUSHY_BRANCH=$(gitpushy-branch-name)
gitpushy-cat .gitpushy-$1 .gitpushy-$1-$PUSHY_BRANCH
[ -n "$2" ] && gitpushy-script $2-$1 ${@:3}
}
gitpushy-cat() {
[ -z "$PUSHY_BRANCH" ] && PUSHY_BRANCH=$(gitpushy-branch-name)
# cat files in repo
grep -v "^\s*$" <(for file in $@; do
git show refs/heads/$PUSHY_BRANCH:$file 2>/dev/null
done)
}
gitpushy-init() {
export PUSHY_REPO=""
export PUSHY_BRANCH=""
export PUSHY_BRANCHES=()
[ -z "$PUSHY_REPO" ] && if [ $(git rev-parse --is-bare-repository) = true ]; then
PUSHY_REPO=$(basename "$PWD")
PUSHY_REPO=${PUSHY_REPO%.git}
else
PUSHY_REPO=$(basename $(readlink -nf "$PWD"/..))
fi
while read oldrev newrev refname; do
PUSHY_BRANCHES+=($(git rev-parse --symbolic --abbrev-ref $refname))
done
OFS=$IFS;
IFS=$'\n'
PUSHY_BRANCHES=($(sort -u <<<"${PUSHY_BRANCHES[@]}"))
IFS=$OFS;
for PUSHY_BRANCH in ${PUSHY_BRANCHES[@]}; do
gitpushy-push-branch $PUSHY_BRANCH
done
}
gitpushy-committer() {
git log -1|grep -Po "(?<=Author:\s).*(?=\s+\<)"
}
gitpushy-server-ip() {
ping -c 1 $1 | grep -Po -m 1 '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}';
}
gitpushy-local-ips() {
ifconfig | grep -Po '(?<=addr:)[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
}
gitpushy-in-array() {
local x
for x in "${@:2}"; do
[ "$x" = "$1" ] && return 0
done
return 1
}
gitpushy-server-is-local() {
if gitpushy-in-array "$(gitpushy-server-ip $1)" $(gitpushy-local-ips); then
return 0
fi
return 1
}
|
Java
|
UTF-8
| 908
| 2.375
| 2
|
[] |
no_license
|
package com.screendemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etDemo = new EditText(this);
// 在代码中设置控件尺寸时,用dp单位规定尺寸,使用前转换成px单位
int dpWidth = DisplayUtil.dip2Px(this, 170);
int dpHeight = DisplayUtil.dip2Px(this, 50);
LayoutParams params = new LayoutParams(dpWidth, dpHeight);
addContentView(etDemo, params);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
C#
|
UTF-8
| 1,708
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace HermaFx.IO
{
public class TempFile : IDisposable
{
public string FullPath { get; private set; }
public TempFile()
{
this.FullPath = Path.GetTempFileName();
}
public TempFile(Stream data)
: this()
{
CopyStreamToFullPath(data);
}
public TempFile(string path)
{
Guard.Against<IOException>(File.Exists(path),
string.Format("Path {0} provided for TempFile already exists. TempFile cannot be created?!", path));
var directoryName = Path.GetDirectoryName(path);
Guard.Against<DirectoryNotFoundException>(!Directory.Exists(directoryName),
string.Format("Directory provided {0} for creating TempFile does not exists?!", directoryName));
// XXX: We create empty file to "reserve" path. Then dispose FileStream
File.Create(path).Dispose();
this.FullPath = path;
}
public TempFile(string path, Stream data)
: this(path)
{
CopyStreamToFullPath(data);
}
#region Private Methods
private void CopyStreamToFullPath(Stream data)
{
using (var stream = File.OpenWrite(FullPath))
{
data.CopyTo(stream);
stream.Flush();
}
}
#endregion
public override string ToString()
{
return FullPath;
}
public static implicit operator String(TempFile file)
{
return file.FullPath;
}
#region IDisposable Members
~TempFile() { Dispose(false); }
public void Dispose() { Dispose(true); }
private void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
}
if (FullPath != null)
{
try { File.Delete(FullPath); }
catch { } // best effort
FullPath = null;
}
}
#endregion
}
}
|
C++
|
UTF-8
| 1,178
| 3.046875
| 3
|
[] |
no_license
|
#include "ColaDeSerializacion.h"
#include "../../common/Excepcion.h"
#include <utility>
ColaSerializacion::ColaSerializacion() :
conditionVariable(),
cola(),
mutex(),
colaCerrada(false){}
SerializacionCliente ColaSerializacion::pop(){
std::unique_lock<std::mutex> lock(this->mutex);
while (this->cola.empty()){
if (this->colaCerrada){
throw Excepcion("Cola cerrada");
}
conditionVariable.wait(lock);
}
SerializacionCliente unCliente = std::move(this->cola.front());
this->cola.pop();
return unCliente;
}
void ColaSerializacion::push(SerializacionCliente cliente){
std::unique_lock<std::mutex> lock(this->mutex);
if (this->colaCerrada){
throw Excepcion("No se pueden encolar mas mensajes, la cola ha sido cerrada");
}
this->cola.push(std::move(cliente));
conditionVariable.notify_all();
}
void ColaSerializacion::cerrarCola(){
std::unique_lock<std::mutex> lock(this->mutex);
if (this->colaCerrada) return;
this->colaCerrada = true;
this->conditionVariable.notify_all();
}
|
Java
|
UTF-8
| 1,520
| 2.21875
| 2
|
[] |
no_license
|
package vn.com.hiringviet.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vn.com.hiringviet.dao.EndorseDAO;
import vn.com.hiringviet.dao.SkillResumeDAO;
import vn.com.hiringviet.dto.EndorseDTO;
import vn.com.hiringviet.model.Endorse;
import vn.com.hiringviet.model.SkillResume;
import vn.com.hiringviet.service.EndorseService;
import vn.com.hiringviet.util.DateUtil;
// TODO: Auto-generated Javadoc
/**
* The Class EndorseServiceImpl.
*/
@Service("endorseService")
public class EndorseServiceImpl implements EndorseService {
/** The endorse dao. */
@Autowired
private EndorseDAO endorseDAO;
/** The skill resume dao. */
@Autowired
private SkillResumeDAO skillResumeDAO;
/* (non-Javadoc)
* @see vn.com.hiringviet.service.EndorseService#create(vn.com.hiringviet.dto.EndorseDTO)
*/
@Override
public Integer create(EndorseDTO endorseDTO) {
Endorse endorse = new Endorse();
endorse.setAccount(endorseDTO.getAccount());
endorse.setCreatedDate(DateUtil.now());
SkillResume skillResume = skillResumeDAO.findOne(endorseDTO.getSkillResumeId());
endorse.setSkillResume(skillResume);
return endorseDAO.create(endorse);
}
/* (non-Javadoc)
* @see vn.com.hiringviet.service.EndorseService#deleteByAccountId(java.lang.Integer, java.lang.Integer)
*/
@Override
public boolean deleteByAccountId(Integer accountId, Integer skillResumeId) {
return endorseDAO.deleteByAccountId(accountId, skillResumeId);
}
}
|
C#
|
UTF-8
| 2,489
| 2.671875
| 3
|
[] |
no_license
|
using Mojio.Client.OBDDevice;
using Mojio.Client.OBDDevice.Contracts;
using Mojio.Client.OBDDevice.InTheHandBluetooth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsole
{
internal class Program
{
private static void Main(string[] args)
{
IOBDDevice bt = new BluetoothDevice();
var observer = new DeviceConnectionObserver();
observer.Subscribe(new ConsoleObserver());
bt.Subscribe(observer);
bt.StartDiscovery("OBDII");
while (observer.Vehicle == null)
{
Console.WriteLine("Waiting for Bluetooth connection to telematic device");
Task.Delay(1000).Wait();
}
Console.WriteLine("Got a connection to the bluetooth telematic device");
while (!observer.Connected)
{
Console.WriteLine("Waiting for Vehicle OBD Connectivity");
Task.Delay(1000).Wait();
}
Console.WriteLine("Connected to the Vehicle OBD Port");
Console.ReadKey();
}
}
public class ConsoleObserver : IObserver<IOBDParsedResult>
{
public ConsoleObserver()
{
System.Console.ForegroundColor = ConsoleColor.White;
}
private static object _lock = new object();
public void OnNext(IOBDParsedResult value)
{
lock (_lock)
{
if (value.Measure != null)
{
System.Console.WriteLine("{0} - {1} = {2}", value.Measure.TimeStamp, value.Measure.Name, value.Measure.Value);
}
else
{
System.Console.WriteLine("{2} : {1}, {0}", value.Raw.Replace(@"\r", "").Replace(@"\n", ""),
value.Request, value.RequestType);
}
}
}
public void OnError(Exception error)
{
lock (_lock)
{
System.Console.ForegroundColor = ConsoleColor.Red;
var value = (error as OBDException).ObdParsedResult;
System.Console.WriteLine("ERROR: {2} : {1}, {0}", value.Error, value.Request, value.RequestType);
System.Console.ForegroundColor = ConsoleColor.White;
}
}
public void OnCompleted()
{
}
}
}
|
JavaScript
|
UTF-8
| 3,475
| 2.78125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
var RingOffset = klass.create();
_.extend(RingOffset.prototype, {
initialize: function() {
this.speed = 0;
this.currentOffset = 0.0;
this.nextDecision = 0;
this.maxOffset = (Math.PI) / 8;
},
setWanderState: function() {
this.speed = randbound(-0.003, 0.003);
},
tick: function() {
var curTime = (new Date()).getTime();
if (curTime > this.nextDecision) {
this.setWanderState();
this.nextDecision = curTime + Math.round(randbound(2000, 7000));
}
this.currentOffset += this.speed;
if (this.currentOffset > this.maxOffset) {
this.currentOffset = this.maxOffset;
} else if (this.currentOffset < -this.maxOffset) {
this.currentOffset = -this.maxOffset;
}
}
});
// May want to track things using polar coords
// and then translating to x,y
var PiChart = klass.create();
_.extend(PiChart.prototype, {
initialize: function(app, pos, rad, n) {
this.application = app;
this.position = pos;
this.radius = rad;
this.wedges = [];
this.wedgeColors = [[255, 78, 78],
[78, 255, 78],
[78, 78, 255]];
this.nWedges = n;
for (var i=0; i<this.nWedges; i++) {
this.wedges.push(0.0);
}
this.rings = 6;
this.ringOffset = [];
for (var i=0; i<this.rings; i++) {
this.ringOffset.push(new RingOffset());
}
},
updateWedges: function(wedgeValues) {
for (var i=0; i<this.nWedges; i++) {
var val = wedgeValues[i] || 0;
this.wedges[i] = val;
}
},
tick: function() {
for (var i=0; i<this.rings; i++) {
this.ringOffset[i].tick()
}
},
capPath: function(g, r, w, h, d) {
var h1 = h - (w/2)
var x1 = h1 * Math.cos(r) + this.position[0];
var y1 = h1 * Math.sin(r) + this.position[1];
var r1 = r + Math.PI;
g.arc(x1, y1, w/2, r, r1, d);
},
renderWedge: function(g, r1, r2, rgba) {
var ringWidth = (this.radius / (this.rings * 2));
for (var i = 0; i < this.rings - 2; i++) {
var ringHeight = this.radius - (i * ringWidth * 2);
g.beginPath();
g.fillStyle = rgba;
var off = this.ringOffset[i].currentOffset;
g.arc(this.position[0], this.position[1], ringHeight,
r1 + off, r2 + off);
this.capPath(g, r2 + off, ringWidth, ringHeight, false);
g.arc(this.position[0], this.position[1], ringHeight - ringWidth,
r2 + off, r1 + off, true);
this.capPath(g, r1 + off, ringWidth, ringHeight, true);
g.fill();
g.closePath();
}
},
render: function(g) {
this.tick();
var last = 0;
var unclaimed = 1 - _.reduce(this.wedges, function (l, r) {
return l + r;
}, 0);
var buffer = (unclaimed * Math.PI * 2) / this.wedges.length;
for (var i=0; i<this.wedges.length; i++) {
var arc = this.wedges[i] * Math.PI * 2 + last;
if (this.wedges[i] !== 0) {
this.renderWedge(g, last, arc,
rgbaString(this.wedgeColors[i]));
}
last = arc + buffer;
}
}
});
// vim: set sts=4 sw=4 expandtab:
|
C++
|
UTF-8
| 2,409
| 3.453125
| 3
|
[] |
no_license
|
/* cohenSutherland.h
*
* Algoritmo de clipping de linhas; implementa LineClipper.
*/
#ifndef COHEN_SUTHERLAND_H
#define COHEN_SUTHERLAND_H
#include "render/clipping/lineClipper.h"
#include "render/clipping/clippingArea.h"
#include "math/point.h"
class CohenSutherland : public LineClipper<2> {
private:
ClippingArea ca;
public:
/* Cria e vincula à área de clipping 'a' */
CohenSutherland( ClippingArea a );
virtual void setArea( ClippingArea ) override;
virtual bool clip( Math::Point<2>&, Math::Point<2>& ) override;
virtual ~CohenSutherland() = default;
private:
/* Códigos da região em que se encontra o ponto, em relação
* à área de clipping.
* | |
* LEFT_TOP | TOP | RIGHT_TOP
* ------------+--------+-------------
* | |
* LEFT | MIDDLE | RIGHT
* | |
* ------------+--------+-------------
* LEFT_BOTTOM | BOTTOM | RIGHT_BOTTOM
* | |
* O quadrado central é delimitado pela área de clipping,
* de forma que um ponto que esteja dentro da área de clipping
* possuirá código MIDDLE.
*
* Os códigos das regiões é definido de forma que seja possível
* fazer operações bit-a-bit com eles e obter resultados corretos.
* Por exemplo, LEFT | TOP == TOP_LEFT, e
* unsigned char code = regionOf( v );
* if( code & TOP )
* testa se v está no topo da área de clipping.
*/
enum {
MIDDLE = 0x00,
LEFT = 0x01,
RIGHT = 0x02,
TOP = 0x10,
BOTTOM = 0x20,
TOP_LEFT = 0x11,
TOP_RIGHT = 0x12,
BOTTOM_LEFT = 0x21,
BOTTOM_RIGHT = 0x22
};
/* Retorna a região do ponto passado. */
unsigned char regionOf( Math::Point<2>& );
/* Efetua clipping no ponto passado, para que se enquadre na
* área de clipping.
*
* c é o coeficiente angular. Esta função modificará o ponto
* passado para que fique na extremidade mais próxima da área
* de clipping, mas ainda dentro de sua reta.
*
* Caso não haja interseção entre a reta e a área de clipping,
* false é retornado; caso contrário, o método retorna true. */
bool clip( Math::Point<2>&, double c );
};
#endif // COHEN_SUTHERLAND_H
|
C++
|
UTF-8
| 8,477
| 3.546875
| 4
|
[] |
no_license
|
// Member-function definitions for class HugeInteger
#include <iostream>
using namespace std;
#include "HugeInteger.h" // include definition of class HugeInteger
// default constructor; construct a zero HugeInteger with size 1
HugeInteger::HugeInteger()
: integer( 1 )
{
}
// constructor; construct a zero HugeInteger with size n
HugeInteger::HugeInteger( unsigned int n )
: integer( ( n > 0 ) ? n : 1 )
{
} // end HugeInteger constructor
// copy constructor
// constructs a HugeInteger with a copy of each of the elements in integerToCopy
HugeInteger::HugeInteger( const HugeInteger &integerToCopy )
: integer( integerToCopy.integer )
{
} // end HugeInteger copy constructor
// destructor; destroys the HugeInteger
HugeInteger::~HugeInteger()
{
} // end HugeInteger destructor
// overloaded assignment operator;
// const return avoids: ( a1 = a2 ) = a3
const HugeInteger &HugeInteger::assign( const HugeInteger &right )
{
if( &right != this ) // avoid self-assignment
integer.assign( right.integer );
return *this; // enables x = y = z, for example
}
// function that tests if two HugeIntegers are equal
bool HugeInteger::equal( const HugeInteger &right ) const
{
HugeInteger int1(*this);
HugeInteger int2(right);
unsigned int size1 = integer.size();
unsigned int size2 = right.integer.size();
vector::iterator it1 = int1.integer.end()-1;
vector::iterator it2 = int2.integer.end()-1;
if (size1 == size2)
{
for (; it1 >= int1.integer.begin(); --it1, --it2)
{
if (*it1 != *it2)
return false;
}
return true;
}
else
{
return false;
}
} // end function equal
// function that tests if one HugeInteger is less than another
bool HugeInteger::less( const HugeInteger &right ) const
{
HugeInteger int1(*this);
HugeInteger int2(right);
unsigned int size1 = integer.size();
unsigned int size2 = right.integer.size();
vector::iterator it1 = int1.integer.end()-1;
vector::iterator it2 = int2.integer.end()-1;
if (size1 > size2)
return false;
else if (size1 < size2)
return true;
else
{
for (; it1 >= int1.integer.begin(); --it1, --it2)
{
if (*it1 > *it2)
return false;
else if (*it1 < *it2)
return true;
else if (*it1 == *it2)
continue;
}
return false;
}
} // end function less
// function that tests if one HugeInteger is less than or equal to another
bool HugeInteger::lessEqual( const HugeInteger &right ) const
{
return ( less( right ) || equal( right ) );
} // end function lessEqual
// addition operator; HugeInteger + HugeInteger
HugeInteger HugeInteger::add( HugeInteger &op2 )
{
unsigned int op1Size = integer.size();
unsigned int op2Size = op2.integer.size();
unsigned int sumSize = ( op1Size >= op2Size ) ? op1Size + 1 : op2Size + 1;
HugeInteger sum( sumSize );
vector::iterator it1 = integer.begin();
vector::iterator it3 = sum.integer.begin();
for( ; it1 != integer.end(); ++it1, ++it3 )
*it3 = *it1;
vector::iterator it2 = op2.integer.begin();
for( it3 = sum.integer.begin(); it2 != op2.integer.end(); ++it2, ++it3 )
*it3 += *it2;
for( it3 = sum.integer.begin(); it3 != sum.integer.end() - 1; ++it3 )
if( *it3 > 9 )
{
( *it3 ) -= 10;
( *( it3 + 1 ) )++;
}
if( *it3 == 0 )
sum.integer.pop_back();
return sum;
} // end function add
// subtraction operator; HugeInteger - HugeInteger
HugeInteger HugeInteger::subtract( HugeInteger &op2 )
{
HugeInteger zero;
if( equal( op2 ) )
return zero;
HugeInteger difference( *this );
vector::iterator it1 = op2.integer.begin();
vector::iterator it2 = difference.integer.begin();
for (; it1 != op2.integer.end(); ++it1, ++it2)
*it2 -= *it1;
for (it2 = difference.integer.begin(); it2 < difference.integer.end(); ++it2)
{
if (*it2 < 0)
{
*it2 += 10;
*(it2 + 1) -= 1;
}
}
for (it2 = difference.integer.end() - 1; *it2 == 0; --it2)
difference.integer.pop_back();
return difference;
} // end function subtract
// multiplication operator; HugeInteger * HugeInteger
HugeInteger HugeInteger::multiply( HugeInteger &op2 )
{
HugeInteger zero;
if( isZero() || op2.isZero() )
return zero;
unsigned int productSize = integer.size() + op2.integer.size();
HugeInteger product( productSize );
vector::iterator it1 = integer.begin();
vector::iterator it2 = op2.integer.begin();
vector::iterator it3 = product.integer.begin();
for (unsigned int i = 0; i < integer.size(); ++i)
for (unsigned int j = 0; j < op2.integer.size(); ++j)
*(it3 + i + j) += *(it1 + i) * *(it2 + j);
for (it3 = product.integer.begin(); it3 < product.integer.end(); ++it3)
if (*it3 >= 10)
{
*(it3 + 1) += *(it3) / 10;
*(it3) %= 10;
}
for (it3 = product.integer.end() - 1; *it3 == 0; --it3)
product.integer.pop_back();
return product;
} // end function multiply
// division operator; HugeInteger / HugeInteger provided that op2 is not zero
HugeInteger HugeInteger::divide(HugeInteger& op2)
{
HugeInteger zero;
if (less(op2))
return zero;
HugeInteger quotient;
/*if (equal(op2))
{
quotient.integer.begin()[0] = 1;
return quotient;
}*/
HugeInteger remainder(*this);
unsigned int dividendSize = integer.size();
unsigned int divisorSize = op2.integer.size();
unsigned int quotientSize = quotient.integer.size();
unsigned int remainderSize = remainder.integer.size();
unsigned int n = dividendSize - divisorSize;
vector::iterator it1 = integer.begin();
vector::iterator it2 = op2.integer.begin();
vector::iterator it3 = quotient.integer.begin();
vector::iterator it4 = remainder.integer.begin();
unsigned int bufferSize = divisorSize + n;
HugeInteger buffer(dividendSize);
vector::iterator it5 = buffer.integer.begin();
//for (int i = divisorSize; i > 0; i--)
//buffer.integer.begin()[n + i - 1] = op2.integer.begin()[i - 1];
for (unsigned int i = divisorSize; i > 0; i--)
*(it5 + n + i - 1) = *(it2 + i - 1);
quotientSize = dividendSize - divisorSize;
if (less(buffer))
buffer.divideByTen();
else
{
quotientSize++;
quotient.integer.resize(quotientSize);
}
quotient.integer.resize(quotientSize);
for (it3 = quotient.integer.end() - 1; it3 >= quotient.integer.begin(); --it3)
{
while (buffer.lessEqual(remainder))
{
HugeInteger a(remainder.subtract(buffer));
remainder.assign(a);
++*it3;
if (remainder.isZero())
{
return quotient;
}
}
buffer.divideByTen();
}
return quotient;
} // end function divide
// modulus operator; HugeInteger % HugeInteger provided that op2 is not zero
HugeInteger HugeInteger::modulus( HugeInteger &op2 )
{
HugeInteger quotient = divide( op2 );
HugeInteger product = quotient.multiply( op2 );
HugeInteger remainder = subtract( product );
return remainder;
}
// convert a vector of decimal digits into a HugeInteger
void HugeInteger::convert( vector &v )
{
integer.resize( v.size() );
vector::iterator it1 = integer.end() - 1;
vector::iterator it2 = v.begin();
for( ; it2 != v.end(); --it1, ++it2 )
*it1 = *it2;
} // end function convert
// function that tests if a HugeInteger is zero
bool HugeInteger::isZero()
{
for( vector::iterator it = integer.begin(); it != integer.end(); ++it )
if ( *it != 0 )
return false;
return true;
}
// function that divides a HugeInteger by 10; shift a HugeInteger one position to the right
void HugeInteger::divideByTen()
{
vector::iterator it = integer.begin();
vector::iterator it2 = it;
for( ++it2; it2 != integer.end(); ++it, ++it2 )
*it = *it2;
integer.pop_back();
}
// overloaded output operator
void HugeInteger::output( ostream &outFile )
{
vector::iterator it = integer.end() - 1;
for( ; it != integer.begin() - 1; --it )
if( *it < 10 )
outFile << *it;
outFile << endl;
} // end function output
|
C
|
UTF-8
| 1,499
| 3.515625
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fonction.h"
char lireCaractere()
{
char caractere = 0;
caractere = getchar(); /*L'utilisateur entre une lettre, cette fonction getchar() est une fonction de stdio
elle revient au même que d'écrire: scanf("%c", &lettreEntre), sauf que la diff
est que l'on pourras ne pas prendre en compte la touche Entree, voir ci-dessous. */
caractere = toupper(caractere);/*La fonction toupper va mettre en majuscule le caractère, si ce n'est déjà fait.*/
while(getchar() != '\n'); /*Contrairement à la fonction scanf qui enregistre la touche Entree, ce qui fausse
le programme si l'on veut faire appelle à la fonction scanf dans le même code source
l'on peut avec cette fonction getchar faire une boucle jusqu'à ce que l'utilisateur
appuie sur Entree. Si par mégarde ou pour faire chier le monde l'utilsateur a
entrée un mot et non une lettre, c'est la première lettre qui seras pris en compte
Les autres lettres seront vidés de la mémoire, on dit qu'on vide le buffer.*/
}
void recherche(const char* motSecret, char* lettreEntre, int longueurChaine)
{
int i = 0;
for(i = 0; i < longueurChaine; i++)
{
if(motSecret[i] == lettreEntre)
{
motSecret[i] = lettreEntre;
}
}
}
|
C++
|
UTF-8
| 1,809
| 2.84375
| 3
|
[] |
no_license
|
/************************************************************
* (C) Voxel Farm Inc. 2015
*/
#pragma once
#include <stdint.h>
namespace HyVoxel
{
/****************************
* *
* Union Find *
* (Fast Classification) *
* *
****************************/
template <typename idxType>
class CUnionFind
{
public:
CUnionFind() {};
CUnionFind(idxType N);
~CUnionFind();
idxType Find(idxType id);
void Union(idxType id1, idxType id2);
void Reset();
protected:
struct node
{
idxType parent;
idxType rank;
};
node* uf;
idxType size;
};
template <typename idxType>
CUnionFind<idxType>::CUnionFind(idxType N)
{
this->size = N;
this->uf = VF_ALLOC(node, N);
for (idxType i = 0; i < N; i++)
{
uf[i].parent = i;
uf[i].rank = 0;
}
}
template <typename idxType>
CUnionFind<idxType>::~CUnionFind()
{
VF_FREE(uf);
}
template <typename idxType>
idxType CUnionFind<idxType>::Find(idxType id)
{
if (uf[id].parent != id)
{
uf[id].parent = Find(uf[id].parent);
}
return uf[id].parent;
}
template <typename idxType>
void CUnionFind<idxType>::Union(idxType id1, idxType id2)
{
if (id1 == id2)
{
return;
}
idxType id1Root = Find(id1);
idxType id2Root = Find(id2);
if (id1Root == id2Root)
{
return;
}
if (uf[id1Root].rank < uf[id2Root].rank)
{
uf[id1Root].parent = id2Root;
}
else if (uf[id1Root].rank > uf[id2Root].rank)
{
uf[id2Root].parent = id1Root;
}
else
{
uf[id2Root].parent = id1Root;
uf[id1Root].rank++;
}
}
template <typename idxType>
void CUnionFind<idxType>::Reset()
{
for (idxType i = 0; i < this->size; i++)
{
uf[i].parent = i;
uf[i].rank = 0;
}
}
typedef CUnionFind<uint16_t> CUnionFind16;
typedef CUnionFind<uint32_t> CUnionFind32;
}
|
C#
|
UTF-8
| 1,634
| 2.609375
| 3
|
[] |
no_license
|
using System;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
namespace BA.Examples.ServiceProcess.Services.Core
{
public abstract class PublishService<T> where T : class
{
protected static void FireEvent(params object[] args)
{
StackFrame stackFrame = new StackFrame(1);
string methodName = stackFrame.GetMethod().Name;
PublishTransient(methodName, args);
}
static void PublishTransient(string methodName, params object[] args)
{
T[] subscribers =
SubscriptionManager<T>.GetTransientList(methodName);
Publish(subscribers, false, methodName, args);
}
static void Publish(T[] subscribers, bool closeSubscribers,
string methodName, params object[] args)
{
WaitCallback fire = delegate(object subscriber)
{
Invoke(subscriber as T, methodName, args);
if (closeSubscribers)
{
using (subscriber as IDisposable)
{ }
}
};
Action<T> queueUp = delegate(T subscriber)
{
ThreadPool.QueueUserWorkItem(fire, subscriber);
};
Array.ForEach(subscribers, queueUp);
}
static void Invoke(T subscriber, string methodName, object[] args)
{
Type type = typeof(T);
MethodInfo methodInfo = type.GetMethod(methodName);
try { methodInfo.Invoke(subscriber, args); }
catch { }
}
}
}
|
PHP
|
UTF-8
| 1,292
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace ModuleBZ\YandexTurbo\Element;
use ModuleBZ\YandexTurbo;
class Rating {
/** @var float $value значение рейтинга */
protected $value;
/** @var float $best из скольки максимальных */
protected $best;
/**
* Rating constructor.
* @param float $value
* @param float $best
*/
public function __construct(float $value = 0,float $best=0) {
$this->value = $value;
$this->best = $best;
}
/**
* Установка значения рейтинга
* @param float $value
* @return Rating
*/
public function setValue(float $value): Rating
{
$this->value = $value;
return $this;
}
/**
* Установка максимального значения в рейтинге
* @param float $best
* @return Rating
*/
public function setBest(float $best): Rating
{
$this->best = $best;
return $this;
}
public function __toString() {
return
'<div itemscope itemtype="http://schema.org/Rating">'
.'<meta itemprop="ratingValue" content="'.$this->value.'"/>'
.'<meta itemprop="bestRating" content="'.$this->best.'"/>'
.'</div>';
}
}
|
Markdown
|
UTF-8
| 5,673
| 3
| 3
|
[] |
no_license
|
Scala version used: 10.4.2
I have encountered what I am fairly sure is broken behavior in case classes when members are declared using backquotes.
I have the following minimized test case:
```scala
object HelloScalaBug {
case class wrong(`a b`: Int, a: Int)
case class right(a: Int, `a b`: Int)
def main(args: Array[String]) {
val w = wrong(1, 2) // Should produce a 'wrong' with `a b`=1 and a=2. Actually produces a 'wrong' w/ `a b`=1 and a=1
val r = right(2, 1) // Produces a 'right' with `a b`=1 and a=2
// You would think the above would produce objects whose respective fields were equal ...
if (r.a == w.a) {
println ("Test passes")
} else {
println ("Test fails")
}
}
}
```
Freaky.
```scala
scala> case class wrong(`a b`: Int, a: Int)
defined class wrong
scala> wrong(1, 2)
res6: wrong = wrong(1,1)
scala> .`a b`
res7: Int = 1
scala> res6.a
res8: Int = 1
scala> .`a beans
```
Plus, code completion tab after the b yields what you see here.
But there's an issue for backticks in REPL.
```
Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> case class right3a(a: Int, `a b`: Int, b: Int)
defined class right3a
scala> right3a(1,2,3)
res0: right3a = right3a(1,2,3)
scala> case class right3b(b: Int, `a b`: Int, a: Int)
defined class right3b
scala> right3b(1,2,3)
res1: right3b = right3b(1,2,2)
scala> case class right4(b: Int, `a b`: Int, a: Int, `a `: Int)
defined class right4
scala> right4(1,2,3,4)
res2: right4 = right4(1,2,2,4)
scala> case class right5(b: Int, `a b`: Int, a: Int, `a `: Int, `a b c`: Int)
defined class right5
scala> right5(1,2,3,4,5)
res3: right5 = right5(1,2,5,2,4) // lolwut
scala>
```
I looked into the issue a bit, and I think I found the main cause and a potential fix (though I am uncertain about the fix).
The source of the issue seems to be: https://github.com/scala/scala/blob/2.11.x/src/compiler/scala/tools/nsc/transform/Constructors.scala#L501, where the wrong parameter can be matched when the names involved include dollar signs (even when the names used in the source program do not include dollar signs). The current behaviour matches names that are exactly the same (which is correct) as well as names that start with the same substring, followed by a dollar sign, followed by anything. That behaviour is somewhat weird, but would explain the different test cases, since the space in `a b` is represented using an initial dollar sign followed by some representation of space.
I looked into it, and it seems the current behaviour was changed in this commit: https://github.com/scala/scala/commit/6b6d21444f2d68988423424ee4a9ebda544985e9#diff-086eb87150c79730cf3cfe9cb8b12219L70, where the previous behaviour was to match names that are exactly the same as well as names that start with the same substring and with a dollar sign at the end. Reverting the behaviour to that in the commit solves most cases discussed here (as well as the case "case class plus(a_+ : Int, a_ : String)"): Only Arya Irani's case with "case class right5(b: Int, `a b`: Int, a: Int, `a `: Int, `a b c`: Int)" does not print correctly, and accessing its fields works correctly. Cases where dollar signs are used directly at the end of names, such as "case class dollarsign(a$: Int, a: String)" and "case class dollarsign2(`a$`: Int, a: String)", still fail.
I did not figure out what the purpose of the check is. The original behaviour seems to be to check against an "original name": https://github.com/scala/scala/commit/cb7711db82c381848a6571047c68145e4f2d3c46#diff-086eb87150c79730cf3cfe9cb8b12219L58. In either case, I think a refactoring of the handling of Names from working on the string values to encapsulating the string value and instead provide more descriptive methods would be useful in making it much easier to verify and maintain correctness in relation to the handling of names, though I can imagine that would be quite a lot of work. In line with this, a better fix than presented below would implement a descriptive method (describing what the matching means) on Name (or similar) that handles the matching and call that instead of directly matching on parts of the string value of the name.
The potential fix (tested using "ant test-opt"):
```scala
def matchesName(param: Symbol) =
param.name == name ||
(param.name.startsWith(name) && param.name.endsWith(nme.NAME_JOIN_STRING))
```
Your analysis is spot on, Jens. I'd actually started a patch for this last week: https://github.com/scala/scala/compare/2.11.x...retronym:ticket/8831?expand=1
In the commit comment, I describe the rationale for `startsWith`; the case accessor method for a non-public case class parameter `a` is mangled to a name like `a$1`. This itself is problematic, as it is leads to fragile binary compatibility. The 2.12.x branch uses a more structured name for these mangled `a$accessor$1`.
I'll make sure we fix this before 2.11.7. Until then, the workaround is to avoid using case class param names that start with `someOtherParamName$`.
Another manifestation of this bug, reported on the mailing list:
```
we noticed some strange behaviour of productIterator in Scala 2.11.5:
case class Data(a: String, b: String, `a-some`: String)
val m = Data("1", "2", "3")
assert(m.productIterator.mkString(", ") == "1, 2, 3")
Result: "1, [3, 2]" did not equal "1, [2, 3]"
"a-some" can be any mangled symbol with an "a" prefix.
Is the order of productIterator on case classes guaranteed to be in parameter order? If so, this seems to be a bug. Can anyone reproduce it?
```
|
Python
|
UTF-8
| 549
| 2.84375
| 3
|
[] |
no_license
|
import json
class DB:
def query_db(self, file_name):
with open(file_name) as json_file:
try:
rows = json.load(json_file)
except ValueError:
rows = []
return rows
def update_db(self, file_name, rows):
with open(file_name, 'w') as json_file:
json.dump(rows, json_file, indent=4)
def clear_db(self, file_name):
with open(file_name, 'w') as json_file:
json_list = []
json.dump(json_list, json_file, indent=4)
|
Java
|
UTF-8
| 1,927
| 1.984375
| 2
|
[] |
no_license
|
package com.linkwee.web.model;
import java.io.Serializable;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*
* @描述: 实体Bean
*
* @创建人: liqimoon
*
* @创建时间:2016年11月10日 10:29:41
*
* Copyright (c) 深圳领会科技有限公司-版权所有
*/
public class SysGrayRelease implements Serializable {
private static final long serialVersionUID = 6960085708324999265L;
/**
*
*/
private Integer id;
/**
*产品id/活动编码
*/
private String pid;
/**
*0:公共 1:产品 2:机构
*/
private Integer type;
/**
*0:启用 1:停用
*/
private Integer status;
/**
*手机号码
*/
private String mobile;
/**
*用户id
*/
private String userId;
/**
*用户名
*/
private String userName;
public void setId(Integer id){
this.id = id;
}
public Integer getId(){
return id;
}
public void setPid(String pid){
this.pid = pid;
}
public String getPid(){
return pid;
}
public void setType(Integer type){
this.type = type;
}
public Integer getType(){
return type;
}
public void setStatus(Integer status){
this.status = status;
}
public Integer getStatus(){
return status;
}
public void setMobile(String mobile){
this.mobile = mobile;
}
public String getMobile(){
return mobile;
}
public void setUserId(String userId){
this.userId = userId;
}
public String getUserId(){
return userId;
}
public void setUserName(String userName){
this.userName = userName;
}
public String getUserName(){
return userName;
}
@Override
public String toString() {
return JSON.toJSONString(this, SerializerFeature.UseISO8601DateFormat);
}
}
|
Python
|
UTF-8
| 1,972
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
"""
Component
"""
import json
from websocket import create_connection
from core.observer import Observable
class BaseComponent(object):
"""
Class for components
"""
config = dict()
def __init__(self):
with open('./config.json') as file:
BaseComponent.config = json.loads(file.read())
self.output_notifier = BaseComponent.OutputNotifier(self)
self.component_id = None
@staticmethod
def get_parameters():
"""
copy this to every component with parameters and
change Component to the inherit class name
return all parameters of the component
"""
for key, value in BaseComponent.__dict__.items():
if isinstance(value, property):
print(key)
@staticmethod
def ws_send(package):
"""
send data to websocket
"""
try:
websocket = create_connection('ws://localhost:%s' % \
BaseComponent.config['web_socket_port'])
websocket.send(package)
websocket.close()
except ConnectionRefusedError:
pass
def send(self, data):
"""
bundle data package for sending to websocket
"""
package = dict()
package['component'] = self.__class__.__name__
if self.component_id is None:
package['id'] = 'undefined'
else:
package['id'] = self.component_id
package['data'] = data
BaseComponent.ws_send(str(package))
class OutputNotifier(Observable):
"""
Class for Notifier
"""
def __init__(self, outer):
Observable.__init__(self)
self.outer = outer
def notify_observers(self, arg=None):
"""
notify observers
"""
self.outer.send({'status': 'stopped'})
self.set_changed()
Observable.notify_observers(self, arg)
|
Java
|
UTF-8
| 377
| 3.90625
| 4
|
[] |
no_license
|
package com.bvan.javastart.lesson4.loop;
/**
* @author bvanchuhov
*/
public class SalaryWhile {
public static void main(String[] args) {
long salary = 600; // (1)
while (salary < 10000) { // (2)
System.out.println("Work. My salary is " + salary);
salary += 1000; // (3)
}
System.out.println("Stop!!!");
}
}
|
Markdown
|
UTF-8
| 1,196
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
# Tooltip
A Tooltip component is UI component that provides the user with additional context when engaged.
## Example
```jsx
<Tooltip title="You're my boy!!!">Blue</Tooltip>
```
## Props
| Prop | Type | Description |
| ------------- | ----------------- | ------------------------------------------------------------------- |
| className | `string` | Custom class names to be added to the component. |
| maxWidth | `number`/`string` | Max width for the component. |
| minWidth | `number`/`string` | Min width for the component. |
| renderContent | `Function` | Renders a component within the Tooltip. Is prioritized over `title` |
| title | `string` | Text to display within the Tooltip. |
| triggerOn | `string` | Determines how to engage the component. |
This component is powered by [Pop](../../Pop/docs/Pop.md). After additional props, check out [Pop's documentation](../../Pop/docs/Pop.md).
|
Java
|
UTF-8
| 2,447
| 2.5
| 2
|
[] |
no_license
|
package com.newline.simple;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import com.hht.simple.R;
import com.newline.simple.model.SerialPortModel;
import com.newline.simple.model.SerialPortModel;
import android_serialport_api.SerialPort;
public class MainActivity extends Activity {
SerialPortUtils serialPortUtils = new SerialPortUtils();
private byte[] mBuffer;
private Handler handler = new Handler();
private TextView hello;
SerialPort serialPort;
private String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello = findViewById(R.id.hello);
serialPort = serialPortUtils.openSerialPort();
//串口数据监听事件
serialPortUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {
@Override
public void onDataReceive(byte[] buffer, int size) {
s = SerialPortUtils.bytesToHexString(buffer);
Log.d("MainActivity", "进入数据监听事件中。。。" + s);
//
//在线程中直接操作UI会报异常:ViewRootImpl$CalledFromWrongThreadException
//解决方法:handler
//
mBuffer = buffer;
String partOffCodes = SerialPortUtils.bytesToHexString(mBuffer).toUpperCase();
SerialPortModel serialPortModel = SerialPortModel.getSerialPortModelByControllingCode(partOffCodes, size);
Log.i("Main"," serialPortModel = "+serialPortModel);
if (serialPortModel != null) {
serialPortModel.action(MainActivity.this);
String code = serialPortModel.getReturnCode();
serialPortUtils.sendSerialPort(code);
}
handler.post(runnable);
}
//开线程更新UI
Runnable runnable = new Runnable() {
@Override
public void run() {
hello.setText("size:"+ String.valueOf(mBuffer.length)+"数据监听:"+ s);
}
};
});
}
@Override
protected void onDestroy() {
super.onDestroy();
serialPortUtils.closeSerialPort();
}
}
|
Java
|
UTF-8
| 16,870
| 2.09375
| 2
|
[
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"CC-BY-2.5"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package groovy.json;
import groovy.transform.NamedParam;
import org.apache.groovy.json.internal.JsonFastParser;
import org.apache.groovy.json.internal.JsonParserCharArray;
import org.apache.groovy.json.internal.JsonParserLax;
import org.apache.groovy.json.internal.JsonParserUsingCharacterSource;
import org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport;
import org.codehaus.groovy.runtime.ResourceGroovyMethods;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
/**
* This has the same interface as the original JsonSlurper written for version 1.8.0, but its
* implementation has completely changed. It is now up to 20x faster than before, and its speed
* competes and often substantially exceeds popular common JSON parsers circa Jan, 2014.
* <p />
* JSON slurper parses text or reader content into a data structure of lists and maps.
* <p>
* Example usage:
* <code><pre class="groovyTestCase">
* def slurper = new groovy.json.JsonSlurper()
* def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
*
* assert result.person.name == "Guillaume"
* assert result.person.age == 33
* assert result.person.pets.size() == 2
* assert result.person.pets[0] == "dog"
* assert result.person.pets[1] == "cat"
* </pre></code>
*
* JsonSlurper can use several types of JSON parsers. Please read the documentation for
* JsonParserType. There are relaxed mode parsers, large file parser, and index overlay parsers.
* Don't worry, it is all groovy. JsonSlurper will just work, but understanding the different parser
* types may allow you to drastically improve the performance of your JSON parsing.
* <p />
*
* Index overlay parsers (INDEX_OVERLAY and LAX) are the fastest JSON parsers.
* However they are not the default for a good reason.
* Index overlay parsers has pointers (indexes really) to original char buffer.
* Care must be used if putting parsed maps into a long term cache as members of map
* maybe index overlay objects pointing to original buffer.
* You can mitigate these risks by using chop and lazy chop properties.
* <p />
* Chop eagerly dices up the buffer so each Value element points to a small copy of the original buffer.
* <p />
* Lazy Chop dices up the buffer when a list get or map get is called so if an GPath expression or
* such is applied.
* <p />
* You do not need chop or lazy chop if you are NOT putting the map into a long term cache.
* You do not need chop or lazy chop if you are doing object de-serialization.
* Recommendation is to use INDEX_OVERLAY for JSON buffers under 2MB.
* The maxSizeForInMemory is set to 2MB and any file over 2MB will use a parser designed for
* large files, which is slower than the INDEX_OVERLAY, LAX, and CHAR_BUFFER parsers, but
* faster than most commonly used JSON parsers on the JVM for most use cases circa January 2014.
* <p />
* To enable the INDEX_OVERLAY parser do this:
*
* <code><pre>
* parser = new JsonSlurper().setType(JsonParserType.INDEX_OVERLAY);
* </pre></code>
*
* @see groovy.json.JsonParserType
* @since 1.8.0
*/
public class JsonSlurper {
private int maxSizeForInMemory = 2000000;
private boolean chop = false;
private boolean lazyChop = true;
private boolean checkDates = true;
private JsonParserType type = JsonParserType.CHAR_BUFFER;
/**
* Max size before Slurper starts to use windowing buffer parser.
* @return size of file/buffer
* @since 2.3
*/
public int getMaxSizeForInMemory() {
return maxSizeForInMemory;
}
/**
* Max size before Slurper starts to use windowing buffer parser.
* @since 2.3
* @return JsonSlurper
*/
public JsonSlurper setMaxSizeForInMemory(int maxSizeForInMemory) {
this.maxSizeForInMemory = maxSizeForInMemory;
return this;
}
/** Parser type.
* @since 2.3
* @see groovy.json.JsonParserType
* @return type
*/
public JsonParserType getType() {
return type;
}
/** Parser type.
* @since 2.3
* @see groovy.json.JsonParserType
* @return JsonSlurper
*/
public JsonSlurper setType(JsonParserType type) {
this.type = type;
return this;
}
/** Turns on buffer chopping for index overlay.
* @since 2.3
* @see groovy.json.JsonParserType
* @return chop on or off
*/
public boolean isChop() {
return chop;
}
/** Turns on buffer chopping for index overlay.
* @since 2.3
* @see groovy.json.JsonParserType
* @return JsonSlurper
*/
public JsonSlurper setChop(boolean chop) {
this.chop = chop;
return this;
}
/** Turns on buffer lazy chopping for index overlay.
* @see groovy.json.JsonParserType
* @return on or off
* @since 2.3
*/
public boolean isLazyChop() {
return lazyChop;
}
/** Turns on buffer lazy chopping for index overlay.
* @see groovy.json.JsonParserType
* @return JsonSlurper
* @since 2.3
*/
public JsonSlurper setLazyChop(boolean lazyChop) {
this.lazyChop = lazyChop;
return this;
}
/**
* Determine if slurper will automatically parse strings it recognizes as dates. Index overlay only.
* @return on or off
* @since 2.3
*/
public boolean isCheckDates() {
return checkDates;
}
/**
* Determine if slurper will automatically parse strings it recognizes as dates. Index overlay only.
* @return on or off
* @since 2.3
*/
public JsonSlurper setCheckDates(boolean checkDates) {
this.checkDates = checkDates;
return this;
}
/**
* Parse a text representation of a JSON data structure
*
* @param text JSON text to parse
* @return a data structure of lists and maps
*/
public Object parseText(String text) {
if (text == null || text.isEmpty()) {
throw new IllegalArgumentException("Text must not be null or empty");
}
return createParser().parse(text);
}
/**
* Parse a JSON data structure from content from a reader
*
* @param reader reader over a JSON content
* @return a data structure of lists and maps
*/
public Object parse(Reader reader) {
if (reader == null) {
throw new IllegalArgumentException("Reader must not be null");
}
Object content;
JsonParser parser = createParser();
content = parser.parse(reader);
return content;
}
/**
* Parse a JSON data structure from content from an inputStream
*
* @param inputStream stream over a JSON content
* @return a data structure of lists and maps
* @since 2.3
*/
public Object parse(InputStream inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("inputStream must not be null");
}
Object content;
JsonParser parser = createParser();
content = parser.parse(inputStream);
return content;
}
/**
* Parse a JSON data structure from content from an inputStream
*
* @param inputStream stream over a JSON content
* @param charset charset
* @return a data structure of lists and maps
* @since 2.3
*/
public Object parse(InputStream inputStream, String charset) {
if (inputStream == null) {
throw new IllegalArgumentException("inputStream must not be null");
}
if (charset == null) {
throw new IllegalArgumentException("charset must not be null");
}
Object content;
content = createParser().parse(inputStream, charset);
return content;
}
/**
* Parse a JSON data structure from content from a byte array.
*
* @param bytes buffer of JSON content
* @param charset charset
* @return a data structure of lists and maps
* @since 2.3
*/
public Object parse(byte [] bytes, String charset) {
if (bytes == null) {
throw new IllegalArgumentException("bytes must not be null");
}
if (charset == null) {
throw new IllegalArgumentException("charset must not be null");
}
Object content;
content = createParser().parse(bytes, charset);
return content;
}
/**
* Parse a JSON data structure from content from a byte array.
*
* @param bytes buffer of JSON content
* @return a data structure of lists and maps
* @since 2.3
*/
public Object parse(byte [] bytes) {
if (bytes == null) {
throw new IllegalArgumentException("bytes must not be null");
}
Object content;
content = createParser().parse(bytes);
return content;
}
/**
* Parse a JSON data structure from content from a char array.
*
* @param chars buffer of JSON content
* @return a data structure of lists and maps
* @since 2.3
*/
public Object parse(char [] chars) {
if (chars == null) {
throw new IllegalArgumentException("chars must not be null");
}
Object content;
content = createParser().parse(chars);
return content;
}
private JsonParser createParser() {
switch (type) {
case LAX:
return new JsonParserLax(false, chop, lazyChop, checkDates);
case CHAR_BUFFER:
return new JsonParserCharArray();
case CHARACTER_SOURCE:
return new JsonParserUsingCharacterSource();
case INDEX_OVERLAY:
return new JsonFastParser(false, chop, lazyChop, checkDates);
default:
return new JsonParserCharArray();
}
}
/**
* Parse a JSON data structure from content within a given Path.
*
* @param path {@link Path} containing JSON content
* @return a data structure of lists and maps
*/
public Object parse(Path path) throws IOException {
return parse(Files.newInputStream(path));
}
/**
* Parse a JSON data structure from content within a given Path.
*
* @param path {@link Path} containing JSON content
* @param charset the charset for this File
* @return a data structure of lists and maps
*/
public Object parse(Path path, String charset) throws IOException {
return parse(Files.newInputStream(path), charset);
}
/**
* Parse a JSON data structure from content within a given File.
*
* @param file File containing JSON content
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(File file) {
return parseFile(file, null);
}
/**
* Parse a JSON data structure from content within a given File.
*
* @param file File containing JSON content
* @param charset the charset for this File
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(File file, String charset) {
return parseFile(file, charset);
}
private Object parseFile(File file, String charset) {
if (file.length() < maxSizeForInMemory) {
return createParser().parse(file, charset);
} else {
return new JsonParserUsingCharacterSource().parse(file, charset);
}
}
/**
* Parse a JSON data structure from content at a given URL.
*
* @param url URL containing JSON content
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(URL url) {
return parseURL(url, null);
}
/**
* Parse a JSON data structure from content at a given URL.
*
* @param url URL containing JSON content
* @param params connection parameters
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(URL url, Map params) {
return parseURL(url, params);
}
/**
* Parse a JSON data structure from content at a given URL. Convenience variant when using Groovy named parameters for the connection params.
*
* @param params connection parameters
* @param url URL containing JSON content
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(
@NamedParam(value = "connectTimeout", type = Integer.class)
@NamedParam(value = "readTimeout", type = Integer.class)
@NamedParam(value = "useCaches", type = Boolean.class)
@NamedParam(value = "allowUserInteraction", type = Boolean.class)
@NamedParam(value = "requestProperties", type = Map.class)
Map<String, ?> params,
URL url
) {
return parseURL(url, params);
}
private Object parseURL(
URL url,
@NamedParam(value = "connectTimeout", type = Integer.class)
@NamedParam(value = "readTimeout", type = Integer.class)
@NamedParam(value = "useCaches", type = Boolean.class)
@NamedParam(value = "allowUserInteraction", type = Boolean.class)
@NamedParam(value = "requestProperties", type = Map.class)
Map<String, ?> params
) {
Reader reader = null;
try {
if (params == null || params.isEmpty()) {
reader = ResourceGroovyMethods.newReader(url);
} else {
reader = ResourceGroovyMethods.newReader(url, params);
}
return createParser().parse(reader);
} catch (IOException ioe) {
throw new JsonException("Unable to process url: " + url.toString(), ioe);
} finally {
if (reader != null) {
DefaultGroovyMethodsSupport.closeWithWarning(reader);
}
}
}
/**
* Parse a JSON data structure from content at a given URL.
*
* @param url URL containing JSON content
* @param charset the charset for this File
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(URL url, String charset) {
return parseURL(url, null, charset);
}
/**
* Parse a JSON data structure from content at a given URL.
*
* @param url URL containing JSON content
* @param params connection parameters
* @param charset the charset for this File
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(URL url, Map params, String charset) {
return parseURL(url, params, charset);
}
/**
* Parse a JSON data structure from content at a given URL. Convenience variant when using Groovy named parameters for the connection params.
*
* @param params connection parameters
* @param url URL containing JSON content
* @param charset the charset for this File
* @return a data structure of lists and maps
* @since 2.2.0
*/
public Object parse(Map params, URL url, String charset) {
return parseURL(url, params, charset);
}
private Object parseURL(URL url, Map params, String charset) {
Reader reader = null;
try {
if (params == null || params.isEmpty()) {
reader = ResourceGroovyMethods.newReader(url, charset);
} else {
reader = ResourceGroovyMethods.newReader(url, params, charset);
}
return parse(reader);
} catch (IOException ioe) {
throw new JsonException("Unable to process url: " + url.toString(), ioe);
} finally {
if (reader != null) {
DefaultGroovyMethodsSupport.closeWithWarning(reader);
}
}
}
}
|
Java
|
UTF-8
| 670
| 2.046875
| 2
|
[] |
no_license
|
package com.pengfei.intern.dao.impl;
import com.pengfei.intern.dao.JobDao;
import com.pengfei.intern.domain.Intern;
import com.pengfei.intern.domain.Job;
import com.pengfei.intern.domain.Task;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by zhaopen on 5/16/2017.
*/
@Repository
public class JobDaoImpl extends BaseDaoImpl<Job> implements JobDao{
@Override
public List<Job> getAllByIntern(Intern itr) {
return find("select j from Job as j where j.intern=?0",itr);
}
@Override
public List<Job> getAllByTask(Task task) {
return find("select j from Job as j where j.task=?0",task);
}
}
|
JavaScript
|
UTF-8
| 1,454
| 2.984375
| 3
|
[] |
no_license
|
export default function showAddItemForm() {
let style = document.getElementById("addItemForm").style.display;
"block" == style ? (style = "none") : (style = "block");
document.getElementById("addItemForm").style.display = style;
}
const input = document.getElementById("item");
const addItemForm = document.getElementById("addItemForm");
const itemCancel = document.getElementById("itemCancel");
const itemSubmit = document.getElementById("itemSubmit");
addItemForm.addEventListener("submit", submitInfo);
function submitInfo(e) {
e.preventDefault();
createElement(input.value);
input.value = "";
}
itemCancel.addEventListener(
"click",
() => (addItemForm.style.display = "none")
);
const createElement = (text) => {
const listItem = document.createElement("li");
listItem.textContent = text;
listItem.classList.add("listItem");
document.getElementById("list").appendChild(listItem);
addButtons(listItem);
};
function addButtons(item) {
const itemDone = document.createElement("i");
itemDone.classList.add("fas", "fa-check", "itemIcon");
itemDone.addEventListener(
"click",
() => (itemDone.parentElement.style.textDecoration = "line-through")
);
const removeItem = document.createElement("i");
removeItem.classList.add("far", "fa-trash-alt", "itemIcon");
removeItem.addEventListener("click", () => removeItem.parentElement.remove());
item.appendChild(itemDone);
item.appendChild(removeItem);
}
|
Python
|
UTF-8
| 1,055
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
__author__ = 'isee15'
import LunarSolarConverter
converter = LunarSolarConverter.LunarSolarConverter()
def LunarToSolar(year, month, day, isleap = False):
lunar = LunarSolarConverter.Lunar(year, month, day, isleap)
solar = converter.LunarToSolar(lunar)
return (solar.solarYear, solar.solarMonth, solar.solarDay)
def SolarToLunar(year, month, day):
solar = LunarSolarConverter.Solar(year, month, day)
lunar = converter.SolarToLunar(solar)
return (lunar.lunarYear, lunar.lunarMonth, lunar.lunarDay)
def LunarMonthDays(year, month, isleap = False):
converter = LunarSolarConverter.LunarSolarConverter
days = converter.lunar_month_days[year - converter.lunar_month_days[0]]
leap = LunarSolarConverter.GetBitInt(days, 4, 13)
offset = 0
loopend = leap
if not isleap:
if month <= leap or leap == 0:
loopend = month - 1
else:
loopend = month
days = LunarSolarConverter.GetBitInt(days, 1, 12 - loopend) == 1 and 30 or 29
return days
|
Java
|
UTF-8
| 22,960
| 3.28125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package alix.util;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
/**
* A mutable string implementation thought for efficiency more than security.
* The hash function is same as String so that a Term can be found in a Set<String>.
* The same internal char array could be shared by multiple Term instances (with different offset and len),
* allowing to scan
*
* @author glorieux-f
*/
public class Term implements CharSequence, Comparable<Term>
{
/** The characters */
private char[] data = new char[16];
/** Start index of the String in the array, allow fast trim(), or allow different terms to share the same text line (ex: char separated values) */
private int start = 0;
/** Number of characters used */
private int len;
/** Cache the hash code for the string */
private int hash; // Default to 0
/** Internal pointer inside the scope of the string, used by csv scanner (value()) */
private int pointer = -1;
/**
* Empty constructor, value will be set later
*/
public Term( )
{
}
/**
* Construct a term by copy of a term content (modification of this Term object will NOT affect source Term)
*/
public Term( Term t )
{
replace(t);
}
/**
* Construct a term by copy of a char array (modification of this Term object will NOT affect the source array)
* @param a a char array
*/
public Term( final char[] a )
{
replace(a, -1, -1);
}
/**
* Construct a term by copy of a char sequence
* @param cs a char sequence (String, but also String buffers or builders)
*/
public Term( CharSequence cs )
{
replace( cs, -1, -1 );
}
/**
* Construct a term by copy of a section of char sequence (String, but also String buffers or builders)
* @param cs a char sequence (String, but also String buffers or builders)
* @param offset start index from source string
* @param count number of chars from offset
*/
public Term( CharSequence cs, int offset, int count )
{
replace( cs, offset, count );
}
@Override
public int length()
{
return len;
}
/**
* Link by reference to a section of a term (modification of one of the Term WILL affect the 2 Term)
* @param term the source term
* @param offset start index from source term
* @param count number of chars from offset
* @return the Term object for chaining
*/
public Term link( final Term term, final int offset, final int count )
{
data = term.data;
start = term.start + offset;
len = count;
return this;
}
/**
* Link a term by reference to a section of a char array (modification of the Term object or the char array WILL affect the other)
* @param a a char array
* @param offset start index from source term
* @param count number of chars from offset
*/
public Term link( final char[] a, final int offset, final int count )
{
data = a;
start = offset;
len = count;
return this;
}
/**
* Is Term with no chars ?
* @return true if len == 0, or false
*/
public boolean isEmpty()
{
return (len == 0);
}
@Override
public char charAt( int index )
{
/* no test and no exception
if ((index < 0) || (index >= len)) {
throw new StringIndexOutOfBoundsException(index);
}
*/
return data[start+index];
}
/**
* Reset term (no modification to internal data)
* @return the Term
*/
public Term reset()
{
len = 0;
hash = 0;
return this;
}
/**
* Replace Term content by copy af a String
* @param cs a char sequence
* @return the Term object for chaining
*/
public Term replace( CharSequence cs )
{
return replace( cs, -1, -1);
}
/**
* Replace Term content by a span of String
* @param cs a char sequence
* @param index of the string from where to copy chars
* @param number of chars to copy -1
* @return the Term object for chaining, or null if the String provided is null (for testing)
*/
public Term replace( CharSequence cs, int offset, int count )
{
if ( cs == null ) return null;
if (offset <= 0 && count < 0) {
offset = 0;
count = cs.length();
}
if ( count <= 0) {
len = 0;
return this;
}
sizing( count );
for (int i=start; i<count; i++) {
data[i] = cs.charAt( offset++ );
}
len = count;
/*
// longer
value = s.toCharArray();
len = value.length;
*/
return this;
}
/**
* Replace Term content by copy of a char array, 2 time faster than String
* @param a text as char array
* @return the Term object for chaining
*/
public Term replace( char[] a )
{
return replace( a, -1, -1);
}
/**
* Replace Term content by a span of a char array
* @param a text as char array
* @param index of the string from where to copy chars
* @param number of chars to copy -1
* @return the Term object for chaining
*/
public Term replace( char[] a, int offset, int count )
{
if (offset <= 0 && count < 0) {
offset = 0;
count = a.length;
}
if ( count <= 0) {
len = 0;
return this;
}
len = count;
sizing( count );
System.arraycopy( a, offset, data, start, count );
return this;
}
/**
* Replace this term content by the copy of a term.
* Reset the start position.
* @param term
* @return
*/
public Term replace( Term term )
{
int newlen = term.len;
// do not change len before sizing
sizing( newlen );
start = 0;
System.arraycopy( term.data, term.start, data, start, newlen );
len = newlen;
return this;
}
/**
* Append a character
* @param c
* @return the Term object for chaining
*/
public Term append( char c )
{
int newlen = len + 1;
sizing( newlen );
data[len] = c;
len = newlen;
return this;
}
/**
* Append a term
* @param term
* @return the Term object for chaining
*/
public Term append( Term term )
{
int newlen = len + term.len;
sizing( newlen );
System.arraycopy( term.data, term.start, data, start+len, term.len);
len = newlen;
return this;
}
/**
* Append a string
* @param cs String or other CharSequence
* @return the Term object for chaining
*/
public Term append( CharSequence cs )
{
int count = cs.length();
int newlen = len + count;
sizing( newlen );
int offset = start+len;
for (int i=0; i<count; i++) {
data[offset++] = cs.charAt( i );
}
len = newlen;
return this;
}
/**
* Test if char array container is big enough to contain a new size
* If resized, chars outside the scope are kept, maybe they are needed by
* other users of the char array
* @param newlen The new size to put in
* @return true if resized
*/
private boolean sizing( final int newlen )
{
hash = 0; // resizing occurs when content change, uncache hashcode
if ( (start+newlen) <= data.length ) return false;
char[] a = new char[ Calcul.nextSquare( start+newlen ) ];
try {
System.arraycopy( data, 0, a, 0, data.length );
} catch (Exception e) {
System.out.println( new String( data )+" "+len );
throw(e);
}
data = a;
return true;
}
/**
* Last char, will send an array out of bound, with no test
* @return last char
*/
public char last()
{
return data[len-1];
}
/**
* Set last char, will send an array out of bound, with no test
*/
public Term last( char c )
{
data[len-1] = c;
hash = 0;
return this;
}
/**
* Remove last char
*/
public Term lastDel()
{
len--;
hash = 0;
return this;
}
/**
* First char
*/
public char first()
{
return data[start];
}
/**
* Delete first char (just by modification of pointers)
* @return the Term for chaining
*/
public Term firstDel()
{
hash = 0;
start++;
len--;
return this;
}
/**
* Put first char upperCase
* @return the Term for chaining
*/
public Term firstToUpper()
{
hash = 0;
data[start] = Character.toUpperCase( data[start] );
return this;
}
/**
* Is first letter Upper case ?
* @return true for Titlecase, UPPERCASE; false for lowercase
*/
public boolean isFirstUpper()
{
return Char.isUpperCase( data[start] );
}
/**
* Change case of the chars in scope of the term.
* @return the Term object for chaining
*/
public Term toLower()
{
char c;
for ( int i=start; i < len; i++ ) {
c = data[i];
if ( Char.isLowerCase( c ) ) continue;
// a predefine hash of chars is not faster
// if ( LOWER.containsKey( c )) s.setCharAt( i, LOWER.get( c ) );
data[i] = Character.toLowerCase( c );
}
hash = 0;
return this;
}
/**
* Suppress spaces at start and end of string.
* Do not affect the internal char array data but modify only its limits.
* Should be very efficient.
* @return the modified Term object
*/
public Term trim()
{
int from = start;
char[] dat = data;
int to = start + len;
while ( from < to && dat[from] < ' ' ) from++;
to --;
while ( to > from && dat[to] < ' ' ) to--;
start = from;
len = to -from + 1;
return this;
}
/**
* Suppress specific chars at start and end of String.
* Do not affect the internal char array data but modify only its limits.
* @param chars
* @return the modified Term object
*/
public Term trim( String chars)
{
int from = start;
char[] dat = data;
int to = start + len;
// possible optimisation on indexOf() ?
while ( from < to && chars.indexOf( dat[from] ) > -1 ) from++;
to --;
// test for escape chars ? "\""
while ( to > from && chars.indexOf( dat[to] ) > -1 ) to--;
start = from;
len = to -from + 1;
return this;
}
/**
* Test prefix
* @param prefix
* @return true if the Term starts by prefix
*/
public boolean startsWith( final CharSequence prefix)
{
int lim = prefix.length();
if ( lim > len) return false;
for ( int i=0; i < lim; i++ ) {
if ( prefix.charAt( i ) != data[start+i]) return false;
}
return true;
}
/**
* Test suffix
* @param suffix
* @return true if the Term ends by suffix
*/
public boolean endsWith( final CharSequence suffix)
{
int lim = suffix.length();
if ( lim > len) return false;
for ( int i=0; i < lim; i++ ) {
if ( suffix.charAt( lim-1-i ) != data[start+len-1-i]) return false;
}
return true;
}
public int value( Term cell, final char separator )
{
if ( pointer < 0 ) pointer = 0;
pointer = value( cell, separator, pointer );
return pointer;
}
/**
* Read value in a char separated string. The term objected is update from offset position to the next separator (or end of String).
* @param separator
* @param offset index position to read from
* @return a new offset from where to search in String, or -1 when end of line is reached
*/
public int value( Term cell, final char separator, final int offset )
{
if ( offset >= len ) return -1;
char[] dat = data;
int to = start + offset;
int max = start + len;
while ( to < max) {
if ( dat[to] == separator && (to == 0 || dat[to-1] != '\\') ) { // test escape char
cell.link( this, offset, to-offset-start );
return to-start+1;
}
to++;
}
// end of line
cell.link( this, offset, to-offset-start );
return to-start;
}
/**
* An split on one char
* @param separator
* @return
*/
public String[] split( char separator )
{
// store generated Strings in alist
ArrayList<String> list = new ArrayList<>();
int offset = start;
int to = start;
int max = start + len;
char[] dat = data;
while ( to <= max ) {
// not separator, continue
if ( dat[to] != separator ) {
to++;
continue;
}
// separator, add a String
list.add( new String( dat, offset, to-offset) );
offset = ++to;
}
list.add( new String( dat, offset, to-offset) );
return list.toArray( new String[0] );
}
/**
* Modify a char in the String
* @param index position of the char to change
* @param c new char value
* @return the Term object for chaining
*/
public Term setCharAt( int index, char c )
{
if ( (index < 0) || (index >= len) ) {
throw new StringIndexOutOfBoundsException(index);
}
data[start+index] = c;
return this;
}
@Override
public CharSequence subSequence( int start, int end )
{
System.out.println( "Term.subSequence() TODO Auto-generated method stub" );
return null;
}
/**
*
* @return
*/
private static boolean globsearch( CharSequence glob, int globstart, int globend,
CharSequence text, int textstart, int textend ) {
// empty pattern will never found things
if ( glob.length() < 1 ) return false;
// empty text will never match
if ( text.length() < 1 ) return false;
/*
for ( int i=globstart; i <= globend; i++ ) System.out.print( globdata[i] );
System.out.print( ' ' );
for ( int i=textstart; i <= textend; i++ ) System.out.print( textdata[i] );
System.out.println();
*/
char globc;
char textc;
// test if finish
// prefix search
final int inc;
// pat*, prefix search, go forward from start
if ( ( globc = glob.charAt( globstart ) ) != '*' ) {
textc = text.charAt( textstart );
inc = 1;
}
// *pat, suffix search, go backward from end
else if ( ( globc = glob.charAt( globend ) ) != '*' ) {
textc = text.charAt( textend );
inc = -1;
}
// *, just one star, we are OK
else if ( globend == globstart ) {
return true;
}
// *pat*, more than one star, progress by start
else {
int globi = globstart+1;
for (;;) {
globc = glob.charAt( globi );
if ( globc == '*' )
return globsearch( glob, globi, globend, text, textstart, textend );
// '?' not handled
// find the first
while ( text.charAt( textstart ) != globc ) {
if ( textstart == textend ) return false;
textstart++;
}
//
for (;;) {
globi++;
textstart++;
if ( textstart >= textend && globi+1 == globend ) return true;
if ( textstart >= textend || globi+1 == globend
|| text.charAt( textstart ) != glob.charAt( globi ) )
// not found, forward inside text, restart from the joker
return globsearch( glob, globi, globend, text, textstart, textend );
}
}
}
// not enough chars in text to find glob
if ( (globend - globstart) > ( textend - textstart ) + 1 ) return false;
// *pat or pat*
for (;;) {
if ( globc == '*' )
return globsearch( glob, globstart, globend, text, textstart, textend );
else if ( globc == '?' );
// TODO, char class [éju…]
else if ( globc != textc ) return false;
if ( globstart == globend && textstart == textend ) return true;
// ??? unuseful ?
// if ( globstart >= globend || textstart >= textend ) return false;
if ( inc > 0 ) {
globc = glob.charAt( ++globstart );
textc = text.charAt( ++textstart );
}
else {
globc = glob.charAt( --globend );
textc = text.charAt( --textend );
}
}
}
/**
* @param text
* @return
*/
public boolean glob( CharSequence text )
{
return globsearch( this, 0, len-1, text, 0, text.length()-1 );
}
@Override
public boolean equals ( Object o )
{
if (this == o) return true;
char[] test;
// limit field lookup
int offset = start;
int lim = len;
if (o instanceof Term) {
Term oTerm = (Term)o;
if ( oTerm.len != lim ) return false;
// hashcode already calculated, if different, not same strings
if (hash != 0 && oTerm.hash != 0 && hash != oTerm.hash) return false;
test = oTerm.data;
int offset2 = oTerm.start;
for ( int i=0 ; i < lim ; i++ ) {
if ( data[offset+i] != test[offset2+i] ) return false;
}
return true;
}
else if (o instanceof char[]) {
if ( ((char[])o).length != lim ) return false;
test = (char[])o;
for ( int i=0; i < lim; i++ ) {
if ( data[offset+i] != test[i] ) return false;
}
return true;
}
// String or other CharSequence, by acces char by char
// faster than copy of the compared char array, even for complete equals
else if ( o instanceof CharSequence ) {
if ( ((CharSequence)o).length() != len) return false;
for ( int i=0; i < lim; i++ ) {
if ( ((CharSequence)o).charAt( i ) != data[offset+i]) return false;
}
return true;
}
/*
else if (o instanceof String) {
if ( ((String)o).length() != len) return false;
test = ((String)o).toCharArray();
for ( int i=0; i < len; i++ ) {
if ( data[offset+i] != test[i] ) return false;
}
return true;
}
*/
else return false;
}
/**
* HashMaps maybe optimized by ordered lists in buckets
* Do not use as a nice orthographic ordering
*/
@Override
public int compareTo( Term t ) {
char v1[] = data;
char v2[] = t.data;
int k1 = start;
int k2 = t.start;
int lim1 = k1 + Math.min( len, t.len);
while ( k1 < lim1 ) {
char c1 = v1[k1];
char c2 = v2[k2];
if (c1 != c2) {
return c1 - c2;
}
k1++;
k2++;
}
return len - t.len;
}
public int compareTo( String string ) {
char chars[] = data;
int ichars = start;
int istring = 0;
int lim = Math.min( len, string.length() );
while ( istring < lim ) {
char c1 = chars[ichars];
char c2 = string.charAt( istring );
if (c1 != c2) {
return c1 - c2;
}
ichars++;
istring++;
}
return len - string.length();
}
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
int h = hash;
if (h == 0) {
int end = start+len;
for (int i = start; i < end; i++) {
h = 31*h + data[i];
}
hash = h;
}
// System.out.println( this+" "+hash );
return h;
}
public void print(PrintWriter out) {
int len = this.len;
for ( int i =start; i < len; i++ ) out.print( data[i] );
}
@Override
public String toString( )
{
return new String( data, start, len );
}
/**
* No reason to use in CLI, except for testing.
* @param args
*/
public static void main(String[] args)
{
Term glob = new Term( "*ent" );
Term test = new Term( "t" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
test = new Term( "présentement" );
glob = new Term( "*ent*ent" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
glob = new Term( "présentement" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
glob = new Term( "prés*ent" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
glob = new Term( "présentement*" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
glob = new Term( "present" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
glob = new Term( "présent" );
System.out.println( glob+" GLOB "+test+" : "+glob.glob( test ) );
System.exit( 1 );
Term term;
term = new Term("123456");
term.lastDel();
System.out.println( term.endsWith( "345" ) );
Term line = new Term(",,C,D,,EPO");
System.out.println( line+" test CSV" );
Term cell = new Term();
while ( line.value( cell, ',' ) > -1 ) {
System.out.print( cell );
System.out.print( '|' );
}
System.out.println( );
System.out.println( Arrays.toString( line.split( ',' ) ) );
System.out.println( "trim() \" \" \""+ new Term(" ").trim( " " )+"\"" );
System.out.println( "// Illustration of char data shared between two terms" );
line = new Term("01234567890123456789");
System.out.println( "line: \""+line+"\"" );
Term span = new Term( );
span.link( line, 3, 4 );
System.out.println( "span=new Term(line, 3, 4): \""+span+"\"" );
span.setCharAt( 0, '-' );
System.out.println( "span.setCharAt(0, '-') " );
System.out.println( "line: \""+line+"\"" );
System.out.println( "span: \""+span+"\"" );
System.out.println( "Test comparesTo()="+span.compareTo( new Term("-456") )+" equals()="+span.equals( "-456" ) );
System.out.println( span.append( "____" )+", "+line );
for ( char c=33; c < 100; c++) span.append( c );
System.out.println( "span: \""+span+"\"" );
System.out.println( "line: \""+line+"\"" );
System.out.print( "Testing equals()" );
long time = System.nanoTime();
// test equals perf with a long String
String text = "java - CharBuffer vs. char[] - Stack Overflow stackoverflow.com/questions/294382/charbuffer-vs-char Traduire cette page 16 nov. 2008 - No, there's really no reason to prefer a CharBuffer in this case. In general, though ..... P.S If you use a backport remember to remove it once you catch up to the version containing the real version of the backported code.";
term = new Term(text);
term.last( 'p' ); // modify the last char
for ( int i=0; i < 10000000; i++) {
term.equals( text );
}
System.out.print( term.equals( text ) );
System.out.println( " " + ((System.nanoTime() - time) / 1000000) + " ms");
/*
System.out.println( t.copy( "abcde", 2, 1 ) );
t.clear();
for ( char c=33; c < 100; c++) t.append( c );
System.out.println( t );
t.clear();
for ( int i=0; i < 100; i++) {
t.append( " "+i );
}
System.out.println( t );
*/
/*
HashSet<String> dic = new HashSet<String>();
String text="de en le la les un une des";
for (String token: text.split( " " )) {
dic.add( token );
}
System.out.println( dic );
System.out.println( "HashSet<String>.contains(String) "+dic.contains( "des" ) );
System.out.println( "HashSet<String>.contains(Term) "+dic.contains( new Term("des") ) );
*/
}
}
|
Rust
|
UTF-8
| 5,856
| 2.8125
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::borrow::Borrow;
use regex::Regex;
struct MorseDecoder {
morse_code: HashMap<String, String>,
}
fn main() {
let decoder = MorseDecoder::new();
print!("{}", decoder.decode_bits("1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011"));
}
impl MorseDecoder {
fn new() -> MorseDecoder {
MorseDecoder{ morse_code :
[("....-", "4"),("--..--", ","),(".--", "W"),(".-.-.-", "."),("..---", "2"),(".", "E"),("--..", "Z"),(".----", "1"),(".-..", "L"),
(".--.", "P"),(".-.", "R"),("...", "S"),("-.--", "Y"),("...--", "3"),(".....", "5"),("--.", "G"),("-.--.", "("),("-....", "6"),
(".-.-.", "+"),("...-..-", "$"),(".--.-.", "@"),("...---...", "SOS"),("..--.-", "_"),("-.", "N"),("-..-", "X"),("-----", "0"),
("....", "H"),("-...", "B"),(".---", "J"),("---...", ","),("-", "T"),("---..", "8"),("-..-.", "/"),("--.-", "Q"),("...-", "V"),
("----.", "9"),("--", "M"),("-.-.-.", ";"),("-.-.--", "!"),("..-.", "F"),("..--..", "?"),("-...-", "="),("..-", "U"),(".----.", "'"),
("---", "O"),("-.--.-", ")"),("..", "I"),("-....-", "-"),(".-..-.", "\""),(".-", "A"),("-.-.", "C"),("-..", "D"),(".-...", "&"),
("--...", "7"),("-.-", "K")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()}
}
fn match_zeros(&self, s: &str, scale: usize) -> String {
match s.len() / scale{
1 => "".to_string(),
3 => " ".to_string(),
_ => " ".to_string()
}
}
fn match_ones(&self, s: &str, scale: usize) -> String {
match s.len() / scale {
1 => ".".to_string(),
3 => "-".to_string(),
_ => panic!()
}
}
fn decode_seq(&self, s: &str, scale: usize) -> String {
match s.chars().next().unwrap() {
'1' => self.match_ones(s, scale),
'0' => self.match_zeros(s, scale),
_ => panic!()
}
}
fn extract_scale(&self, vec: Vec<&str>) -> usize {
vec.into_iter()
.map(|x| x.len())
.min().unwrap_or(0)
}
pub fn decode_bits(&self, encoded: &str) -> String {
let encoded_zeros_removed = encoded
.trim_start_matches('0')
.trim_end_matches('0');
let signals: Vec<&str> = Regex::new(r"1+|0+").unwrap()
.find_iter(encoded_zeros_removed)
.map(|x| x.as_str())
.collect();
let scale: usize = self.extract_scale(signals.clone());
signals
.into_iter()
.map(|x| self.decode_seq(x, scale))
.collect()
}
fn decode_word(&self, encoded: &str) -> String {
encoded
.split(" ")
.fold(String::new(), |word, letter| {
format!("{}{}", word, self.morse_code.get(letter).unwrap_or(String::new().borrow()))
})
}
pub fn decode_morse(&self, encoded: &str) -> String {
encoded
.trim()
.split(" ")
.into_iter()
.map(|word| self.decode_word(word))
.collect::<Vec<String>>()
.join(" ")
}
}
#[test]
fn example_1() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011")), "HEY JUDE".to_string());
}
#[test]
fn example_2() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("111000111000111000111000000000111000000000111111111000111000111111111000111111111000000000000000000000111000111111111000111111111000111111111000000000111000111000111111111000000000111111111000111000111000000000111")), "HEY JUDE".to_string());
}
#[test]
fn example_extra_zeros_1() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011000000000000")), "HEY JUDE".to_string());
}
#[test]
fn example_extra_zeros_2() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("000000000000000111000111000111000111000000000111000000000111111111000111000111111111000111111111000000000000000000000111000111111111000111111111000111111111000000000111000111000111111111000000000111111111000111000111000000000111")), "HEY JUDE".to_string());
}
#[test]
fn empty() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("")), "".to_string());
}
#[test]
fn empty_zeros() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("0000000000000000")), "".to_string());
}
#[test]
fn example_4() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("11001100110011000000110000001100111111001100110000001100111111001100110000001111110011111100111111")), "HELLO".to_string());
}
#[test]
fn example_5() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("1111000011110000111100000000000001111111111110000111111111111000011111111111100000000000011110000111100001111")), "SOS".to_string());
}
#[test]
fn example_6() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("111010111010001110101110101110111")), "C!".to_string());
}
#[test]
fn example_7() {
let decoder = MorseDecoder::new();
assert_eq!(decoder.decode_morse(&decoder.decode_bits("111000000000111111111000111000000000111111111000111000111")), "END".to_string());
}
|
JavaScript
|
UTF-8
| 1,269
| 2.78125
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
import Todoitem from './todoitem'
class Todolist extends Component {
constructor(props){
super(props);
this.state={
inputValue:'',
list:['html','css','js']
}
this.onhandleChange=this.onhandleChange.bind(this)
this.onhandleClick=this.onhandleClick.bind(this)
}
onhandleChange(e){
this.setState({
inputValue:e.target.value
})
}
onhandleClick(){
let list=this.state.list;
list.push(this.state.inputValue)
this.setState({
list,
inputValue:''
})
}
onhandleDelete(index){
let list =[...this.state.list];
list.splice(index,1)
this.setState({list})
}
gettodoList(){
return this.state.list.map((item,index)=>{
return <Todoitem key={index} index={index} item={item} delete={this.onhandleDelete.bind(this,index)} />
})
}
render() {
return (
<div>
<h3>hello.world</h3>
<input type='text' value={this.state.inputValue} onChange={this.onhandleChange}/>
<button onClick={this.onhandleClick}>添加</button>
<ul>
{this.gettodoList()}
</ul>
</div>
);
}
}
export default Todolist;
|
Python
|
UTF-8
| 1,622
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
__author__ = 'Archana V Menon, Sujith V'
def dominating_set(G):
"""
Finds a greedy approximation for a minimal vertex cover of a specified
graph. At each iteration, the algorithm picks the vertex with the
highest degree and adds it to the cover, until all edges are covered.
:param G: networkx graph
:return: vertex cover as a list of nodes
:raise ValueError: when graph is null
"""
if not G:
raise ValueError("Error : null graph")
# copy given graph
graph = G.copy()
# vertex cover list
vertex_cover = []
while len(graph.edges()) > 0 :
# get degrees of all nodes in the graph
deg = graph.degree()
# find node with maximum degree
v = max(deg, key=deg.get)
# add the node to vertex cover
vertex_cover.append(v)
# delete the node from graph
graph.remove_node(v)
# return vertex_cover
return vertex_cover
if __name__ == "__main__":
# get graph
# from read_graph import read_graph
# G = read_graph("data/CA-GrQc.txt")
from test_graphs import test_graph2
G = test_graph2()
# find approximate dominating set
ds = dominating_set(G)
print "Minimum dominating set \n"
print "Graph size : ", len(G)
print "Length : ", len(ds)
print "Nodes : ", ds
nodes_list1 = ds
nodes_list2 = G.nodes()
for node in nodes_list1:
nodes_list2.remove(node)
# draw graph
print "\n\nDrawing graph. Might take some time ..."
from draw_graph import draw_graph
draw_graph(G, nodes_list1, nodes_list2, G.edges(), None)
|
JavaScript
|
UTF-8
| 836
| 3.90625
| 4
|
[] |
no_license
|
// The Goal
// Destroy the mountains before your starship collides with one of them. For that, shoot the highest mountain on your path.
// Rules
// At the start of each game turn, you are given the height of the 8 mountains from left to right.
// By the end of the game turn, you must fire on the highest mountain by outputting its index (from 0 to 7).
// Firing on a mountain will only destroy part of it, reducing its height. Your ship descends after each pass.
// Constraints
// 0 ≤ mountainH ≤ 9
// Response time per turn ≤ 100ms
// game loop
while (true) {
var position = 0;
var hmax = 0;
for (let i = 0; i < 8; i++) {
var mountainH = parseInt(readline()); // represents the height of one mountain.
if (mountainH > hmax) {
hmax = mountainH;
position = i;
}
}
console.log(position);
}
|
JavaScript
|
UTF-8
| 1,359
| 2.703125
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
import moment from 'moment';
class Timer extends Component {
constructor() {
super();
this.tmrw = moment().add(1, 'day').hours('10').minutes('30').seconds('00').format();
this.before = moment().hours('7').minutes('00').seconds('00').format();
this.after = moment().hours('11').minutes('30').seconds('00').format();
this.date = moment().unix();
this.tmrwTimestamp = moment(this.tmrw).unix();
this.tstamp = moment((this.tmrwTimestamp - this.date) * 1000).format('HH:mm:ss');
this.state = {
tstamp: this.tstamp,
};
}
componentWillMount() {
this.timer = setInterval(() => {
const date = moment().unix();
const tmrwTimestamp = moment(this.tmrw).unix();
// Si je suis entre 8h et 11h30
if (moment().isAfter(this.before) && moment().isBefore(this.after)) {
return this.setState({ tstamp: moment((tmrwTimestamp - date) * 1000).format('HH:mm:ss') });
}
this.setState({ tstamp: 'Reviens à partir de 8h!' });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<p className="main-header-timer-content">
<span id="timer" className="main-header-timer-content-time">
{this.state.tstamp}
</span>
</p>
);
}
}
export default Timer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.