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
|
---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 234 | 2.59375 | 3 |
[] |
no_license
|
d3 = require('d3')
module.exports.expScale = function expScale(a,b,c,exp,round){
var out = d3.scaleLinear()
.domain([0, c])
.range([a, b])
.clamp(true)
if (round) return Math.round(out(exp))
else return out(exp);
}
|
C#
|
UTF-8
| 3,234 | 4.0625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Data_Structures
{
class Program
{
static void Main(string[] args)
{
/*take word and revers inputed word
* take input and display input in reverse
* create separate method for resersing sting
* return type should be a string
* parameter should be a string
* inside sting reverse method, reverse inputed string unsing a stack
* start a stack
* use stack to store characters
* use stack to retrieve characters in reverse order
* display revers string in console
* problem can be solved without stack. if you find easier without still use stack
* ============================================
* consider cases where user does not enter a single word but a sentence
* don't reverse entire sentense, instead reverse each word but keep the words in the original order
* validate user input to make sure user isn't using symbols or numbers
*/
Console.Write("Please enter what you would like to reverse: ");
string forWord = Console.ReadLine(); //grab the word
string finalRev = ReverseString(forWord); // call method
Console.Write($"\nYour word in reverse is {finalRev}.\n\n");
StringBuilder revSent = new StringBuilder(); //new stuff
string[] words = finalRev.Split(' '); //creates an array and splits a string by whatever character you want into different entries in the array.
for (int i = words.Length - 1; i >= 0; i--) //loop through the array backwards to right the order of the words
{
revSent.Append(words[i]); //searches through the array values
revSent.Append(" "); //and appends them together to form a new string with a space between them
}
Console.WriteLine(revSent);
//for (int i = 0; i < finalRev.Length; i++)
//{
// if (finalRev[i] == " ")
// {
// }
//}
Console.Write("There is another way.\n\nYour word in reverse is ");
for (int i = forWord.Length - 1; i >= 0; i--) //this is the non-stack way to do this
{
Console.Write(forWord[i]); //assigns a number and works through the string backwards
}
Console.Write(".\n\n");
}
static string ReverseString(string input)
{
Stack<char> words = new Stack<char>(); //created stack
string newWord = "";
for (int i = 0; i < input.Length; i++) //loop through input
{
//Console.WriteLine($"{input[i]}"); //test
words.Push(input[i]); //save to stack
}
for (int i = 0; i < input.Length; i++) //to grab the text from the top of the stack
{
newWord = newWord + words.Pop();
}
return newWord;
}
}
}
|
Markdown
|
UTF-8
| 2,031 | 2.84375 | 3 |
[] |
no_license
|
---
date: 2018-03-01T00:00:00+11:00
lastmod: 2018-03-01T00:00:00+11:00
title: Hold out your hand, and join our UNIHACK Fam ❤
authors: ["sophia"]
categories:
- Press
tags:
- Agile
cover:
image: https://miro.medium.com/fit/c/1400/420/1*ohg9MMhVKknFw-tvfyH7lg.jpeg
style: half
slug: 43160/UH-recruitment-campaign
---
This article was originally published on UNIHACK Inc's Medium blog.
We were recruiting for new volunteers in the UNIHACK team. In order to give potential applicants a glimpse into what we do and how we operate, I interviewed a number of our volunteers and wrote a 4-part series. The series aims to highlight the various experiences, backgrounds and how our experience helped us grow professionally/personally.
## Hold out your hand, and join our UNIHACK Fam ❤
In any job, you’ve usually got two approaches to choose from — go hard or go home.
In the UNIHACK Fam, we like to go hard and push for the greatest results we can possibly get. There are a lot of lessons to learn in a high-functioning team. Many people don’t realise that there can be more to a student-run organisation than just semi-hard labour and partying hard.
In that sense, UNIHACK stands out, not only do our audience appreciate our events — tech people are always yearning to learn — but we also push our own boundaries as far as we can go. We’re not restricted by a governing body and we get to pick the direction we want to go.
This is not to say that our only goals are simply to work, work, work — we do our best to maximise the learnings of our team members and of course, to have as much cheeky fun as we can on the way.
We want to share that experience with you.
I imagine it can be a bit difficult to understand what the experience is like without a) knowing what we do on a day-to-day basis and b) seeing what we achieve at the end.
{{< button link="https://medium.com/unihack-blog/hold-out-your-hand-and-join-our-unihack-fam-1-4-6f7ada44e769" capt="Read the rest of this on Medium" >}}
|
Java
|
UTF-8
| 274 | 2.71875 | 3 |
[] |
no_license
|
package observer;
public class Ammo {
private int ammo;
public Ammo() {
}
public Ammo(int ammo) {
this.ammo = ammo;
}
public void setAmmo(int ammo) {
this.ammo = ammo;
}
public int getAmmo() {
return ammo;
}
}
|
Java
|
UTF-8
| 279 | 2.34375 | 2 |
[
"MIT"
] |
permissive
|
package net.scratchforfun.gamedev;
import java.awt.*;
/**
* Created by Magnus on 05/10/2014.
*/
public class Player {
public Image texture;
public int posX;
public int posY;
public Player(){
texture = TextureManager.loadTexture("player");
}
}
|
PHP
|
UTF-8
| 834 | 2.8125 | 3 |
[] |
no_license
|
<?php
include('./classes/Student.php');
$student = new Student();
$students = $student->fetch_report_data();
?>
<?php include_once('./header.php') ?>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Year</th>
<th>Number Of Students</th>
</tr>
</thead>
<tbody>
<?php if (mysqli_num_rows($students) > 0) : ?>
<?php while ($student_row = mysqli_fetch_assoc($students)) : ?>
<tr>
<td><?php echo $student_row['current_school_year'] ?></td>
<td><?php echo $student_row['total_num'] ?></td>
</tr>
<?php endwhile; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</body>
</html>
|
Markdown
|
UTF-8
| 1,584 | 3.046875 | 3 |
[] |
no_license
|
# Normes de codification utilisées #
## Fichiers sources ##
- Les fichiers sources sont tous enregistrés selon le suffixe `.java`.
(Les fichiers `.class` ne sont pas inclus dans le dépôt.)
- Une classe seulement par fichier source.
- Les imports sont au début du fichier avant la classe.
## Classes ##
- Les noms de classe sont en PascalCase.
- Toutes les classes sont des noms (sauf le main qui est la fonction du programme).
- Chaque méthode de classe possède une entête avec sa description, ses paramètres et
son retour.
## Méthodes ##
- Les noms de méthodes sont en camelCase.
## Variables ##
- Les noms de constantes sont en SNAKE_CASE (UPPER)
- Les noms de variables sont en camelCase.
## Indentation ##
- Chaque indentation est à 4 espaces de différence.
- La longueur maximale est de 80 caractères, sauf dans la Javadoc des méthodes.
- Les changements de lignes dans une fonction respectent la longueur maximale et sont
effectués après une virgule ou un point-virgule.
- 2 sauts de ligne entre chaque méthodes.
## Commentaires ##
- Le peu de commentaires se retrouvent au début de la classe pour
expliquer les constantes de classes et délimiter les `Getters/Setters`.
- Les commentaires sont implémentés de la façon `End Of Line` soit : ` // `.
- Les commentaires de documentation pour la Javadoc respectent les normes et sont
délimités de la façon suivante : `/**...*/`.
## Déclarations ##
- Chaque déclarations de variable ou instructions se retrouvent sur sa propre ligne.
Aucune autre instruction sur la même ligne.
|
PHP
|
UTF-8
| 3,038 | 2.59375 | 3 |
[] |
no_license
|
<?php
session_start();
include("functions.php");
chkSsid();
//$_SESSION["lid"]の有無を判定(ログインの後か前か判定)
if(!isset($_SESSION["lid"]) || $_SESSION["lid"]=="" ){
$a = "ゲスト";//ログイン前ならゲスト表記
}else{
$a = $_SESSION["lid"];//ログイン後なら$_SESSION["lid"]を表記
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>記事登録</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
div{padding: 10px;font-size:16px;}
input{width:800px;}
</style>
</head>
<body>
<!-- Head[Start] -->
<!-- ログインメニュー -->
<header>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<!-- 一般用メニュー表示 kanri_flg=0 -->
<?php if($_SESSION["kanri_flg"]=="0"){ ?>
<a class="navbar-brand" href="main.php">メイン</a>
<a class="navbar-brand" href="kanri_main.php">自己記事一覧</a>
<a class="navbar-brand" href="index.php">記事作成</a>
<a class="navbar-brand" href="new_account.php">ユーザー作成</a>
<a class="navbar-brand" href="login.php">ログイン</a>
<a class="navbar-brand" href="logout.php">ログアウト</a>
<?php } ?>
<!-- 管理者用メニュー表示 kanri_flg=1 -->
<?php if($_SESSION["kanri_flg"]=="1"){ ?>
<a class="navbar-brand" href="main.php">メイン</a>
<a class="navbar-brand" href="kanri_main.php">記事一覧</a>
<a class="navbar-brand" href="kanri_user.php">ユーザー一覧</a>
<a class="navbar-brand" href="index.php">記事作成</a>
<a class="navbar-brand" href="new_account.php">ユーザー作成</a>
<a class="navbar-brand" href="login.php">ログイン</a>
<a class="navbar-brand" href="logout.php">ログアウト</a>
<?php } ?>
</div>
</nav>
<header>
<!-- Head[End] -->
<!-- ログインの有無により表示する名前を変更 -->
<div><?=$a?>さん、こんにちは</div>
<!-- Main[Start] -->
<form method="post" action="insert.php" enctype="multipart/form-data">
<div class="jumbotron">
<fieldset>
<legend>記事登録</legend>
<label>タイトル:<input type="text" name="title"></label><br>
<span>カテゴリー:</span>
<select name="category">
<option value="cate1">cate1</option>
<option value="cate2">cate2</option>
<option value="cate3">cate3</option>
<option value="other">other</option>
</select><br>
<!-- <label>カテゴリ:<input type="text" name="category"></label><br> -->
<span>見出し画像:</span><input type="file" name="upfile"><br>
内容:<br>
<label><textArea name="detail" rows="40" cols="100"></textArea></label><br>
<input type="submit" value="送信">
</fieldset>
</div>
</form>
<!-- Main[End] -->
</body>
</html>
|
Java
|
UTF-8
| 445 | 2.1875 | 2 |
[] |
no_license
|
package my.orm.hiber;
import org.hibernate.Session;
import my.orm.datasets.UserDataSet;
public class HibernateUserDataSetDAO
{
private Session session;
public HibernateUserDataSetDAO(Session session)
{
this.session = session;
}
public void save(UserDataSet dataSet)
{
session.save(dataSet);
}
public UserDataSet load(long id)
{
return session.load(UserDataSet.class, id);
}
}
|
C++
|
UTF-8
| 275 | 2.59375 | 3 |
[] |
no_license
|
/*
* 1057.cpp
*
* Created on: 2018. 11. 15.
* Author: paul
*/
#include <iostream>
using namespace std;
int main(){
int n, kn, imn;
cin >> n >>kn>>imn;
int cnt=0;
while(kn!=imn){
kn = kn/2+kn%2;
imn = imn/2+imn%2;
cnt++;
}
cout <<cnt;
return 0;
}
|
Markdown
|
UTF-8
| 1,237 | 3.0625 | 3 |
[] |
no_license
|
# Landing Page Project
## Table of Contents
* [Instructions](#instructions)
* [ProjectNotes](#projectnotes)
## Instructions
The starter project has some HTML and CSS styling to display a static version of the Landing Page project. You'll need to convert this project from a static project to an interactive one. This will require modifying the HTML and CSS files, but primarily the JavaScript file.
To get started, open `js/app.js` and start building out the app's functionality
For specific, detailed instructions, look at the project instructions in the Udacity Classroom.
## ProjectNotes
For this project although I also styled a bit of css and had to add a section in html, the focus was clearly on js. The task included writing functions to be used by event handlers to scroll to sections corresponding with anchor links in the navbar and building the navbar dynamically, so one can have as many content in the html section as ones like and does not have to worry about bulding the nav by hand. Issues I faced were manly how to check if a section is in the users view to style it as active and a basic async structure to have a responsive website even with different userinteractions in a close timeframe.
|
C#
|
UTF-8
| 6,792 | 2.671875 | 3 |
[] |
no_license
|
using MenuItemHelperNS;
namespace ModelsClassLibrary.ModelsNS.SharedNS.MenuItemHelperNS
{
public class SystemPurchaseOrders : IOrdersInfo
{
public SystemPurchaseOrders(
decimal systemOpenPurchaseOrdersInMoney,
double systemOpenPurchaseOrdersInQuantity,
decimal systemClosedPurchaseOrdersInMoney,
double systemClosedPurchaseOrdersInQuantity,
decimal systemInProccessPurchaseOrdersInMoney,
double systemInProccessPurchaseOrdersInQuantity,
decimal systemCanceledPurchaseOrdersInMoney,
double systemCanceledPurchaseOrdersInQuantity,
decimal systemBackPurchaseOrdersInMoney,
double systemBackPurchaseOrdersInQuantity)
{
Initialize(
systemOpenPurchaseOrdersInMoney,
systemOpenPurchaseOrdersInQuantity,
systemClosedPurchaseOrdersInMoney,
systemClosedPurchaseOrdersInQuantity,
systemInProccessPurchaseOrdersInMoney,
systemInProccessPurchaseOrdersInQuantity,
systemCanceledPurchaseOrdersInMoney,
systemCanceledPurchaseOrdersInQuantity,
systemBackPurchaseOrdersInMoney,
systemBackPurchaseOrdersInQuantity);
}
public void Initialize(
decimal systemOpenPurchaseOrdersInMoney,
double systemOpenPurchaseOrdersInQuantity,
decimal systemClosedPurchaseOrdersInMoney,
double systemClosedPurchaseOrdersInQuantity,
decimal systemInProccessPurchaseOrdersInMoney,
double systemInProccessPurchaseOrdersInQuantity,
decimal systemCanceledPurchaseOrdersInMoney,
double systemCanceledPurchaseOrdersInQuantity,
decimal systemBackPurchaseOrdersInMoney,
double systemBackPurchaseOrdersInQuantity)
{
_systemOpenPurchasesOrdersInMoney = systemOpenPurchaseOrdersInMoney;
_systemOpenPurchasesOrdersInQuantity = systemOpenPurchaseOrdersInQuantity;
_systemClosedPurchaseOrdersInMoney = systemClosedPurchaseOrdersInMoney;
_systemClosedPurchaseOrdersInQuantity = systemClosedPurchaseOrdersInQuantity;
_systemInProccessPurchaseOrdersInMoney = systemInProccessPurchaseOrdersInMoney;
_systemInProccessPurchaseOrdersInQuantity = systemInProccessPurchaseOrdersInQuantity;
_systemCanceledPurchaseOrdersInMoney = systemCanceledPurchaseOrdersInMoney;
_systemCanceledPurchaseOrdersInQuantity = systemCanceledPurchaseOrdersInQuantity;
_systemBackPurchaseOrdersInMoney = systemBackPurchaseOrdersInMoney;
_systemBackPurchaseOrdersInQuantity = systemBackPurchaseOrdersInQuantity;
}
static decimal _systemOpenPurchasesOrdersInMoney;
static double _systemOpenPurchasesOrdersInQuantity;
public IMenuItemHelper Open
{
get
{
SystemOpenPurchaseOrders item = new SystemOpenPurchaseOrders(_systemOpenPurchasesOrdersInMoney, _systemOpenPurchasesOrdersInQuantity);
return item;
}
}
//----------------------------------------------------------------
static decimal _systemClosedPurchaseOrdersInMoney { get; set; }
static double _systemClosedPurchaseOrdersInQuantity { get; set; }
public IMenuItemHelper Closed
{
get
{
SystemClosedPurchaseOrders item = new SystemClosedPurchaseOrders(_systemClosedPurchaseOrdersInMoney, _systemClosedPurchaseOrdersInQuantity);
return item;
}
}
//----------------------------------------------------------------
static decimal _systemInProccessPurchaseOrdersInMoney { get; set; }
static double _systemInProccessPurchaseOrdersInQuantity { get; set; }
public IMenuItemHelper InProccesss
{
get
{
SystemInProccessPurchaseOrders item = new SystemInProccessPurchaseOrders(_systemInProccessPurchaseOrdersInMoney, _systemInProccessPurchaseOrdersInQuantity);
return item;
}
}
//----------------------------------------------------------------
static decimal _systemCanceledPurchaseOrdersInMoney { get; set; }
static double _systemCanceledPurchaseOrdersInQuantity { get; set; }
public IMenuItemHelper Canceled
{
get
{
SystemCanceledPurchaseOrders item = new SystemCanceledPurchaseOrders(_systemCanceledPurchaseOrdersInMoney, _systemCanceledPurchaseOrdersInQuantity);
return item;
}
}
//----------------------------------------------------------------
static decimal _systemBackPurchaseOrdersInMoney;
static double _systemBackPurchaseOrdersInQuantity;
public IMenuItemHelper BackOrdered
{
get
{
SystemBackPurchaseOrders item = new SystemBackPurchaseOrders(_systemBackPurchaseOrdersInMoney, _systemBackPurchaseOrdersInQuantity);
return item;
}
}
//----------------------------------------------------------------
//static decimal _systemCreditPurchaseOrdersInMoney;
//static double _systemCreditPurchaseOrdersInQuantity;
//public IMenuItemHelper Credit
//{
// get
// {
// SystemCreditPurchaseOrders item = new SystemCreditPurchaseOrders(_systemCreditPurchaseOrdersInMoney, _systemCreditPurchaseOrdersInQuantity);
// return item;
// }
//}
////----------------------------------------------------------------
//static decimal _systemQuotationPurchaseOrdersInMoney;
//static double _systemQuotationPurchaseOrdersInQuantity;
//public IMenuItemHelper Quotation
//{
// get
// {
// SystemQuotationPurchaseOrders item = new SystemQuotationPurchaseOrders(_systemQuotationPurchaseOrdersInMoney, _systemQuotationPurchaseOrdersInQuantity);
// return item;
// }
//}
//----------------------------------------------------------------
public IMenuItemHelper Total
{
get
{
decimal total_PurchaseOrders_Money = 0;
double total_PurchaseOrders_Qty = 0;
SystemTotalPurchaseOrders item = new SystemTotalPurchaseOrders(total_PurchaseOrders_Money, total_PurchaseOrders_Qty);
return item;
}
}
}
}
|
Go
|
UTF-8
| 1,409 | 3.53125 | 4 |
[] |
no_license
|
//author xinbing
//time 2018/8/28 14:18
//数字工具
package utilities
import (
"fmt"
"strconv"
"math"
)
var fmtStrings = []string{
//第一个是补位
"%0.0f","%0.1f","%0.2f","%0.3f","%0.4f","%0.5f","%0.6f","%0.7f","%0.8f","%0.9f","%0.10f",
}
func Round(f float64, precision int) float64 {
if precision <= 0 {
return math.Round(f)
}
var fmtStr string
if precision <= 10 {
fmtStr = fmtStrings[precision]
} else {
fmtStr = "%0."+strconv.Itoa(precision)+"f"
}
s := fmt.Sprintf(fmtStr, f)
nf, _ := strconv.ParseFloat(s, 64)
return nf
}
func Floor(f float64, precision int) float64 {
if precision <= 0 {
return math.Floor(f)
}
pow := math.Pow10(precision)
nf := f * pow
nf = math.Floor(nf) / pow
return Round(nf,precision)
}
func Ceil(f float64, precision int) float64 {
if precision <= 0 {
return math.Ceil(f)
}
pow := math.Pow10(precision)
nf := f * pow
nf = math.Ceil(nf) / pow
return Round(nf, precision)
}
const (
limit = 0.000000001
)
// compare
func Compare(f1 float64, f2 float64) int {
r := f1 - f2
if math.Abs(r) <= limit {
return 0
} else if r > limit {
return 1
} else {
return -1
}
}
//指定比较的精度
func CompareWithScale(f1, f2 float64, scale int) int{
if scale > 0 {
scale = -scale
}
limit := math.Pow10(scale - 1)
r := f1 - f2
if math.Abs(r) <= limit {
return 0
} else if r > limit {
return 1
} else {
return -1
}
}
|
Java
|
UTF-8
| 192 | 1.953125 | 2 |
[] |
no_license
|
package com.atguigu.mybatis.mapper;
import java.util.List;
import com.atguigu.mybatis.entities.Dog;
public interface DogMapper
{
public List<Dog> getDogByName(String dogName);
}
|
Java
|
UTF-8
| 9,176 | 1.976563 | 2 |
[] |
no_license
|
package com.scenetec.upf.operation.repository.codedictionary;
import com.scenetec.upf.operation.model.domain.codedictionary.CodeDictionaryDO;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import com.github.pagehelper.Page;
import java.util.Map;
import java.util.List;
/**
* @author scenetec
* @date 2019/10/30
*/
@Repository
@Mapper
public interface CodeDictionaryMapper {
/**
* 创建
* @param obj
* @return
*/
@Insert("insert into t_code_dictionary (id,user_create,gmt_create,user_modified,gmt_modified,type,code,value,remark) values (#{id},#{userCreate},#{gmtCreate},#{userModified},#{gmtModified},#{type},#{code},#{value},#{remark})")
@Options(useGeneratedKeys = true, keyProperty = "id")
long create(CodeDictionaryDO obj);
/**
* 批量插入
* @param obj
* @return
*/
@Insert(
"<script>"
+"insert into t_code_dictionary ("
+" user_create, gmt_create, user_modified, gmt_modified, type, code, value, remark"
+") values "
+"<foreach collection='list' item='item' index='index' separator=','>"
+"( #{item.userCreate}, #{item.gmtCreate}, #{item.userModified}, #{item.gmtModified}, #{item.type}, #{item.code}, #{item.value}, #{item.remark})"
+"</foreach>"
+"</script>"
)
int insertList(List<CodeDictionaryDO> obj);
/**
* 批量插入(modify:无则插入有则更新)
* @param obj
* @return
*/
@Insert(
"<script>"
+"insert into t_code_dictionary ("
+" user_create, gmt_create, user_modified, gmt_modified, type, code, value, remark"
+") values "
+"<foreach collection='list' item='item' index='index' separator=','>"
+"( #{item.userCreate}, #{item.gmtCreate}, #{item.userModified}, #{item.gmtModified}, #{item.type}, #{item.code}, #{item.value}, #{item.remark})"
+"</foreach>"
+" ON DUPLICATE KEY UPDATE "
+"user_create = VALUES(user_create),"
+"gmt_create = VALUES(gmt_create),"
+"user_modified = VALUES(user_modified),"
+"gmt_modified = VALUES(gmt_modified),"
+"type = VALUES(type),"
+"code = VALUES(code),"
+"value = VALUES(value),"
+"remark = VALUES(remark)"
+"</script>"
)
int modifyList(List<CodeDictionaryDO> obj);
/**
* 删除
* @param userId
* @return
*/
@Delete("delete from t_code_dictionary where id = #{id}")
int delete(Long userId);
/**
* 更新
* @param obj
* @return
*/
@Update(
"<script>"
+"update t_code_dictionary <set> "
+"<if test='userCreate != null'> user_create = #{userCreate}, </if> "
+"<if test='gmtCreate != null'> gmt_create = #{gmtCreate}, </if> "
+"<if test='userModified != null'> user_modified = #{userModified}, </if> "
+"<if test='gmtModified != null'> gmt_modified = #{gmtModified}, </if> "
+"<if test='type != null'> type = #{type}, </if> "
+"<if test='code != null'> code = #{code}, </if> "
+"<if test='value != null'> value = #{value}, </if> "
+"<if test='remark != null'> remark = #{remark}, </if> "
+"</set> where id = #{id}"
+"</script>"
)
int update(CodeDictionaryDO obj);
/**
* 查询详细
* @param id
* @return
*/
@Select("select id, user_create,gmt_create,user_modified,gmt_modified,type,code,value,remark from t_code_dictionary where id = #{id}")
@Results(id="CodeDictionaryResultMap", value = {@Result(property = "id", column = "id"), @Result(property = "userCreate", column = "user_create"),@Result(property = "gmtCreate", column = "gmt_create"),@Result(property = "userModified", column = "user_modified"),@Result(property = "gmtModified", column = "gmt_modified"),@Result(property = "type", column = "type"),@Result(property = "code", column = "code"),@Result(property = "value", column = "value"),@Result(property = "remark", column = "remark")})
CodeDictionaryDO getById(@Param("id") Long id);
@Select("select id,type,code,value from t_code_dictionary where code = #{code}")
@ResultMap("CodeDictionaryResultMap")
CodeDictionaryDO getByCode(@Param("code") String code);
/**
* 查询列表(分页)
* @param params
* @return
*/
@Select(
"<script>"
+ "select id, user_create,gmt_create,user_modified,gmt_modified,type,code,value,remark from t_code_dictionary where 1 = 1"
+ "<if test='params.code != null'> and code = #{params.code}</if>"
+ "<if test='params.type != null'> and type = #{params.type}</if>"
+ "</script>"
)
@ResultMap("CodeDictionaryResultMap")
Page<CodeDictionaryDO> list(@Param("params") Map<String, Object> params);
@Select(
"<script>"
+ "select id, code,value from t_code_dictionary where 1 = 1"
+ "<if test='params.code != null'> and code = #{params.code}</if>"
+ "<if test='params.codeBus != null'> and code REGEXP #{params.codeBus}</if>"
+ "<if test='params.type != null'> and type = #{params.type}</if>"
+ "</script>"
)
@ResultMap("CodeDictionaryResultMap")
Page<CodeDictionaryDO> listBeCodeAndValue(@Param("params") Map<String, Object> params);
/**
* 查询总数
* @param obj
* @return
*/
@Select(
"<script>"
+"select count(*) from t_code_dictionary <where> <trim suffixOverrides='AND'>"
+"<if test='userCreate != null'> user_create = #{userCreate} AND </if> "
+"<if test='gmtCreate != null'> gmt_create = #{gmtCreate} AND </if> "
+"<if test='userModified != null'> user_modified = #{userModified} AND </if> "
+"<if test='gmtModified != null'> gmt_modified = #{gmtModified} AND </if> "
+"<if test='type != null'> type = #{type} AND </if> "
+"<if test='code != null'> code = #{code} AND </if> "
+"<if test='value != null'> value = #{value} AND </if> "
+"<if test='remark != null'> remark = #{remark} AND </if> "
+"</trim></where> "
+"</script>"
)
int count(CodeDictionaryDO obj);
/**
* 通过条件查询单条记录
* @param obj
* @return
*/
@Select(
"<script>"
+"select id, user_create,gmt_create,user_modified,gmt_modified,type,code,value,remark from t_code_dictionary"
+"<where> <trim suffixOverrides='AND'>"
+"<if test='id != null and id>0'> id = #{id} AND </if>"
+"<if test='userCreate != null'> user_create = #{userCreate} AND </if> "
+"<if test='gmtCreate != null'> gmt_create = #{gmtCreate} AND </if> "
+"<if test='userModified != null'> user_modified = #{userModified} AND </if> "
+"<if test='gmtModified != null'> gmt_modified = #{gmtModified} AND </if> "
+"<if test='type != null'> type = #{type} AND </if> "
+"<if test='code != null'> code = #{code} AND </if> "
+"<if test='value != null'> value = #{value} AND </if> "
+"<if test='remark != null'> remark = #{remark} AND </if> "
+"</trim></where> "
+"</script>"
)
@ResultMap("CodeDictionaryResultMap")
CodeDictionaryDO selectOne(CodeDictionaryDO obj);
/**
* 通过条件查询多条记录(不分页)
* @param obj
* @return
*/
@Select(
"<script>"
+"select id, user_create,gmt_create,user_modified,gmt_modified,type,code,value,remark from t_code_dictionary"
+"<where> <trim suffixOverrides='AND'>"
+"<if test='userCreate != null'> user_create = #{userCreate} AND </if> "
+"<if test='gmtCreate != null'> gmt_create = #{gmtCreate} AND </if> "
+"<if test='userModified != null'> user_modified = #{userModified} AND </if> "
+"<if test='gmtModified != null'> gmt_modified = #{gmtModified} AND </if> "
+"<if test='type != null'> type = #{type} AND </if> "
+"<if test='code != null'> code = #{code} AND </if> "
+"<if test='value != null'> value = #{value} AND </if> "
+"<if test='remark != null'> remark = #{remark} AND </if> "
+"</trim></where> "
+"</script>"
)
@ResultMap("CodeDictionaryResultMap")
List<CodeDictionaryDO> selectList(CodeDictionaryDO obj);
@Select(
"<script>"
+ "select * from t_code_dictionary where 1 = 1"
+ "<if test='params.code != null'> and code = #{params.code}</if>"
+ "<if test='params.type != null'> and type = #{params.type}</if>"
+ "<if test='params.value != null '> and value like concat('%',#{params.value},'%')</if>"
+ "order by gmt_modified desc"
+ "</script>"
)
@ResultMap("CodeDictionaryResultMap")
Page<CodeDictionaryDO> pageList(@Param("params") Map<String, Object> params);
}
|
C++
|
UTF-8
| 1,678 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
#include "status.h"
#include <stdio.h>
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
namespace pytorch {
namespace ctc {
Status::Status(pytorch::ctc::Code code, string msg) {
assert(code != pytorch::ctc::OK);
state_ = new State;
state_->code = code;
state_->msg = msg;
}
const string& Status::empty_string() {
static string* empty = new string;
return *empty;
}
string Status::ToString() const {
if (state_ == nullptr) {
return "OK";
} else {
char tmp[30];
const char* type;
switch (code()) {
case pytorch::ctc::Code::CANCELLED:
type = "Cancelled";
break;
case pytorch::ctc::Code::INVALID_ARGUMENT:
type = "Invalid argument";
break;
case pytorch::ctc::Code::FAILED_PRECONDITION:
type = "Failed precondition";
break;
case pytorch::ctc::Code::OUT_OF_RANGE:
type = "Out of range";
break;
default:
snprintf(tmp, sizeof(tmp), "Unknown code(%d)",
static_cast<int>(code()));
type = tmp;
break;
}
string result(type);
result += ": " + state_->msg;
return result;
}
}
std::ostream& operator<<(std::ostream& os, const Status& x) {
os << x.ToString();
return os;
}
namespace errors {
Status InvalidArgument(string msg) { return Status(Code::INVALID_ARGUMENT, msg); }
Status FailedPrecondition(string msg) { return Status(Code::FAILED_PRECONDITION, msg); }
}
}
}
|
C#
|
UTF-8
| 1,064 | 2.546875 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour
{
//customization
[SerializeField] private GameObject attachTarget;
[SerializeField] private Vector3 camOffSet = new Vector3(0f, 1.6f, 0f);
[SerializeField] private float camSensitivity = 2.0f;
//Visualization purpose
[SerializeField] private float xAxis = 0.0f;
[SerializeField] private float yAxis = 0.0f;
// Update is called once per frame
void Update()
{
//Have same position as the attachTarget with an offset
transform.position = attachTarget.transform.position + camOffSet;
//get mouse coords
xAxis += camSensitivity * Input.GetAxis("Mouse X");
yAxis -= camSensitivity * Input.GetAxis("Mouse Y");
//convert mouse coords to eulerAngles
transform.eulerAngles = new Vector3(yAxis, xAxis, 0.0f);
//same I too don't know wtf Euler Angles are but it works
//Thanks StackOverflow
}
}
|
JavaScript
|
UTF-8
| 3,333 | 2.609375 | 3 |
[] |
no_license
|
var express = require('express');
var router = express.Router();
// Require controller modules.
var incident_controller = require('../controllers/incidentController');
var person_controller = require('../controllers/personController');
var vehicle_controller = require('../controllers/vehicleController');
/// INCIDENT ROUTES ///
// GET catalog home page.
router.get('/', incident_controller.index);
// GET request for creating a incident report. NOTE This must come before routes that display incident (uses id).
router.get('/incident/create', incident_controller.incident_create_get);
// POST request for creating a incident report.
router.post('/incident/create', incident_controller.incident_create_post);
// GET request to delete a incident report.
router.get('/incident/:id/delete', incident_controller.incident_delete_get);
// POST request to delete a incident report.
router.post('/incident/:id/delete', incident_controller.incident_delete_post);
// GET request to update a incident report.
router.get('/incident/:id/update', incident_controller.incident_update_get);
// POST request to update a incident report.
router.post('/incident/:id/update', incident_controller.incident_update_post);
// GET request for one of the incident reports.
router.get('/incident/:id', incident_controller.incident_detail);
// GET request for list of the incident reports.
router.get('/incidents', incident_controller.incident_list);
// PERSON ROUTES
// GET request for creating a person. NOTE This must come before route for id (i.e. display author).
router.get('/person/create', person_controller.person_create_get);
// POST request for creating a person.
router.post('/person/create', person_controller.person_create_post);
// GET request to delete a person.
router.get('/person/:id/delete', person_controller.person_delete_get);
// POST request to delete a person.
router.post('/person/:id/delete', person_controller.person_delete_post);
// GET request to update a person.
router.get('/person/:id/update', person_controller.person_update_get);
// POST request to update a person.
router.post('/person/:id/update', person_controller.person_update_post);
// GET request for one person.
router.get('/person/:id', person_controller.person_detail);
// GET request for list of all people.
router.get('/persons', person_controller.person_list);
/// VEHICLE ROUTES ///
// GET request for creating a vehicle. NOTE This must come before route that displays Genre (uses id).
router.get('/vehicle/create', vehicle_controller.vehicle_create_get);
//POST request for creating a vehicle.
router.post('/vehicle/create', vehicle_controller.vehicle_create_post);
// GET request to delete a vehicle.
router.get('/vehicle/:id/delete', vehicle_controller.vehicle_delete_get);
// POST request to delete a vehicle.
router.post('/vehicle/:id/delete', vehicle_controller.vehicle_delete_post);
// GET request to update a vehicle.
router.get('/vehicle/:id/update', vehicle_controller.vehicle_update_get);
// POST request to update a vehicle.
router.post('/vehicle/:id/update', vehicle_controller.vehicle_update_post);
// GET request for one vehicle.
router.get('/vehicle/:id', vehicle_controller.vehicle_detail);
// GET request for list of all vehicles.
router.get('/vehicles', vehicle_controller.vehicle_list);
module.exports = router;
|
JavaScript
|
UTF-8
| 3,391 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
class snakeObjekt {
constructor(){
this.cellsCout = 1;
this.cells=[];
this.step = 5;
this.cellWH = 5;
this.maxW=100;
this.score=0;
this.bgColor=["radial-gradient(circle,#424242 40%,#ffde00 50%,#212121 60%)","radial-gradient(circle,#ff3d00 30%,#424242 40%,#ffff00 50%,#212121 60%)"];
this.shadow=["0px 2px 2px 0px black","0px 0px 25px 3px #ff3d00"];
this.shadpwIdx=0;
this.cr = app.GetScreenHeight()/app.GetScreenWidth();
this.maxH=parseInt(100*(this.cr));
while((this.maxH%5)!=0){this.maxH-=1}
this.directionHead = {x:5,y:0};
app.ShowPopup( Math.floor(this.maxH/10));
this.animationShadow = () =>{
this.shadowIdx===0?this.shadowIdx=1:this.shadowIdx=0;
this.cells[0].elementDiv.style.boxShadow=this.shadow[this.shadowIdx];
this.cells[0].elementDiv.style.background=this.bgColor[this.shadowIdx];
}
this.pushCell = (arg)=>{
this.cells.unshift(new createDiv(1,arg,"radial-gradient(circle,#424242 40%,#ffde00 50%,#212121 60%)","0px 2px 5px 0px rgb(0,0,0)"));
}
this.moveStep = (apple,dir = this.directionHead)=>{
for(let i = 0;i<this.cells.length;i++){
if(i===0){
let c=this.cells[0].xy;
//app.ShowPopup( c.x +">"+apple.xymy.x);
if(c.x===apple.xymy.x&&c.y===apple.xymy.y){
this.cells[0].setCreateColorAndShadow();
this.pushCell(apple.xymy);
apple.newPos();
$("#score").text(++this.score);
break;
}
//app.ShowPopup( JSON.stringify(this.cells[0].xy) );
if(dir.x!=0){
if((c.x<95)&&(c.x!=0)){
this.cells[0].tr({x:(this.cells[0].xy.x+dir.x),y:(this.cells[0].xy.y+dir.y)});
}
else if((c.x===0)&&(dir.x<0)){
this.cells[0].tr({x:95,y:this.cells[0].xy.y+dir.y})
}
else if((c.x===0)&&(dir.x>0)){
this.cells[0].tr({x:c.x+dir.x,y:c.y});
}
else if((c.x===95)&&(dir.x>0)){
this.cells[0].tr({x:0,y:this.cells[0].xy.y})
}
else if((c.x===95)&&(dir.x<0)){
this.cells[0].tr({x:c.x+dir.x,y:c.y})
}
}
if(dir.y!=0){
if((c.y<this.maxH)&&(c.y!=0)){
this.cells[0].tr({x:(this.cells[0].xy.x+dir.x),y:(this.cells[0].xy.y+dir.y)});
}
else if((c.y===0)&&(dir.y<0)){
this.cells[0].tr({x:c.x,y:this.maxH})
}
else if((c.y===0)&&(dir.y>0)){
this.cells[0].tr({x:c.x,y:c.y+dir.y});
}
else if((c.y===this.maxH)&&(dir.y>0)){
this.cells[0].tr({x:c.x,y:0})
}
else if((c.y===this.maxH)&&(dir.y<0)){
this.cells[0].tr({x:c.x,y:c.y+dir.y})
}
}
}
else{
// i%2>0?this.cells[i].s.background="#ff6e40":this.cells[i].setCreateColorAndShadow();
this.cells[i].tr(this.cells[i-1].xyPrev);
}
}
}
this.move=(arg1)=>{
switch (arg1){
case "left":
this.directionHead={x:-5,y:0};
break;
case "down":
this.directionHead={x:-0,y:5};
break;
case "right":
this.directionHead={x:5,y:0};
break;
case "up":
this.directionHead={x:0,y:-5};
break;
};
}
for (let i = 0;i<7;i++){
this.pushCell({x:10,y:50});}
}
}
|
Markdown
|
UTF-8
| 196 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: page
title: Repos
permalink: /repos/
---
{% for repository in site.github.public_repositories %}
* [{{ repository.name }}]({{ repository.html_url }}){:target="_blank"}
{% endfor %}
|
Python
|
UTF-8
| 1,390 | 2.90625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
__all__ = ['xml2elem', 'strptime']
##############################
# xml2elem implementations
import sys
from xml.dom.minidom import parseString
class minidom_xml2elem(object):
def __init__(self, root):
if isinstance(root, basestring):
self.root = parseString(root).childNodes[0]
else:
self.root = root
def find(self, tag):
return minidom_xml2elem(self.root.getElementsByTagName(tag)[0])
def __iter__(self):
for node in self.root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
yield minidom_xml2elem(node)
@property
def attrib(self):
return dict(self.root.attributes.items())
@property
def text(self):
return self.root.childNodes[0].nodeValue
try:
# import lxml if exist
from lxml.etree import XML as xml2elem
except:
if sys.version_info < (2,5):
xml2elem = minidom_xml2elem
else:
from xml.etree.ElementTree import fromstring as xml2elem
##############################
# strptime implementations
import sys, time
from datetime import datetime
# Python2.4 have no `strptime` method at datetime class
if sys.version_info < (2,5):
strptime = lambda t,f: datetime(*(time.strptime(t, f)[0:6]))
else:
strptime = datetime.strptime
|
JavaScript
|
UTF-8
| 1,430 | 3.578125 | 4 |
[] |
no_license
|
function computerPlay() {
let numberOfChoices = 3;
choice = function() {
return Math.floor(Math.random() * Math.floor(numberOfChoices));
};
switch (choice()) {
case 0:
return "rock";
break;
case 1:
return "paper";
break;
case 2:
return "scissors";
break;
}
}
function playRound(playerSelection, computerSelection) {
let _playerSelection = playerSelection.toLowerCase();
switch (true) {
case _playerSelection == "rock" && computerSelection == "paper":
case _playerSelection == "paper" && computerSelection == "scissors":
case _playerSelection == "scissors" && computerSelection == "rock":
return -1;
break;
case _playerSelection == "paper" && computerSelection == "rock":
case _playerSelection == "scissors" && computerSelection == "paper":
case _playerSelection == "rock" && computerSelection == "scissors":
return 1;
break;
case _playerSelection == computerSelection:
return 0;
break;
default:
return `${playerSelection} is not an option. Please choose paper, rock, or scissors.`;
}
}
const game = () => {
let bestOf = 0;
for (i = 0; i < 5; i++) {
let playerSelection = prompt("choose paper, rock, or scissors");
let computerSelection = computerPlay();
bestOf += playRound(playerSelection, computerSelection);
}
return bestOf > 0 ? "you Win!" : "you Lose!";
};
|
Java
|
UTF-8
| 211 | 1.8125 | 2 |
[] |
no_license
|
package com.hexagonal.shop.domain;
import com.hexagonal.shop.domain.core.Product;
import java.util.List;
public interface PriceArchive {
void save(double price, List<Product> products, long timestamp);
}
|
C++
|
UTF-8
| 1,957 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "stdafx.h"
#include "ReLexer.h"
#include "ReToken.h"
#include "ReInputStream.h"
#include "ReIdentifierReader.h"
#include "ReNumberReader.h"
#include "ReOperatorReader.h"
#include "RePunctReader.h"
#include "ReStringReader.h"
#include "ReSyntaxException.h"
#include "ReCompareOperatorReader.h"
#include <regex>
namespace Redneck
{
list<Reader*> Lexer::_readers = CreateReaders();
list<Reader*> Lexer::CreateReaders()
{
list<Reader*> readers;
readers.push_back(new IdentifierReader());
readers.push_back(new NumberReader());
readers.push_back(new OperatorReader());
readers.push_back(new PunctReader());
readers.push_back(new StringReader());
readers.push_back(new CompareOperatorReader());
return readers;
}
Lexer::Lexer(const InputStream& inputStream)
{
_inputStream = inputStream;
_currentToken = Step();
}
Lexer::~Lexer()
{
}
Token Lexer::Peek()
{
return _currentToken;
}
Token Lexer::Next()
{
Token token = Token(_currentToken.GetTokenType(), _currentToken.GetValue());
_currentToken = Step();
return token;
}
void Lexer::Consume(TokenType tokenType)
{
if (_currentToken.GetTokenType() != tokenType)
{
throw SyntaxException();
}
_currentToken = Step();
}
bool Lexer::Eof()
{
Token token = Peek();
return token.GetTokenType() == TokenType::TOKEN_NULL;
}
void Lexer::Skip()
{
while (!_inputStream.Eof() && IsWhitespace(_inputStream.Peek()))
{
_inputStream.Ignore();
}
}
bool Lexer::IsWhitespace(string str)
{
return regex_match(str, regex("( |\\n|\\r|\\t)"));
}
Token Lexer::Step()
{
Skip();
if (_inputStream.Eof())
{
return Token(TOKEN_NULL);
}
string peek = _inputStream.Peek();
for (Reader* reader : _readers)
{
if (reader->IsReadable(peek))
{
return reader->Read(_inputStream);
}
}
return Token(TOKEN_NULL);
}
}
|
C++
|
UTF-8
| 1,532 | 3.15625 | 3 |
[] |
no_license
|
/*
* weapon.h
*
* Created on: 2016年1月8日
* Author: olivia.long
* TAPD:
* Description:
*
*/
#ifndef SRC_PATTERNS_STRATEGY_WEAPON_H_
#define SRC_PATTERNS_STRATEGY_WEAPON_H_
#include <iostream>
using namespace std;
class WeaponBehavior
{
public:
WeaponBehavior(){}
virtual ~WeaponBehavior(){}
virtual void useWeapon() = 0;
};
class KnifeBehavior: public WeaponBehavior
{
public:
KnifeBehavior(){}
~KnifeBehavior(){}
void useWeapon()
{
cout << "use knife" << endl;
}
};
class AxeBehavior: public WeaponBehavior
{
public:
AxeBehavior(){}
~AxeBehavior(){}
void useWeapon()
{
cout << "use axe" << endl;
}
};
class BowAndArrowBehavior: public WeaponBehavior
{
public:
BowAndArrowBehavior(){}
~BowAndArrowBehavior(){}
void useWeapon()
{
cout << "use bow and arrow" << endl;
}
};
class Character
{
public:
void fight()
{
weapon->useWeapon();
}
void setWeapon(WeaponBehavior *new_weapon)
{
weapon = new_weapon;
}
public:
WeaponBehavior *weapon;
};
class Queen: public Character
{
public:
Queen(){
cout << "I am a Queen!" << endl;
weapon = new BowAndArrowBehavior();
}
~Queen(){
delete weapon;
}
};
class King: public Character
{
public:
King(){
cout << "I am a king!" << endl;
weapon = new AxeBehavior();
}
~King(){
delete weapon;
}
};
#endif /* SRC_PATTERNS_STRATEGY_WEAPON_H_ */
|
C
|
UTF-8
| 132 | 3.171875 | 3 |
[] |
no_license
|
#include<stdio.h>
int sum(int x)
{
int s;
for(s=0;x>0;s=s+x%10,x=x/10);
return s;
}
void main()
{
printf("%d\n",sum(143));
}
|
Markdown
|
UTF-8
| 1,689 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# Rendez-vous geolocalise
## Description
> Énoncé disponible [ici](https://www.labri.fr/perso/zemmari/pam/Projet2017.pdf)
Le projet a pour but le développement d’une application permettant d’organiser des rendez-vous géolocalisés.
__Le fonctionnement de l'application est le suivant :__
- Au lancement, l’utilisateur doit pouvoir soit choisir un (ou plusieurs) contact(s), soit saisir le numéro de la personne à contacter (la (ou les) personne(s) contactée(s) doit avoir également installé l’application).
- L’application récupère alors les coordonnées GPS actuelles ou permet à l'utilisateur dans choisir d'autres et les envoie à la ou les personnes choisies.
- À la réception de l'invitation, la personne peut soit accepter soit refuser le rendez-vous. La personne ayant initié le rendez-vous est alors avertie de la décision de l'invité(e).
## Télécharger l'APK
L'application signée est généré lors de la release : [rdv-geo.apk](https://github.com/adrien-chinour/rendez-vous-geolocalise/releases/latest/download/rdv-geo.apk)
## Développement
### Conventions
1. Le code est a écrire en anglais
2. Les commentaires et la documentation sont en français
### Installation du projet
```bash
git clone https://github.com/adrien-chinour/rendez-vous-geolocalise
```
Ajouter le fichier `secrets.xml` dans le répertoire `app/src/mail/res/values/` avec le contenu suivant :
```xml
<resources>
<!-- Clé d'API Google -->
<string name="google_api_key">API_KEY</string>
</resources>
```
Remplacer `API_KEY` avec votre clé API Google autorisant l'accès à l'API **Maps SDK for Android** et **Time Zone API**.
**Le projet est prêt !**
|
PHP
|
UTF-8
| 475 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
namespace app\index\controller;
use think\Controller;
class IndexController extends Controller
{
public function index()
{
$path = "application\\index\\controller\\index.php";
// 定义输出文字
$html = "<p>我是 [path] 文件的index方法</p>";
// 调用temphook钩子, 实现钩子业务
hook('temphook', ['data'=>$html]);
// 替换path标签
return str_replace('[path]', $path, $html);
}
}
|
Python
|
UTF-8
| 2,410 | 3.265625 | 3 |
[] |
no_license
|
import logging
from flask import json
def get_appliance_info_followup(api_auth, parameters, contexts):
"""
Allows users to get detailed information about a particular appliance,in cases where there are
multiple appliances of the same model. In order to do this, we only retrieve a single option
number. It is done this way because the unique identifier is a very long string and we do not
expect users to be able to remember the identifier. Hence, option numbers are currently the
best way to go.
Works by retrieving the list of appliances that match the model and site that the user requests
to get detailed information about. It asks the user for an option number, and delete the
appliance that matches the option number the user put in. A check is done to make sure it is
within range
Parameters:
- api_auth: SteelConnect API object, it contains authentication log in details
- parameters: The json parameters obtained from the Dialogflow Intent. It obtains the following:
> option_choice: An integer that references an option to delete the appliance
Returns:
- speech: A string which has the response to be read/printed to the user
Example Prompt:
- 2
"""
try:
option_choice = int(parameters["OptionNumber"])
except KeyError as e:
error_string = "Error processing getting appliance information follow up intent"
logging.error(error_string)
return error_string
appliance_options = api_auth.node.get_appliance_list()
appliance_id = appliance_options[option_choice - 1] #option_choice -1 because arrays start at zero <-- this is more of a reminder sort of thing...
res = api_auth.node.get_appliance_info(node_id= appliance_id)
if res.status_code == 200:
if option_choice < 1 or option_choice > len(appliance_options): #Check to see if the value the user inputted is within range
speech = "Please selected a number between 1 and {}".format(len(appliance_options))
else:
appliance_info = res.json()
information = api_auth.node.format_appliance_information(appliance_info)
speech = "Information for Appliance ID: {}\n{}".format(appliance_id, "".join(information))
else:
return "Error: Failed to get information for Appliance {}".format(appliance_id)
return speech
|
JavaScript
|
UTF-8
| 1,265 | 3.359375 | 3 |
[] |
no_license
|
const inquirer = require('inquirer');
const Engineer = require('./lib/Engineer');
const Manager = require('./lib/Manager');
const Intern = require('./lib/Intern');
const promptUser = () => {
return inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'What is the name of your team member',
validate: nameInput => {
if (nameInput) {
return true;
} else {
console.log('Please enter the name of your team member!');
return false;
}
}
},
{
type: 'list',
name: 'role',
message: 'What is the role of your team member',
choices: ['Manager', 'Engineer', 'Intern'],
validate: nameInput => {
if (nameInput) {
return true;
} else {
console.log('Please select the role of your team member!');
return false;
}
}
}
]);
};
function init() {
promptUser()
.then((data) => {
var stringOutput = generateMarkdown(data);
writeToFile('SAMPLEREADME.md', stringOutput);
})
}
//data.name, data.role
|
Python
|
UTF-8
| 4,291 | 2.515625 | 3 |
[] |
no_license
|
def test_add_liquidity(t, chain, utils, omg_token, exchange_factory, omg_exchange, assert_tx_failed):
deadline = chain.head_state.timestamp + 300
assert exchange_factory.getExchange(omg_token.address) == omg_exchange.address
assert utils.remove_0x_head(omg_exchange.tokenAddress()) == omg_token.address.hex()
assert utils.remove_0x_head(omg_exchange.factoryAddress()) == exchange_factory.address.hex()
omg_token.approve(omg_exchange.address, 100*10**18)
# Can't add liquidity without tokens
assert_tx_failed(lambda: omg_exchange.addLiquidity(10*10**18, deadline, value=5*10**18, sender=t.k1))
chain.mine()
# msg.value can't be 0
assert_tx_failed(lambda: omg_exchange.addLiquidity(10*10**18, deadline))
chain.mine()
# Token value can't be 0
assert_tx_failed(lambda: omg_exchange.addLiquidity(0, deadline, value=5*10**18))
chain.mine()
# Throw exception if not enough gas is provided
assert_tx_failed(lambda: omg_exchange.addLiquidity(10*10**18, deadline, value=5*10**18, startgas=25000))
# Liquidity provider (t.a0) adds liquidity
omg_exchange.addLiquidity(10*10**18, deadline, value=5*10**18)
assert chain.head_state.get_balance(omg_exchange.address) == 5*10**18
assert omg_token.balanceOf(omg_exchange.address) == 10*10**18
assert omg_exchange.totalSupply() == 5*10**18
assert omg_exchange.balanceOf(t.a0) == 5*10**18
def test_liquidity_pool(t, chain, utils, omg_token, exchange_factory, omg_exchange, assert_tx_failed):
deadline = chain.head_state.timestamp + 300
omg_token.transfer(t.a1, 10*10**18)
omg_token.approve(omg_exchange.address, 100*10**18)
omg_token.approve(omg_exchange.address, 10*10**18, sender=t.k1)
# First liquidity provider (t.a0) adds liquidity
omg_exchange.addLiquidity(2*10**18, deadline, value=1*10**18)
assert omg_exchange.totalSupply() == 1*10**18
assert omg_exchange.balanceOf(t.a0) == 1*10**18
assert omg_exchange.balanceOf(t.a1) == 0
assert omg_exchange.balanceOf(t.a2) == 0
assert omg_token.balanceOf(t.a1) == 10*10**18
assert omg_token.balanceOf(t.a2) == 0
assert chain.head_state.get_balance(omg_exchange.address) == 1*10**18
assert omg_token.balanceOf(omg_exchange.address) == 2*10**18
# Second liquidity provider (t.a1) adds liquidity
omg_exchange.addLiquidity(1, deadline, value=5*10**18, sender=t.k1)
assert omg_exchange.totalSupply() == 6*10**18
assert omg_exchange.balanceOf(t.a0) == 1*10**18
assert omg_exchange.balanceOf(t.a1) == 5*10**18
assert omg_exchange.balanceOf(t.a2) == 0
assert omg_token.balanceOf(t.a1) == 0
assert chain.head_state.get_balance(omg_exchange.address) == 6*10**18
assert omg_token.balanceOf(omg_exchange.address) == 12*10**18
# Can't divest more liquidity than owned
assert_tx_failed(lambda: omg_exchange.removeLiquidity((5*10**18 + 1), 1, 1, deadline, sender=t.k2))
# Mine block
chain.mine()
# Second liquidity provider (t.a1) transfers liquidity to third liquidity provider (t.a2)
omg_exchange.transfer(t.a2, 2*10**18, sender=t.k1)
assert omg_exchange.balanceOf(t.a0) == 1*10**18
assert omg_exchange.balanceOf(t.a1) == 3*10**18
assert omg_exchange.balanceOf(t.a2) == 2*10**18
assert omg_token.balanceOf(t.a1) == 0
assert chain.head_state.get_balance(omg_exchange.address) == 6*10**18
assert omg_token.balanceOf(omg_exchange.address) == 12*10**18
# Mine block
chain.mine()
# First, second and third liquidity providers remove their remaining liquidity
omg_exchange.removeLiquidity(1*10**18, 1, 1, deadline)
omg_exchange.removeLiquidity(3*10**18, 1, 1, deadline, sender=t.k1)
omg_exchange.removeLiquidity(2*10**18, 1, 1, deadline, sender=t.k2)
assert omg_exchange.totalSupply() == 0
assert omg_exchange.balanceOf(t.a0) == 0
assert omg_exchange.balanceOf(t.a1) == 0
assert omg_exchange.balanceOf(t.a2) == 0
assert omg_token.balanceOf(t.a1) == 6*10**18
assert omg_token.balanceOf(t.a2) == 4*10**18
assert chain.head_state.get_balance(omg_exchange.address) == 0
assert omg_token.balanceOf(omg_exchange.address) == 0
# Can add liquidity again after all liquidity is divested
omg_exchange.addLiquidity(2*10**18, deadline, value=1*10**18)
|
Markdown
|
UTF-8
| 4,347 | 3 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# machinae
This is the documentation for [machinae][ma], a generic state machine
intended to be primarily used in game development.
In addition to this book you can find a list of the items in
the [API documentation][ap].
[ma]: https://github.com/rustgd/machinae
[ap]: https://docs.rs/machinae
You'll mostly need the types `StateMachine`, `State` and `Trans`.
The state machine stores a stack of states and updates that stack
according to the `Trans`itions returned by the current state.
## Book structure
This book is split into five chapters, this being the introduction. After this chapter:
* [Implementing State][im]
* [State methods and transitions][me]
* [Using machinae outside of game development][us]
* [Troubleshooting][tr]
[im]: ./01_state.html
[me]: ./02_methods.html
[us]: ./03_non_game_dev.html
[tr]: ./04_trouble.html
## Example code
```rust
extern crate machinae;
use machinae::*;
#[derive(Debug)]
struct Error;
enum Event {
WindowQuit,
KeyPress(char),
}
struct Game {
// ..
}
enum GameState {
Loading,
MainMenu,
InGame,
}
impl<'a> State<&'a mut Game, Error, Event> for GameState {
fn start(&mut self, args: &mut Game) -> Result<Trans<Self>, Error> {
match *self {
GameState::Loading => {
args.load("buttons");
args.load("player");
Trans::None
}
GameState::MainMenu => {}
GameState::InGame => {
if !args.login() {
Trans::None
} else {
eprintln!("Login failed");
Trans::Pop
}
}
}
}
// all methods have a default no-op implementation,
// so you can also leave them out
fn resume(&mut self, _: &mut Game) {}
fn pause(&mut self, _: &mut Game) {}
fn stop(&mut self, args: &mut Game) {
match *self {
GameState::Loading => {}
GameState::MainMenu => {}
GameState::InGame => args.logout(),
}
}
fn update(&mut self, args: &mut Game) -> Result<Trans<Self>, Error> {
match *self {
GameState::Loading => {
let progress = args.progress();
args.draw_bar(progress);
if progress == 1.0 {
Trans::Switch(GameState::MainMenu)
} else {
Trans::None
}
}
GameState::MainMenu => {
if args.button("start_game") {
Trans::Push(GameState::InGame)
} else {
Trans::None
}
}
GameState::InGame => {
args.draw("player");
if args.is_alive("player") {
Trans::None
} else {
// Don't let the user rage quit
Trans::Quit
}
},
}
}
fn fixed_update(&mut self, args: &mut Game) -> Result<Trans<Self>, Error> {
match *self {
GameState::Loading => {}
GameState::MainMenu => {}
GameState::InGame => args.do_physics(),
}
}
fn event(&mut self, args: &mut Game, event: Event) -> Result<Trans<Self>, Error> {
match event {
Event::KeyPress('w') => args.translate("player", 3.0, 0.0),
Event::KeyPress('q') => Trans::Quit,
Event::WindowQuit => Trans::Quit,
}
}
}
fn run() -> Result<(), Error> {
use std::time::{Duration, Instant};
let mut machine = StateMachineRef::new(GameState::Loading);
let mut game = Game { /*..*/ };
machine.start(&mut game)?;
machine.fixed_update(&mut game)?;
let mut last_fixed = Instant::now();
while machine.running() {
for event in window.poll_events() {
machine.event(&mut game, event)?;
}
if last_fixed.elapsed().subsec_nanos() > 4_000_000 {
machine.fixed_update(&mut game)?;
}
machine.update(&mut game)?;
}
Ok(())
}
fn main() {
if let Err(e) = run() {
eprintln!("Error occurred: {:?}", e);
}
}
```
|
C++
|
UTF-8
| 1,669 | 2.65625 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
struct Persist_Tree{
struct Node{
int l,r,lnum,rnum,li,ri;
};
Node node[2000000];
int used;
int pos[100001];
void build(int i,int l,int r){
node[i].l=l,node[i].r=r;
node[i].lnum=node[i].rnum=0;
if(l+1==r)return;
int m=(l+r)>>1;
node[i].li=used++,node[i].ri=used++;
build(node[i].li,l,m),build(node[i].ri,m,r);
}
void add(int i,int j,int x){
node[i]=node[j];
if(node[i].l+1==node[i].r)return;
int m=(node[i].l+node[i].r)>>1;
if(x<m){
node[i].lnum++;
node[i].li=used++;
add(node[i].li,node[j].li,x);
}else{
node[i].rnum++;
node[i].ri=used++;
add(node[i].ri,node[j].ri,x);
}
}
int query(int i,int j,int x){
if(node[i].l+1==node[i].r)return 0;
int m=(node[i].l+node[i].r)>>1;
if(x<m){
return node[i].rnum-node[j].rnum+query(node[i].li,node[j].li,x);
}else{
return query(node[i].ri,node[j].ri,x);
}
}
};
Persist_Tree pt;
int main(){
int i,j,m,n,a,b,c,d;
pt.pos[0]=0;
while(scanf("%d %d",&n,&m)==2){
pt.used=0;
pt.build(pt.used++,0,n+1);
for(i=0;i<n;i++){
scanf("%d",&j);
pt.pos[i+1]=pt.used++;
pt.add(pt.pos[i+1],pt.pos[i],j);
}
while(m--){
scanf("%d %d %d %d",&a,&b,&c,&d);
printf("%d\n",pt.query(pt.pos[b],pt.pos[a-1],c-1)-pt.query(pt.pos[b],pt.pos[a-1],d));
}
}
}
|
Markdown
|
UTF-8
| 861 | 2.65625 | 3 |
[] |
no_license
|
# ALttPRSpriteRandomizer
Script for use with [ALttPEntranceRandomizer](http://github.com/KevinCathcart/ALttPEntranceRandomizer) (*"ALttPER"*) to add random sprites to game files
## Setup
* Needs [python](https://www.python.org/downloads/)
* Needs [*ALttPER*](http://github.com/KevinCathcart/ALttPEntranceRandomizer) python script
* Place `SpriteRandomizer.py` into *ALttPER* `\data\` folder
* Script will pull all `*.sfc` files in `\data\gamefiles\`
* Script will pull a random `*.zspr` file from `\data\sprites\` to patch into each `*.sfc`, choosing a random sprite each time (may result in duplicates)
## Usage
* `python SpriteRandomizer.py`
## Output:
* Script will blindly write gamefiles to `\data\` folder, overwriting files if they have the same filename
* Script uses ERROR channel to print its messages as opposed to INFO which the main script uses
|
Markdown
|
UTF-8
| 7,774 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
---
title: Menggunakan UUID (Universally Unique Identifier) di PHP / Laravel
author: Yoga Hanggara
extends: _layouts.post
section: content
categories: [php, laravel-5, laravel-4, basic, uuid, database]
date: 2015-07-31
---
## Problem 1: Tebak-Tebak Berhadiah
Selama ini, kita sering menggunakan _Auto-Increment Integer_ sebagai _Primary Key_ dalam tabel-tabel _database_ kita. Kemudian biasanya dalam aplikasi web, kita mengakses data tersebut dengan alamat URL seperti ini:
http://myapplication.com/user?id=105
http://myapplication.com/user/105
Pengguna aplikasi kita bisa mengenali dengan mudah URL tersebut, dimana `User ID` kita adalah `105`. Suatu saat pengguna tersebut iseng-iseng mengakses URL dan mengganti `User ID` misal `104`, atau `106`. Sehingga User bisa mengetahui siapa User yang mendaftar sebelum dan sesudah dirinya, padahal bisa jadi itu tidak diperbolehkan. Atau, pengguna menggunakan `User ID = 1`, yang mana biasanya User ID `1` itu adalah _User Administrator_, tentu ini berbahaya.
Atau bisa saja ada orang iseng, _hacker_, yang penasaran, lalu membuat sebuah _program_ untuk mendapatkan data-data semua User, hanya dengan perintah sederhana, sebagai contoh:
for ($i = 1; $i <= 1000, $i++) {
saveData('http://myapplication.com/user?id=' . $i);
}
// Result:
// http://myapplication.com/user?id=1
// http://myapplication.com/user?id=2
// http://myapplication.com/user?id=...
// http://myapplication.com/user?id=999
// http://myapplication.com/user?id=1000
Dengan _script_ sederhana, _Hacker_ ini bisa mendapatkan semua data-data User hanya dalam waktu singkat saja.
## Problem 2: Primary Key Conflict dan Scalabillity
Ceritanya, kita telah berhasil membuat sebuah aplikasi besar, dan digunakan di satu tempat. Data-datanya sudah ribuan. Kemudian ada permintaan untuk memasang aplikasi tersebut di tempat lain juga, sehingga nantinya akan ada 2 _server_ aplikasi, atau bahkan lebih.
Data-data aplikasi di Server #1 sudah menggunakan _Primary Key_ `ID` katakanlah `1 s/d 1.000.000`. Aplikasi di Server #2, karena baru, tentu saja akan menggunakan _Primary Key_ `ID` dari `0` lagi, dan `auto-increment` juga. Sampai saat ini tentu tidak ada masalah, karena 2 aplikasi tersebut berjalan sendiri-sendiri.
Di kemudian hari, ada permintaan untuk menggabungkannya jadi 1 tempat, karena alasan agar lebih mudah dikelola dan distribusi terpusat. Pertanyaannya, lalu bagaimana menggabungkannya? Apakah sekedar `copy` dan `paste` bisa? Jawabannya tentu tidak bisa, karena pasti akan ada data bentrok/konflik di keduanya, disebabkan _Primary Key_ `ID` banyak yang sama. Padahal sebuah _Primary Key_ harus **unique**.
Dalam kasus lain, aplikasi yang memiliki jumlah transaksi yang sangat banyak, masif, dan cepat, misal dalam 1 detik ada 1000 transaksi/_insert_ data baru, fungsi `auto-increment` ini akan tidak berfungsi dengan baik. Namun jika _insert_ masih sebatas 1-2 menit sekali, hal ini belum jadi masalah.
## Solusi: Apa itu UUID (Universally Unique Identifier) ?
Dari [Wikipedia](https://en.wikipedia.org/wiki/Universally_unique_identifier):
> The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. In this context the word unique should be taken to mean "practically unique" rather than "guaranteed unique". Since the identifiers have a finite size, it is possible for two differing items to share the same identifier. The identifier size and generation process need to be selected so as to make this sufficiently improbable in practice. Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.
Gampangnya, UUID adalah kumpulan 32 karakter (_String_) yang dibuat secara acak (_random_) dengan teknik khusus yang dijamin unik untuk setiap data. Dalam waktu 1 detik pun, jika di-_generate_ 1000 UUID, kecil kemungkinan ada UUID yang sama. Sehingga lebih cocok untuk digunakan sebagai _Primary Key_.
Contoh UUID (tanpa strip):
25769c6cd34d4bfeba98e0ee856f3e7a
00b245066523042a3bf4698f30617f0e
0179ec949e72ed4df4e0182965a71073
UUID tersebut tentu saja sulit ditebak oleh pengguna karena tidak mempunyai pola khusus. Jika ada _hacker_ yang ingin menggunakan program _looping_ untuk mendapatkan seluruh data User, maka dia perlu membuat banyak kombinasi 32 karakter tersebut, tentu tidak mudah dan membutuhkan waktu lama.
## Library UUID Generator untuk PHP / Laravel
Jika kita _search_ _Composer Package_ di [Packagist](https://packagist.org/search/?q=uuid ) _library_ yang populer digunakan untuk membuat UUID ini adalah [ramsey/uuid](https://packagist.org/packages/ramsey/uuid) / _website:_ [RAMSEY/UUID](https://benramsey.com/projects/ramsey-uuid/) / _source:_ [GitHub](https://github.com/ramsey/uuid).
Tambahkan _package_ ini di _composer.json_ dengan perintah:
composer require ramsey/uuid
Kemudian untuk menggunakannya, dapat menggunakan contoh seperti yang ada di dokumentasi _library_ ini:
require 'vendor/autoload.php';
use Ramsey\Uuid\Uuid;
// Generate a version 1 (time-based) UUID object
$uuid1 = Uuid::uuid1();
echo $uuid1->toString() . "\n"; // e4eaaaf2-d142-11e1-b3e4-080027620cdd
// Generate a version 3 (name-based and hashed with MD5) UUID object
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid3->toString() . "\n"; // 11a38b9a-b3da-360f-9353-a5a725514269
// Generate a version 4 (random) UUID object
$uuid4 = Uuid::uuid4();
echo $uuid4->toString() . "\n"; // 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a
// Generate a version 5 (name-based and hashed with SHA1) UUID object
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid5->toString() . "\n"; // c4a760a8-dbcf-5254-a0d9-6a4474bd1b62
UUID yang dibuat ada beberapa jenis versi (versi 1 s/d 5), masing-masing mempunyai kebutuhan sendiri-sendiri. Saya biasanya menggunakan versi 4.
### Tipe Data Database
Karena kita menggunakan UUID _string_ sebagai _Primary Key_, maka tipe data _field_ yang dibuat tidak bisa _Integer_, namun harus _Variable Character (VARCHAR)_, dengan panjang 32 karakter maksimum. Di Laravel, untuk _Migration_ dan _Schema Builder_ juga harus disesuaikan:
Schema::create('users', function(Blueprint $table)
{
$table->string('id', 32)->primary();
});
### Eloquent ORM
Agar bisa menggunakan UUID di _Model Eloquent ORM_, kita harus menonaktifkan terlebih dahulu fitur _auto increment_, dengan cara:
class User extends Model {
protected $table = 'users';
public $incrementing = false;
}
Kemudian kita bisa menggunakan UUID ini pada saat `Create/Update` data seperti biasanya.
use Ramsey\Uuid\Uuid;
class UserController extends Controller {
public function store()
{
$user = new User;
$user->id = Uuid::uuid4()->getHex(); // toString();
$user->name = "Yoga Hanggara";
$user->save();
}
public function update($id)
{
$user = User::find($id);
$user->save();
}
}
### Efek Samping
Salah satu efek samping menggunakan UUID sebagai _Primary Key_ adalah tidak bisa melakukan _sorting_ atau _order by_ `ID` ini, karena datanya berupa _String_, bukan _Integer_ seperti biasanya. Untuk kebutuhan ini, kita harus pintar-pintar memanipulasi kolom `created_at` / `updated_at`.
Kesulitan lainnya adalah, `ID/UUID` ini menjadi susah untuk diingat :p
|
Python
|
UTF-8
| 3,348 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
import math
import numpy as np
from io import TextIOWrapper, FileIO
from pathlib import Path
from imageio import imread, imwrite
from typing import List
from .binary_manipulation import substitute_lsb, extract_lsb, message_to_binary
from .utils import image_needed_size
def encode(
input_message: TextIOWrapper,
input_image: Path,
output_path: Path,
delimiter: str,
) -> None:
"""Encode a text file using LSB image steganography inside a provided image, storing
the final image on the [output_path]
Args:
input_message (TextIOWrapper): [description]
input_image (Path): [description]
output_path (Path): [description]
delimiter (str): [description]
Raises:
ValueError: if the message size is larger than the length of the provided image
"""
message: str = input_message.read() + delimiter
message: str = message_to_binary(message)
message: List[str] = list(message)
image = imread(input_image)
max_possible_encoded_bits = len(image) * len(image[0]) * 3
if len(message) > max_possible_encoded_bits:
raise ValueError(
"Message is too long for encoding in the provided image. Provide a larger image or a shorter message"
)
red, blue, green = 0, 1, 2
data_index: int = 0
for values in image:
for pixels in values:
if data_index < len(message):
pixels[red] = substitute_lsb(pixels[red], message[data_index])
data_index += 1
if data_index < len(message):
pixels[green] = substitute_lsb(pixels[green], message[data_index])
data_index += 1
if data_index < len(message):
pixels[blue] = substitute_lsb(pixels[blue], message[data_index])
data_index += 1
if data_index >= len(message):
break
imwrite(output_path, image)
print(f"Output image saved in {output_path}")
def decode(input_image: Path, output_message: Path, delimiter: str = "#####") -> None:
"""Decodes a previously encoded message in an provided image, searching for
the [delimiter] at the message end.
Args:
input_image (Path): Path to source image
output_message (Path): Path where the output message will be written
delimiter (str): End of message delimiter.
"""
image = imread(input_image)
binary_data = ""
red, blue, green = 0, 1, 2
for values in image:
for pixels in values:
binary_data += extract_lsb(pixels[red], 1)
binary_data += extract_lsb(pixels[green], 1)
binary_data += extract_lsb(pixels[blue], 1)
byte_data = [binary_data[i : i + 8] for i in range(0, len(binary_data), 8)]
decoded_data = ""
delimiter_found: bool = False
for byte in byte_data:
decoded_data += chr(int(byte, 2))
if decoded_data[-len(delimiter) :] == delimiter:
delimiter_found = True
break
with open(output_message, "w") as fp:
fp.write(decoded_data[: -len(delimiter)])
if delimiter_found:
print(f"Output text saved in {output_message}")
else:
print(
f"Output text saved in {output_message}, but message delimiter could not been found, results may be a little odd."
)
|
JavaScript
|
UTF-8
| 1,137 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
const moment = require('moment')
const r2 = require('r2')
const _ = require('lodash')
const Promise = require('bluebird')
module.exports = async function (req, res) {
const app = this;
let foodsToAvoid = []
let pastFiveBirthdays = []
for (var i = 0, years = 5; i < years; i++) {
let birthday = moment(req.body.date)
pastFiveBirthdays.push(birthday.subtract(i, 'years'))
}
Promise.map(pastFiveBirthdays, birthday => {
return getFoodsToAvoidWithinTwoWeeksOf(birthday)
.then(foods => {
foods.map(food => {
foodsToAvoid.push(food);
})
})
}).then(() => {
return res.json({ foodsToAvoid: foodsToAvoid })
})
async function getFoodsToAvoidWithinTwoWeeksOf(date) {
const oneWeekBeforeDate = date.subtract(1, 'week').format('YYYYMMDD')
const oneWeekAfterDate = date.add(2, 'week').format('YYYYMMDD')
const url = `https://api.fda.gov/food/enforcement.json?search=report_date:[${oneWeekBeforeDate}+TO+${oneWeekAfterDate}]`
let resp = await r2.get(url).json
return _.map(resp.results, result => {
return result.product_description
})
}
}
|
Python
|
UTF-8
| 2,665 | 4.65625 | 5 |
[] |
no_license
|
#DAY 6 TASK
#1)Write a program to loop through a list of numbers and add +2 to every value to elemenys in list
n = [1,2,3,4,5,6,7]
for i in n:
i += 2
print(i)
"""
2)Write a program to get the below pattern
54321
4321
321
21
1
"""
rows = int(input("Enter the number of rows: "))
for i in range(0, rows + 1):
for j in range(rows - i, 0, -1):
print(j, end=' ')
print()
#3)Python program to print the Fibonacci series
n = int(input("\nPlease Enter the Range Number: "))
f1 = 0
f2 = 1
for Num in range(0, n):
if(Num <= 1):
f0 = Num
else:
f0 = f1 + f2
f1 = f2
f2 = f0
print(f0)
#4)Explain Armstrong number and write a code with a function
n = int(input("Enter a number: "))
sum = 0
temp = n
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if n == sum:
print(n,"is an Armstrong number")
else:
print(n,"is not an Armstrong number")
#5)Write a program to print the multiplication table of 9
n = int(input("Enter the multiplication number: "))
r = int(input("Enter the range:"))
print("Multiplication table of",n)
for i in range(1,r+1):
print(i,'x',n,'=',i*n)
#6)Check if a program is negative or positive
n=int(input ("Enter your number:"))
if(n>0):
print("Number is positive.")
else:
print("Number is negative.")
#7)Write a program to convert the number of days to ages
Days=int(input ("Enter Days:"))
Years=(int)(Days/365)
print("Days to Years:", Years)
#8)Solve Trigonometry problem using math function write a program to solve using math function
import math
x = math.pi/5
y = 4
z = 5
print ("The value of tangent of pi/5 is : ", end="")
print (math.tan(x))
print ("The value of hypotenuse of 4 and 5 is : ", end="")
print (math.hypot(y,z))
#9)Create a calculator only on a code level by using if condition(Basic arithmetic calculation)
print("Calculator")
print("1.Add")
print("2.Substract")
print("3.Multiply")
print("4.Divide")
ch=int(input("Enter Choice(1-4): "))
if ch==1:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a+b
print("Sum = ",c)
elif ch==2:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a-b
print("Difference = ",c)
elif ch==3:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a*b
print("Product = ",c)
elif ch==4:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a/b
print("Quotient = ",c)
else:
print("Invalid Choice")
|
Python
|
UTF-8
| 678 | 3.328125 | 3 |
[] |
no_license
|
# Definition for a binary tree node.
from functools import lru_cache
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
@lru_cache(None)
def rob(self, root: TreeNode) -> int:
if root is None:
return 0
# 抢劫
left = 0 if root.left is None else self.rob(root.left.left) + self.rob(root.left.right)
right = 0 if root.right is None else self.rob(root.right.left) + self.rob(root.right.right)
do_it = root.val + left + right
not_do = self.rob(root.left) + self.rob(root.right)
res = max(do_it, not_do)
return res
|
SQL
|
ISO-8859-1
| 1,841 | 2.546875 | 3 |
[] |
no_license
|
INSERT INTO Pregunta VALUES ('Tengo nombre de animal, cuando la rueda se pincha me tienes que utilizar',
'El len', 'El felino', 'El gato', 'El perro', '20','Comunicacion');
INSERT INTO Pregunta VALUES ('Todos me quieren para descansar si ya te lo he dicho!! no pienses ms',
'La mesa', 'La cama', 'La vereda', 'La silla', '20','Comunicacion');
INSERT INTO Pregunta VALUES ('Te la digo y no me entiendes, te la repito y no me comprendes',
'El algodn', 'La manta', 'El cuero', 'La Tela', '20','Comunicacion')
INSERT INTO Pregunta VALUES ('Soy ave y soy llana, pero no tengo pico ni alas',
'El avestruz', 'La Avellana', 'La nuez', 'El pico', '20','Comunicacion')
INSERT INTO Pregunta VALUES ('Me gustara ser tigre pero no tengo su altura, cuando escuches un "miau" lo adivinaras sin duda',
'El gato', 'El perro', 'El loro', 'El tigre', '20','Comunicacion')
INSERT INTO Pregunta VALUES ('Llevo dinero y no soy banquero, papel o metal, lo que sea me da igual',
'El bolso', 'El maletin', 'La cartera', 'La mochila', '20','Comunicacion')
INSERT INTO Pregunta VALUES ('Redondo soy como un pandero, quien me tome en verano que use sombrero',
'La luna', 'La moneda', 'El sol', 'Una esfera', '20','Comunicacion');
INSERT INTO Pregunta VALUES ('Es pequea como una pera, pero alumbra la casa entera',
'El foco', 'La bombilla', 'La electricidad', 'La lmpara', '20','Comunicacion');
INSERT INTO Pregunta VALUES ('En rincones y entre ramas mis redes voy construyendo, para que moscas incautas, en ellas vayan cayendo',
'Ciempis', 'Cochinillas', 'Milpis', 'La araa', '20','Comunicacion');
INSERT INTO Pregunta VALUES ('Y lo es Y lo es y no lo adivinars aunque te d en un mes',
'La tela', 'El hilo', 'El cartn', 'La hoja', '20','Comunicacion');
|
Markdown
|
UTF-8
| 3,785 | 2.796875 | 3 |
[] |
no_license
|
---
description: "recipe for Beef-Rice-Cheese Casserole | how to cook Beef-Rice-Cheese Casserole"
title: "recipe for Beef-Rice-Cheese Casserole | how to cook Beef-Rice-Cheese Casserole"
slug: 127-recipe-for-beef-rice-cheese-casserole-how-to-cook-beef-rice-cheese-casserole
date: 2020-04-26T13:25:13.367Z
image: https://img-global.cpcdn.com/recipes/c90aee595193e8cd/751x532cq70/beef-rice-cheese-casserole-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/c90aee595193e8cd/751x532cq70/beef-rice-cheese-casserole-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/c90aee595193e8cd/751x532cq70/beef-rice-cheese-casserole-recipe-main-photo.jpg
author: Justin Richards
ratingvalue: 4
reviewcount: 8
recipeingredient:
- "1 cup long grain rice"
- "2 tablespoons oil"
- "1 pound lean ground beef"
- "1/2 cup chopped onion"
- "1 teaspoon chili powder"
- "2 cups water"
- "1 1/4 cups tomato juice"
- "3 beef bouillon cubes"
- "8 ounces grated cheddar cheese"
recipeinstructions:
- "In medium skillet, brown rice in oil. Remove from skillet."
- "In same skillet, brown beef with onions and chili powder. Stir in rice. Turn into 11 x 7 baking dish."
- "In medium saucepan, combine water, tomato juice and bouillon. Cook, stirring until bouillon dissolves. Pour over meat mixture. Cover and bake 40 minutes at 350 degrees or until rice is tender."
- "Remove cover, top with cheese and bake 5 minutes longer."
categories:
- Recipe
tags:
- beefricecheese
- casserole
katakunci: beefricecheese casserole
nutrition: 150 calories
recipecuisine: American
preptime: "PT27M"
cooktime: "PT40M"
recipeyield: "1"
recipecategory: Dessert
---

Hey everyone, it's Drew, welcome to our recipe page. Today, I will show you a way to prepare a simple dish, beef-rice-cheese casserole. It is one of my favorites food recipe. This time, I'm gonna make it a bit tasty. This will be really delicious.
Beef-Rice-Cheese Casserole is one of the most popular of current trending meals in the world. It is easy, it's quick, it tastes yummy. It is appreciated by millions every day. Beef-Rice-Cheese Casserole is something that I have loved my entire life. They are nice and they look wonderful.
To get started with this particular recipe, we must prepare a few ingredients. You can have beef-rice-cheese casserole using 9 ingredients and 4 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Beef-Rice-Cheese Casserole:
1. Make ready 1 cup long grain rice
1. Get 2 tablespoons oil
1. Get 1 pound lean ground beef
1. Take 1/2 cup chopped onion
1. Take 1 teaspoon chili powder
1. Take 2 cups water
1. Prepare 1 1/4 cups tomato juice
1. Get 3 beef bouillon cubes
1. Take 8 ounces grated cheddar cheese
<!--inarticleads2-->
##### Instructions to make Beef-Rice-Cheese Casserole:
1. In medium skillet, brown rice in oil. Remove from skillet.
1. In same skillet, brown beef with onions and chili powder. Stir in rice. Turn into 11 x 7 baking dish.
1. In medium saucepan, combine water, tomato juice and bouillon. Cook, stirring until bouillon dissolves. Pour over meat mixture. Cover and bake 40 minutes at 350 degrees or until rice is tender.
1. Remove cover, top with cheese and bake 5 minutes longer.
So that's going to wrap this up for this instant food beef-rice-cheese casserole recipe. Thank you very much for your time. I am confident you will make this at home. There's gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
|
Python
|
UTF-8
| 237 | 2.59375 | 3 |
[] |
no_license
|
#making necessry imports
import requests
#Loop for 3 synchronous http calls
for n in range(0,3):
r=requests.get('https://webhook.site/#/10c68a23-5b6a-4f00-938a-a74d8d4a653a')
print(r.headers['date'])
|
JavaScript
|
UTF-8
| 783 | 3.15625 | 3 |
[] |
no_license
|
exports.convertDate = function(date){
let tgl = date.split(' ')
let newDateFormat = ''
if(tgl[1] == 'Jan')
newDateFormat = '01'
else if(tgl[1] == 'Feb')
newDateFormat = '02'
else if(tgl[1] == 'Mar')
newDateFormat = '03'
else if(tgl[1] == 'Apr')
newDateFormat = '04'
else if(tgl[1] == 'May')
newDateFormat = '05'
else if(tgl[1] == 'Jun')
newDateFormat = '06'
else if(tgl[1] == 'Jul')
newDateFormat = '07'
else if(tgl[1] == 'Aug')
newDateFormat = '08'
else if(tgl[1] == 'Sep')
newDateFormat = '09'
else if(tgl[1] == 'Oct')
newDateFormat = '10'
else if(tgl[1] == 'Nov')
newDateFormat = '11'
else if(tgl[1] == 'Dec')
newDateFormat = '12'
return `${tgl[2]}/${newDateFormat}/${tgl[3]} ${tgl[4]} ${tgl[0]}`
}
|
PHP
|
UTF-8
| 3,566 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use App\Http\Resources\NoteResource;
use App\Models\Note;
use http\Exception;
use Illuminate\Http\Request;
use Validator;
class NoteController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
$notes = Note::all();
return response()->json(NoteResource::collection($notes), 200);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
// 'title' => 'required|string|max:100',
// 'body' => 'required|string',
// 'picture' => '',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 400);
}
try {
$note = new Note();
$note->title = 'Nooo';
$note->body = 'BOOOODY';
$note->completed = true;
$note->save();
if ($request->has("picture")) {
if ($request->picture) {
$note->clearMediaCollection("picture");
$note->addMediaFromBase64($request->picture)->toMediaCollection("picture");
}
}
return response()->json(['data' => $note], 201);
} catch (\Exception $error) {
return response()->json($error, 400);
}
}
/**
* Display the specified resource.
*
* @param \App\Models\Note $note
* @return \Illuminate\Http\JsonResponse
*/
public function show($id)
{
$note = Note::find($id);
if ($note) {
return response()->json(new NoteResource($note), 200);
}
return response()->json(['data' => 'not found note'], 400);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Note $note
* @return \Illuminate\Http\JsonResponse
*/
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), [
'title' => 'required|string|max:100',
'body' => 'required|string',
'completed' => 'required|boolean',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 400);
}
$note = Note::find($id);
if ($note) {
try {
$note->title = $request->title;
$note->body = $request->body;
$note->completed = $request->completed;
$note->save();
return response()->json(['data' => $note], 200);
} catch (Exception $error) {
return response()->json(['error' => 'Bad Request'], 400);
}
}
return response()->json(['error' => 'Not found note'], 400);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Note $note
* @return \Illuminate\Http\JsonResponse
*/
public function destroy($id)
{
$note = Note::find($id);
if ($note) {
$note->delete();
return response()->json(['data' => 'deleted successfully'], 200);
}
return response()->json(['data' => 'not found note'], 400);
}
}
|
Shell
|
UTF-8
| 1,609 | 3.90625 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash -e
#
# Capture SOAP traffic between web client and vpxd on 127.0.0.1:8085.
#
# Caveats: tested with VCSA 6.0, unlikely to work for other versions.
#
set -e
cache_deb() {
wget $1
ar x *.deb data.tar.gz
tar zxf data.tar.gz
rm -f data.tar.gz
rm -f *.deb
}
dirname="$(dirname $0)"
basename="$(basename $0)"
bindir="${dirname}/.${basename}"
mkdir -p "${bindir}"
# Cache binaries required to run tcpdump on vcsa
if [ ! -f "${bindir}/.done" ]; then
pushd ${bindir}
cache_deb https://launchpadlibrarian.net/200649143/libssl0.9.8_0.9.8k-7ubuntu8.27_amd64.deb
cache_deb https://launchpadlibrarian.net/37430984/libpcap0.8_1.0.0-6_amd64.deb
cache_deb https://launchpadlibrarian.net/41774869/tcpdump_4.0.0-6ubuntu3_amd64.deb
touch .done
popd
fi
scp=(scp)
ssh=(ssh)
# Extract host from GOVC_URL
host="$(govc env -x GOVC_HOST)"
username=root
password="$(govc env GOVC_PASSWORD)"
if [ -x "$(which sshpass)" ] ; then
scp=(sshpass -p "$password" scp)
ssh=(sshpass -p "$password" ssh)
fi
ssh_opts=(-o UserKnownHostsFile=/dev/null
-o StrictHostKeyChecking=no
-o LogLevel=FATAL
-o User=${username}
-o ControlMaster=no)
dev="lo"
filter="port 8085"
tcpdump="env LD_LIBRARY_PATH=/tmp /tmp/tcpdump"
echo "Capturing $dev on $host..."
"${scp[@]}" "${ssh_opts[@]}" \
"${bindir}/lib/libcrypto.so.0.9.8" \
"${bindir}/usr/lib/libpcap.so.0.8" \
"${bindir}/usr/sbin/tcpdump" \
"${host}:/tmp"
"${ssh[@]}" "${ssh_opts[@]}" "$host" ${tcpdump} -i "$dev" -s0 -v -w - "$filter" | wireshark -k -i - 2>/dev/null
|
Java
|
UTF-8
| 5,352 | 2.640625 | 3 |
[] |
no_license
|
package ac.bali.serial;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.comm.CommPort;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;
public class NRSerialPort
{
private RXTXPort serial;
private String port = null;
private boolean connected = false;
private int baud = 115200;
/**
* Class Constructor for a NRSerialPort with a given port and baudrate.
*
* @param port the port to connect to (i.e. COM6 or /dev/ttyUSB0)
* @param baud the baudrate to use (i.e. 9600 or 115200)
*/
public NRSerialPort( String port, int baud )
{
setPort( port );
setBaud( baud );
}
public boolean connect()
{
if( isConnected() )
{
System.err.println( port + " is already connected." );
return true;
}
try
{
if( ( System.getProperty( "os.name" ).toLowerCase().contains( "linux" ) ) )
{
if( port.contains( "rfcomm" )
|| port.contains( "ttyUSB" )
|| port.contains( "ttyS" )
|| port.contains( "ACM" )
|| port.contains( "Neuron_Robotics" )
|| port.contains( "NR" )
|| port.contains( "FTDI" )
|| port.contains( "ftdi" ) )
{
System.setProperty( "ac.bali.serial.SerialPorts", port );
}
}
CommPortIdentifier ident = CommPortIdentifier.getPortIdentifier( port );
CommPort comm = ident.open( "NRSerialPort", 2000 );
if( !( comm instanceof RXTXPort ) )
{
throw new UnsupportedCommOperationException( "Non-serial connections are unsupported." );
}
serial = (RXTXPort) comm;
serial.enableReceiveTimeout( 100 );
serial.setSerialPortParams( getBaud(), SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE );
setConnected( true );
}
catch( PortInUseException e )
{
System.err.println( "This is a bug, passed the ownership test above: " + e.getMessage() );
return false;
}
catch( NativeResourceException e )
{
throw new NativeResourceException( e.getMessage() );
}
catch( Exception e )
{
System.err.println( "Failed to connect on port: " + port + " exception: " );
e.printStackTrace();
setConnected( false );
}
if( isConnected() )
{
serial.notifyOnDataAvailable( true );
}
return isConnected();
}
public InputStream getInputStream()
{
return serial.getInputStream();
}
public OutputStream getOutputStream()
{
return serial.getOutputStream();
}
/**
* Set the port to use (i.e. COM6 or /dev/ttyUSB0)
*
* @param port the serial port to use
*/
private void setPort( String port )
{
this.port = port;
}
public void disconnect()
{
try
{
try
{
getInputStream().close();
getOutputStream().close();
serial.close();
}
catch( Exception e )
{
e.printStackTrace();
throw new RuntimeException( e );
}
serial = null;
setConnected( false );
}
catch( UnsatisfiedLinkError e )
{
throw new NativeResourceException( e.getMessage() );
}
}
public static Set<String> getAvailableSerialPorts()
{
Set<String> available = new HashSet<String>();
try
{
RXTXCommDriver d = new RXTXCommDriver();
Set<String> av = d.getPortIdentifiers();
ArrayList<String> strs = new ArrayList<String>();
for( String s : av )
{
strs.add( 0, s );
}
for( String s : strs )
{
available.add( s );
}
}
catch( UnsatisfiedLinkError e )
{
e.printStackTrace();
throw new NativeResourceException( e.getMessage() );
}
return available;
}
public boolean isConnected()
{
return connected;
}
public void setConnected( boolean connected )
{
this.connected = connected;
}
public void setBaud( int baud )
{
switch( baud )
{
case 2400:
case 4800:
case 9600:
case 14400:
case 19200:
case 28800:
case 38400:
case 57600:
case 76800:
case 115200:
case 230400:
this.baud = baud;
return;
default:
throw new RuntimeException( "Invalid baudrate! " + baud );
}
}
public int getBaud()
{
return baud;
}
public void notifyOnDataAvailable( boolean b )
{
serial.notifyOnDataAvailable( b );
}
}
|
C#
|
UTF-8
| 3,489 | 2.734375 | 3 |
[] |
no_license
|
namespace Glean.Core.Columns
{
using System;
using System.Globalization;
using Glean.Core.Enumerations;
public class DateColumn : BaseColumn<DateTime?>
{
private const string DefaultOutputFormat = "yyyy-MM-dd";
private readonly string[] inputFormats;
private readonly DateTime? invalidDateValue;
public DateColumn(string columnName = null, string[] inputFormats = null,
string outputFormat = DefaultOutputFormat, DateTime? invalidDateValue = null)
: base(columnName)
{
this.invalidDateValue = invalidDateValue;
this.inputFormats = inputFormats ?? GetStandardDateFormats();
OutputFormat = outputFormat;
}
public string OutputFormat { get; }
public static string[] GetStandardDateFormats(StandardDateFormats format = StandardDateFormats.Default)
{
string[] formats = null;
switch (format)
{
case StandardDateFormats.Default:
case StandardDateFormats.Australia:
case StandardDateFormats.UnitedKingdom:
formats = new[]
{
"dd/MM/yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "ddMMyyyy", "dd/M/yy", "d/MM/yy", "d/M/yy",
"yyyy-MM-dd", "yyyy-M-d", "yyyy-MM-d", "yyyy-M-dd"
};
break;
case StandardDateFormats.UnitedStates:
formats = new[]
{
"MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy", "MMddyyyy", "M/dd/yy", "MM/d/yy", "M/d/yy",
"yyyy-MM-dd", "yyyy-M-d", "yyyy-MM-d", "yyyy-M-dd"
};
break;
}
return formats;
}
//[DebuggerHidden]
public static DateTime? ParseValue(string value, string[] validFormats, DateTime? invalidDateValue = null)
{
var result = invalidDateValue;
if (value != null)
{
var trimmedValue = value.TrimAndRemoveConsecutiveWhiteSpace();
if (trimmedValue.Length > 0)
{
DateTime temp;
if (DateTime.TryParseExact(trimmedValue, validFormats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, out temp))
{
result = temp;
}
else
{
throw new ParseException(value, typeof(DateTime));
}
}
}
return result;
}
public override DateTime? ParseValue(string value)
{
try
{
var parsedValue = PreParseValue(value);
return ParseValue(parsedValue, inputFormats);
}
catch (ParseException pe)
{
OnParseError(pe.ValueBeingParsed, typeof(DateTime), pe.Message);
return invalidDateValue;
}
}
public string ParseValueAndFormat(string value)
{
var dt = ParseValue(value);
string stringValue = null;
if (dt.HasValue)
{
stringValue = dt.Value.ToString(OutputFormat);
}
return stringValue;
}
}
}
|
Python
|
UTF-8
| 286 | 3.9375 | 4 |
[] |
no_license
|
#!/usr/bin/env python
from sum import *
print("Calling fortran with ints")
isum = sum_of_int(1,2)
print("Integer sum is: ", isum)
dsum = sum_of_double(1,2)
print("Double sum of ints is: ", dsum)
dsum = sum_of_double(0.5,2.5)
print("Double sum of doubles is: ", dsum)
print("Done")
|
Markdown
|
UTF-8
| 2,029 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
# Registration Control
Registration control introduces the concept of selective registration of services. Registration control can especially be useful in test projects where mock services are used. There are two ways to control service registration. A service attributed as live service does not get called when the application is running in Test mode. Services can also be explicitly filtered out.
## Source Files
### Program.cs
The ConfigureLogging method in program.cs configures logging. The default implementation uses log4net. Pass command line parameter seri to use serilog instead.
### Example.cs
The Run method creates an ApplicationContainerBuilder and initializes an Autofac lifetime scope and runs the service.
### ApplicationContainerBuilder.cs
Every AppBlocks.Autofac application must define a class that inherits from AppBlocksContainerBuilder. This inherited class is used to configure application Autofac services and other entities. In this example, ApplicationContainerBuilder specifies parameter AppBlocksApplicationMode.Test to the base constructor to indicate this application runs in test mode. It also filters out service with type name AppBlocks.Autofac.Examples.RegistrationControl.FilteredOutService.
### IService.cs
Defines the sample service interface with a single method Run
### Service.cs
Implementation for IService interface. Registered using AppBlocksService attribute.
### LiveService.cs
Implements IService interface. Throws an exception in Run method. The service is filtered out during registration since it is attributed with AppBlocksLiveService and the sample application is configured to run in Test mode. When application is run, no exception is thrown since this service is never registered.
### FilteredOutService.cs
Implements IService interface. Throws an exception in Run method. The service is filtered out by ShouldRegisterService method in ApplicationContainerBuilder. When application is run, no exception is thrown since this service is never registered.
|
Markdown
|
UTF-8
| 1,940 | 2.90625 | 3 |
[] |
no_license
|
# Password Generator
## Summary
An employee with access to sensitive data wanted a way to randomly generate passwords based on specific criteria. Starter code was given for an HTML and CSS style page, the javascript needed to run in a browswer was necessary to create this project.
<br>
<br>
## Site Picture

<br>
<br>
## What Was Done
<br>
<br>
## Code Snippet
```javascript
var passwordLength = prompt("How many characters would you like to use?")
if (passwordLength >= 8 && passwordLength <= 128) {
}
var upperCaseConfirm = confirm("Would you like to use Upper Case Letters?");
var lowerCaseConfirm = confirm("Would you like to use Lower Case Letters?");
var numbersConfirm = confirm("Would you like to use numbers?");
var specialCharactersConfirm = confirm("Would you like to use Special Characters?");
```
This code snippet from script.js set the prompts for the users to go through after they press generate password. The initial "passwordLength" carries the if statement
so users would have to choose between a minimum of 8 characters and a maximum of 128. The following variables were set as confirms which would help determine which
characters each user would need on a specific basis
<br>
<br>
## Built With
* [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML)
* [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS)
* [BootStrap](https://getbootstrap.com/)
<br>
<br>
## Deployed Link
[Live Link "Responsive Portfolio"](https://michaelanthonyyy.github.io/password-generator/)
<br>
## Authors
**Michael Medina**
- [Link to Github](https://github.com/michaelanthonyyy)
- [Link to LinkedIn](https://www.linkedin.com/in/michael-medina-22aa70200?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3B311BosSLTMS4JkhAfkX61A%3D%3D)
<br>
<br>
## Aknowledgements
The source code from this project was provided by the UC Berkeley Extension.
|
PHP
|
UTF-8
| 1,755 | 2.828125 | 3 |
[] |
no_license
|
<?php/*
session_start();
include("dbConnect.php");
$EmailId = $_SESSION['EmailId'];
$request = "select * from report where email_id = '$EmailId' ";
$details = mysqli_query($conn,$request);
$data="";
if (mysqli_num_rows($details) > 0) {
$data.="<table> <tr> <th> Table1 name </th><th> table2 name </th> <th>.....</th> <th>Table3 name</th> <th>Table4 name</th> </tr>";
while($row = mysqli_fetch_assoc($details)) {
$data.="<tr >";
$data.= "<td>".$row["tb1 name"]."</td> <td>".$row["tb2 name"]."</td> <td>". $row["tb3 name"]. "</td> <td>". $row["tb4 name"]. "</td> <td>". $row["tb5 name"]. "</td>";
$data.="</tr>";
}
$data.="</table>";
} else {
echo "0 results";
}*/
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{
font-family: Verdana;
color: rgb(33,38,115);
padding: 20px;
}
.heading{
display: block;
font-size: 30px;
margin-bottom: 60px;
margin-top: 10px;
}
th,td{
text-align: center;
padding: 20px;
border: thin solid white;
}
table{
background-color: rgb(225,237,255);
border-radius: 10px;
}
::-webkit-scrollbar{
width: 10px;
}
::-webkit-scrollbar-track{
background: rgb(225,237,255);
}
::-webkit-scrollbar-thumb{
background: rgb(134, 215, 255);
}
</style>
<title>Document</title>
</head>
<body>
<span class="heading">Reports</span>
<table>
</table>
<?/*php echo $data */?>
</body>
</html>
|
Python
|
UTF-8
| 619 | 2.546875 | 3 |
[] |
no_license
|
import QLS.AST.Widget.widget_interface as w
from QL.AST.Expressions.Types import *
class Radio(w.IWidget):
def __init__(self, option1, option2, default=""):
self.option1 = option1
self.option2 = option2
self.default = default
def string_presentation(self, level=0):
s = " " * level + "Radio "
s += "(" + self.option1 + ", " + self.option2 + ")\n"
return s
def get_compatible(self):
return [bool_type.Bool(), number_type.Number()]
def get_settings(self):
return self._properties
def widget_name(self):
return "radiobox"
|
Java
|
UTF-8
| 1,691 | 2.984375 | 3 |
[] |
no_license
|
package org.academiadecodigo.bootcamp.filipejorge.uberlisbondriver.cars;
import org.academiadecodigo.bootcamp.filipejorge.uberlisbondriver.cars.graphics.ColorUber;
import org.academiadecodigo.simplegraphics.graphics.Color;
/**
* Created by Filipe Jorge <Academia de Código_> on 02/02/16.
*/
public enum CarType {
UBERX(UberX.class, 10, ColorUber.VIVIDGREEN.getColor()),
UBERBLACK(UberBlack.class, 15, ColorUber.BLACK.getColor()),
UBERSPACE(UberSpace.class, 10, ColorUber.GREEN.getColor()),
TAXI(Taxi.class, 10, ColorUber.DARKGREEN.getColor());
private Class carClass;
private int maxSpeed;
private int width;
private int height;
private Color color;
CarType(Class carClass, int speed, Color color) {
this.carClass = carClass;
this.maxSpeed = speed;
this.width = 20;
this.height = 20;
this.color = color;
}
public static int getMaxSize() {
int size = 0;
for (CarType cartype : CarType.values()) {
if (size < cartype.width) {
size = cartype.width;
}
}
return size;
}
public static int getAllMaxSpeed() {
int speed = 0;
for (CarType cartype : CarType.values()) {
if (speed < cartype.maxSpeed) {
speed = cartype.maxSpeed;
}
}
return speed;
}
public Class getCarClass() {
return carClass;
}
public int getMaxSpeed() {
return maxSpeed;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Color getColor() {
return color;
}
}
|
Markdown
|
UTF-8
| 3,193 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
# Voucher Code Generator
Generate unique, random, and hard to guess coupon / voucher codes. Use cases: promo codes, loyalty coupons, gift vouchers, in-app purchases, referral links
### Installation
Just use go get.
```go
go get -u github.com/AmirSoleimani/VoucherCodeGenerator@v1.0.1
```
### Tested in the following Golang releases
All releases from Go1.13.x to Go1.18.x.
### How to use
```go
import (
...
"github.com/AmirSoleimani/VoucherCodeGenerator/vcgen"
)
func main() {
wg := sync.WaitGroup{}
wg.Add(3)
// normal
go func(wg *sync.WaitGroup) {
defer wg.Done()
vc, _ := vcgen.NewWithOptions(
vcgen.SetCount(10),
vcgen.SetPattern("###-###-###"),
vcgen.SetCharset("0123456789"),
)
result, err := vc.Run()
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
}(&wg)
// with prefix
go func(wg *sync.WaitGroup) {
defer wg.Done()
vc, _ := vcgen.NewWithOptions(
vcgen.SetCount(10),
vcgen.SetPattern("######"),
vcgen.SetPrefix("WELC-"),
)
result, err := vc.Run()
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
}(&wg)
// with prefix + suffix
go func(wg *sync.WaitGroup) {
defer wg.Done()
vc, _ := vcgen.NewWithOptions(
vcgen.SetCount(10),
vcgen.SetPattern("######"),
vcgen.SetPrefix("WELC-"),
vcgen.SetSuffix("-B"),
)
result, err := vc.Run()
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
}(&wg)
wg.Wait()
}
```
#### Options
```sh
SetLength(length uint16)
SetCount(count uint16)
SetCharset(charset string)
SetPrefix(prefix string)
SetSuffix(suffix string)
SetPattern(pattern string)
```
#### Prefix and Suffix
You can optionally surround each generated code with a prefix and/or suffix.
#### Pattern
Codes may follow a specified pattern. Use hash (`#`) as a placeholder for random characters.
#### Infeasible configs
There exist some configs that are not feasible. For example it's not possible to generate 1000 codes if you want
your codes to be 2 characters long and consisting only of numbers. Voucher code generator detects such cases and
throws an error `"Not possible to generate requested number of codes."`.
#### Config reference
| attribute | default value | description |
|------------------|:--------------:|---------------------------------------------------------------------------------|
| `length` | `6` | Number of characters in a generated code (excluding prefix and suffix) |
| `count` | `1` | Number of codes generated. |
| `charset` | `alphanumeric` | Characters that can appear in the code. |
| `prefix` | `""` | A text appended before the code. |
| `suffix` | `""` | A text appended after the code. |
| `pattern` | `"######"` | A pattern for codes where hashes (`#`) will be replaced with random characters. |
### License
Code released under the [MIT license](LICENSE).
|
Java
|
UTF-8
| 8,094 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
package bomberman;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Class containing all game map data.
* @author David Benes
*/
public class GameMap {
private final int xSize;
private final int ySize;
private final HashSet<Player> players;
private final HashSet<Bomb> bombs;
private final HashSet<Fire> fires;
private final HashSet<Bonus> bonuses;
private final HashSet<WoodenBox> woodenBoxes;
private final HashSet<IronBox> ironBoxes;
public GameMap(int xSize, int ySize) {
this.players = new HashSet<>();
this.bombs = new HashSet<>();
this.fires = new HashSet<>();
this.bonuses = new HashSet<>();
this.woodenBoxes = new HashSet<>();
this.ironBoxes = new HashSet<>();
this.xSize = xSize;
this.ySize = ySize;
}
/**
* Getter for objects on specified coordinates.
* @param x X coordinate.
* @param y Y coordinate.
* @return List of MapObjectTypes.
* @throws Exception
*/
public ArrayList<MapObjectType> getMapObjects(int x, int y) throws Exception {
ArrayList<MapObjectType> retval = new ArrayList<>();
for (WoodenBox woodenbox:woodenBoxes) {
if (woodenbox.getPos().getX()==x && woodenbox.getPos().getY()==y) retval.add(MapObjectType.WOODENBOX);
}
for (IronBox ironBox:ironBoxes) {
if (ironBox.getPos().getX()==x && ironBox.getPos().getY()==y) retval.add(MapObjectType.IRONBOX);
}
for (Bomb bomb:bombs) {
if (bomb.getPos().getX()==x && bomb.getPos().getY()==y) {
switch(bomb.getType()) {
case BASIC:
retval.add(MapObjectType.BOMBBASIC);
break;
case LARGE:
retval.add(MapObjectType.BOMBLARGE);
break;
}
}
}
for (Bonus bonus:bonuses) {
if (bonus.getPos().getX()==x && bonus.getPos().getY()==y) {
switch(bonus.getType()) {
case BOOTS:
retval.add(MapObjectType.BONUSBOOTS);
break;
case EXTRALIFE:
retval.add(MapObjectType.BONUSEXTRALIFE);
break;
case LARGEBOMB:
retval.add(MapObjectType.BONUSBOMBLARGE);
break;
}
}
}
for (Fire fire:fires) {
if (fire.getPos().getX()==x && fire.getPos().getY()==y) retval.add(MapObjectType.FIRE);
}
for (Player player:players) {
if (player.getPos().getX()==x && player.getPos().getY()==y) {
switch(player.getColor()) {
case BLUE:
switch(player.getDirection()) {
case UP:
retval.add(MapObjectType.PLAYERBLUEBACK);
break;
case DOWN:
retval.add(MapObjectType.PLAYERBLUEFRONT);
break;
case RIGHT:
retval.add(MapObjectType.PLAYERBLUERIGHT);
break;
case LEFT:
retval.add(MapObjectType.PLAYERBLUELEFT);
break;
}
break;
case GREEN:
switch(player.getDirection()) {
case UP:
retval.add(MapObjectType.PLAYERGREENBACK);
break;
case DOWN:
retval.add(MapObjectType.PLAYERGREENFRONT);
break;
case RIGHT:
retval.add(MapObjectType.PLAYERGREENRIGHT);
break;
case LEFT:
retval.add(MapObjectType.PLAYERGREENLEFT);
break;
}
break;
case RED:
switch(player.getDirection()) {
case UP:
retval.add(MapObjectType.PLAYERREDBACK);
break;
case DOWN:
retval.add(MapObjectType.PLAYERREDFRONT);
break;
case RIGHT:
retval.add(MapObjectType.PLAYERREDRIGHT);
break;
case LEFT:
retval.add(MapObjectType.PLAYERREDLEFT);
break;
}
break;
case WHITE:
switch(player.getDirection()) {
case UP:
retval.add(MapObjectType.PLAYERWHITEBACK);
break;
case DOWN:
retval.add(MapObjectType.PLAYERWHITEFRONT);
break;
case RIGHT:
retval.add(MapObjectType.PLAYERWHITERIGHT);
break;
case LEFT:
retval.add(MapObjectType.PLAYERWHITELEFT);
break;
}
break;
}
}
}
return retval;
}
/**
* Getter for player with specified ID number. Returns null if no such player exists.
* @param id ID number of a Player.
* @return Player with specified ID number.
*/
public Player getPlayerByID(int id) {
for (Player player:players) {
if (player.getID() == id) return player;
}
return null;
}
public int getXSize() {
return xSize;
}
public int getYSize() {
return ySize;
}
public HashSet<Player> getPlayers() {
return players;
}
public HashSet<Bomb> getBombs() {
return bombs;
}
public HashSet<Fire> getFires() {
return fires;
}
public HashSet<Bonus> getBonuses() {
return bonuses;
}
public HashSet<WoodenBox> getWoodenBoxes() {
return woodenBoxes;
}
public HashSet<IronBox> getIronBoxes() {
return ironBoxes;
}
public void addPlayer(int posX, int posY, PlayerColor color, Direction dir, int id, int lifes) {
this.players.add(new Player(posX, posY, color, dir, id, lifes));
}
public void addBomb(int posX, int posY, Player player) {
this.bombs.add(new Bomb(posX, posY, player));
}
public void addFire(int posX, int posY) {
this.fires.add(new Fire(posX, posY));
}
public void addBonus(int posX, int posY, BonusType type) {
this.bonuses.add(new Bonus(posX, posY, type));
}
public void addWoodenBox(int posX, int posY) {
this.woodenBoxes.add(new WoodenBox(posX, posY));
}
public void addIronBox(int posX, int posY) {
this.ironBoxes.add(new IronBox(posX, posY));
}
public void removeWoodenBox(WoodenBox woodenBox) {
this.woodenBoxes.remove(woodenBox);
}
public void removePlayer(Player player) {
this.players.remove(player);
}
public void removeBonus(Bonus bonus) {
this.bonuses.remove(bonus);
}
public void removeFire(Fire fire) {
this.fires.remove(fire);
}
public void removeBomb(Bomb bomb) {
this.bombs.remove(bomb);
}
}
|
C
|
UTF-8
| 986 | 3.6875 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int every_number[28123], sum_of_divisors[28123], abundant[28123]; // amiable numbers
int i, j; // for loops and number of primes
int sum = 0;
printf("Start\n");
for(i = 0; i < 28123; i = i+1)
{
every_number[i] = i;
sum_of_divisors[i] = 1;
for(j = 2; j < i; j = j+1)
{
if(i % j == 0)
sum_of_divisors[i] = sum_of_divisors[i] + j;
}
if(sum_of_divisors[i] > i)
abundant[i] = 1;
else
abundant[i] = 0;
}
for(i = 1; i < 28123; i = i+1)
{
if(abundant[i])
{
for(j = i; j < 28123; j = j+1)
{
if(abundant[j] && (i + j) < 28123)
every_number[i+j] = 0;
}
}
}
printf("Number\tAbundant?\tSum of Abundant?\n");
for(i = 1; i < 25; i=i+1)
{
printf("%d\t\t%d\t\t%d\n", i, abundant[i], every_number[i]);
}
for(i = 0; i < 28123; i=i+1)
{
sum = sum + every_number[i];
}
printf("Sum of numbers that can't be written as the sum of two abundant numbers: %d\n", sum);
return 0;
}
|
JavaScript
|
UTF-8
| 217 | 2.59375 | 3 |
[] |
no_license
|
process.stdin.on('data', function(chunk){
for(var i = 0 ; i < chunk.length; i ++){
//console.log(chunk[i]);
if(chunk[i] == 46){
chunk.write("!", i, 1);
}
}
console.log(chunk);
});
//process.stdin.resume();
|
Python
|
UTF-8
| 746 | 2.8125 | 3 |
[] |
no_license
|
from db import db
class RoleModel(db.Model):
__tablename__ = 'roles'
ROLES = ["admin", "user"]
# Atributos del Usuario
id = db.Column(db.Integer, primary_key=True)
role_type = db.Column(db.String(80), unique=True)
def __init__(self, role_type):
self.role_type = role_type
def json(self):
return {
'role_type': self.role_type
}
# Métodos definidos para el ORM SQLAlchemy
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
@classmethod
def find_by_role_type(cls, role_type):
return cls.query.filter_by(role_type=role_type).first()
|
C++
|
UTF-8
| 840 | 2.9375 | 3 |
[] |
no_license
|
//
// cScreen.hpp
// Frogger
//
// Created by Kristine Laranjo on 4/22/16.
// Copyright © 2016 Kristine Laranjo. All rights reserved.
//
// This will be my super class.
/*
When speaking about screens, I mean Menu screen, Config screen, Game screen, etc... Those screens you
find in every games.
The problem here is that each screen can be compared to a small SFML application :
Each screen will have its own events and will use some variables useless for other screens.
So, we need to separate each screen in order to avoid conflicts. With SFML, it's very simple to do that!
You just have to create a cScreen class which will represent each screen.
This is an virtual object and it's containing only one method:
*/
#pragma once
#ifndef C_SCREEN
#define C_SCREEN
class cScreen
{
public:
virtual int Run(sf::RenderWindow &App) = 0;
};
#endif
|
Java
|
UTF-8
| 2,747 | 3.546875 | 4 |
[] |
no_license
|
package year2019;
/*
题目描述
Z国的货币系统包含面值1元、4元、16元、64元共计4种硬币,以及面值1024元的纸币。现在小Y使用1024元的纸币购买了一件价
值为N (0 < N \le 1024)N(0<N≤1024)的商品,请问最少他会收到多少硬币?
输入描述:
一行,包含一个数N。
输出描述:
一行,包含一个数,表示最少收到的多少枚硬币。
输出结果应该是不唯一,因为 64 元可以换成16元和 4 元的硬币
姑且认为在能召开的情况下,返回最小个数
备注:
对于100%的数据,N (0 < N \le 1024)N(0<N≤1024)。
分析:
remain = 1024 - N
因为零钱存在着倍数关系,所以按照贪心算法,先计算能找的64元的个数;再按16元面值找。。。
累计所有的硬币个数
优化:
面值都是2的倍数;考虑使用位运算优化
为什么运行时间大,可能是因为加了一个函数,函数信息的保存本身也是占据信息的
考虑改成动态规划:
定义状态表示:dp[i] 0=<i<=remain 表示找 i 元钱,最少需要的硬币数
money[] = {1, 4, 16, 64}
状态转移方程:当前状态依赖于前一个状态
dp[i] = min(dp[i - money[k]] + 1, dp[i]);
结果存在 dp[num] 中
*/
import java.util.Scanner;
public class CashRemain {
private static int cashRemain(int remain) {
int cnt = 0;
// while (remain >= 64) {
// cnt ++;
// remain -= 64;
// }
// cnt += remain / 64;
// remain %= 64;
cnt += remain >> 6;
remain &= 63; // mod : a % (2^n) = a & (2^n - 1)
// remain %= 64;
// cnt += remain / 16;
cnt += remain >> 4;
remain &= 15;
// remain %= 16;
// cnt += remain / 4;
cnt += remain >> 2;
remain &= 3;
// remain %= 4;
// while (remain >= 16) {
// cnt ++;
// remain -= 16;
// }
//
// while (remain >= 4) {
// cnt ++;
// remain -= 4;
// }
return cnt + remain;
}
public static void main(String[] args) {
// int price = 200;
Scanner sc = new Scanner(System.in);
int price = sc.nextInt();
int remain = 1024 - price;
int cnt = 0;
cnt += remain >> 6;
remain &= ((1<<6)- 1); // mod : a % (2^n) = a & (2^n - 1)
// remain %= 64;
// cnt += remain / 16;
cnt += remain >> 4;
remain &= ((1<<4) - 1);
// remain %= 16;
// cnt += remain / 4;
cnt += remain >> 2;
remain &= ((1<<2) - 1);
System.out.println(cnt + remain);
// int x = 65;
// System.out.println(x >> 6);
// System.out.println(x);
}
}
|
Java
|
UTF-8
| 3,754 | 2.203125 | 2 |
[] |
no_license
|
package app.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.crawler.PageInfo;
import com.crawler.insurance.json.InsuranceJsonBean;
import com.microservice.dao.entity.crawler.insurance.basic.AreaCode;
import com.microservice.dao.entity.crawler.insurance.basic.TaskInsurance;
import app.commontracerlog.TracerLog;
import app.service.InsuranceTaskService;
@RestController
@RequestMapping("/insurance")
public class InsuranceTaskController {
public static final Logger log = LoggerFactory.getLogger(InsuranceTaskController.class);
@Autowired
private TracerLog tracer;
@Autowired
private InsuranceTaskService insuranceTaskService;
@PostMapping(path = "/check")
public TaskInsurance createTask(@RequestBody InsuranceJsonBean insuranceJsonBean){
tracer.addTag("InsuranceJsonBean =======>>",insuranceJsonBean.toString());
return insuranceTaskService.createTask(insuranceJsonBean);
}
@GetMapping(path="/tasks/{taskid}/status")
public TaskInsurance taskStatus(@PathVariable String taskid){
TaskInsurance taskInsurance = insuranceTaskService.getTaskInsurance(taskid);
tracer.addTag("Request task status", "taskid:"+taskid);
return taskInsurance;
}
/**
* @Description: 获取所有社保已开发完成的城市
*
* 0 :内测中 1:开发完成 2:维护中
* @return
*/
@GetMapping(path = "/citys")
public List<AreaCode> getCitys(){
tracer.addTag("getCitys ==>","start");
return insuranceTaskService.getCitys();
}
@PostMapping(path = "/tasks/getInsurancePages")
public @ResponseBody
PageInfo<TaskInsurance> getTaskInsurancePages(@RequestParam(value = "currentPage") int currentPage,
@RequestParam(value = "pageSize") int pageSize,
@RequestParam(value = "taskid", required = false) String taskid) {
//根据条件查询
Map<String, Object> paramMap = new HashMap();
paramMap.put("taskid",taskid);
// paramMap.put("idnum",idnum);
Page<TaskInsurance> tasksPage = insuranceTaskService.getTaskInsuranceTaskByParams(paramMap, currentPage, pageSize);
System.out.println("******getTaskPages:"+tasksPage);
PageInfo<TaskInsurance> pageInfo = new PageInfo<TaskInsurance>();
pageInfo.setContent(tasksPage.getContent());
pageInfo.setSize(tasksPage.getSize());
pageInfo.setTotalElements(tasksPage.getTotalElements());
pageInfo.setNumber(tasksPage.getNumber());
return pageInfo;
}
/**
* 根据创建时间统计社保的调用量(线性图表)
* @return
*/
@RequestMapping(value = "/tasks/lineData" , method = {RequestMethod.POST, RequestMethod.GET})
public @ResponseBody
List lineData(){
List result = insuranceTaskService.getInsuranceTaskStatistics();
return result;
}
/**
* 统计每个社保的调用量
* @return
*/
@RequestMapping(value = "/tasks/pieData" , method = {RequestMethod.POST, RequestMethod.GET})
public @ResponseBody
List pieData(){
List result = insuranceTaskService.getGroupByInsurance();
return result;
}
}
|
C++
|
UTF-8
| 737 | 2.765625 | 3 |
[] |
no_license
|
#ifndef SERVER_GAME_LEVELS_EXCEPTIONS_NOMORELEVELSEXCEPTION_H_
#define SERVER_GAME_LEVELS_EXCEPTIONS_NOMORELEVELSEXCEPTION_H_
#include <exception>
#include <string>
namespace server {
namespace game {
namespace levels {
namespace exceptions {
/**
* Excepcion que indica que no existen mas niveles.
* @author Gabriel Raineri
*/
class NoMoreLevelsException : public std::exception {
private:
const std::string details;
public:
NoMoreLevelsException(const std::string& details);
virtual ~NoMoreLevelsException() throw();
virtual const char* what() const throw();
};
}
}
}
}
#endif /*SERVER_GAME_LEVELS_EXCEPTIONS_NOMORELEVELSEXCEPTION_H_*/
|
Java
|
UTF-8
| 320 | 2.046875 | 2 |
[] |
no_license
|
package com.atguigu.bookstore.Test;
import java.sql.Connection;
import org.junit.Test;
import com.atguigu.bookstore.Utils.JDBCUtils;
public class TestJDBCUtils {
@Test
public void TestJDBC(){
Connection conn = JDBCUtils.getConnection();
System.out.println(conn);
JDBCUtils.closeConnection(conn);
}
}
|
PHP
|
UTF-8
| 2,619 | 2.8125 | 3 |
[] |
no_license
|
<?php
/**
* This file is part of the Small Neat Box Framework
* Copyright (c) 2011-2012 Small Neat Box Ltd.
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*/
namespace phpmailer\email;
use snb\email\EmailAbstract;
use snb\config\ConfigInterface;
/**
* An Email class that can be used in development builds
* It actually sends emails, but lets you override the to address
* and ignores any cc and bcc addresses, so your development
* build can capture all the emails to see what they look like
* without accidentally sending customers emails.
*/
class DevEmail extends PHPMailerEmail
{
protected $devEnable; // Allow emails to be sent at all?
protected $overrideTo; // Who to send all emails to
protected $overrideFrom; // Change all emails to be from this address...
/**
* Pulls various config settings out of the config to
* force emails to go to a particular destination.
* @param \snb\config\ConfigInterface $config
*/
public function __construct(ConfigInterface $config)
{
// normal construction
parent::__construct();
// Find the From address to use for all emails
$this->overrideFrom = $this->wrapEmailAddress(
$config->get('email.dev.from.email', ''),
$config->get('email.dev.from.name'));
// Find the To address to use for all emails
$this->overrideTo = $this->wrapEmailAddress(
$config->get('email.dev.to.email', ''),
$config->get('email.dev.to.name'));
// Find the on off switch for dev emails
$this->devEnable = $config->get('email.dev.enable', false);
// If there was not To address, switch off
if ($this->overrideTo['email'] == '') {
$this->devEnable = false;
}
}
/**
* @return bool|void
*/
public function send()
{
// If we have sending email switched off
// then pretend that everything worked just fine
if (!$this->devEnable) {
return true;
}
// cancel any addresses that had been set up
$this->to = array();
$this->from = array();
$this->replyTo = array();
$this->cc = array();
$this->bcc = array();
// Force the to address and from address to be what we want
$this->to($this->overrideTo['email'], $this->overrideTo['name']);
$this->from($this->overrideFrom['email'], $this->overrideFrom['name']);
// send the email
return parent::send();
}
}
|
Java
|
UTF-8
| 4,671 | 1.9375 | 2 |
[] |
no_license
|
package stayabode.foodyHive.models;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Orders implements Serializable {
String name;
String description;
String count;
String chefName;
String orderId;
String image;
String deliveredDate;
String amount;
int quantity;
String chefId;
String orderPrice;
String chefImage;
public String getChefImage() {
return chefImage;
}
public void setChefImage(String chefImage) {
this.chefImage = chefImage;
}
public String getChefId() {
return chefId;
}
public void setChefId(String chefId) {
this.chefId = chefId;
}
public String getOrderPrice() {
return orderPrice;
}
public void setOrderPrice(String orderPrice) {
this.orderPrice = orderPrice;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getChefName() {
return chefName;
}
public void setChefName(String chefName) {
this.chefName = chefName;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDeliveredDate() {
return deliveredDate;
}
public void setDeliveredDate(String deliveredDate) {
this.deliveredDate = deliveredDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
String orderDate;
String orderID;
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
List<FoodItem> foodItemList = new ArrayList<>();
public List<FoodItem> getSingleFoodItemList() {
return singleFoodItemList;
}
public void setSingleFoodItemList(List<FoodItem> singleFoodItemList) {
this.singleFoodItemList = singleFoodItemList;
}
List<FoodItem> singleFoodItemList = new ArrayList<>();
public List<FoodItem> getFoodItemList() {
return foodItemList;
}
public void setFoodItemList(List<FoodItem> foodItemList) {
this.foodItemList = foodItemList;
}
String id;
String orderNo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
public String getPreparationTime() {
return preparationTime;
}
public void setPreparationTime(String preparationTime) {
this.preparationTime = preparationTime;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getPaymentmethod() {
return paymentmethod;
}
public void setPaymentmethod(String paymentmethod) {
this.paymentmethod = paymentmethod;
}
public String getCancelledreason() {
return cancelledreason;
}
public void setCancelledreason(String cancelledreason) {
this.cancelledreason = cancelledreason;
}
public String getCreateddate() {
return createddate;
}
public void setCreateddate(String createddate) {
this.createddate = createddate;
}
String totalAmount;
String preparationTime;
String orderStatus;
String paymentmethod;
String cancelledreason;
String createddate;
}
|
Python
|
UTF-8
| 601 | 3.046875 | 3 |
[] |
no_license
|
# Реализуйте функцию mirror_matrix(), которая принимает двумерный список (матрицу)
# и изменяет его (по месту) таким образом, что правая половина матрицы
# становится зеркальной копией левой половины,
# симметричной относительно вертикальной оси матрицы.
# Если ширина матрицы — нечётная, то "средний" столбец не должен быть затронут.
|
Java
|
UTF-8
| 909 | 2 | 2 |
[
"Apache-2.0"
] |
permissive
|
package br.edu.utfpr.pb.trabalhofinalweb1.config;
import br.edu.utfpr.pb.trabalhofinalweb1.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableJpaAuditing
public class AdditionalResourceWebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploads/**").addResourceLocations("file:uploads/");
}
@Bean
public AuditorAware<User> auditorProvider() {
return new CrudAuditorAware();
}
}
|
C
|
UTF-8
| 1,956 | 3.890625 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define bool int
#define true 1
#define false 0
//é igual ao exercicio 19
typedef struct nodo{
int n;
struct nodo *next;
}nodo;
typedef struct fila{
nodo *first;
nodo *last;
} fila;
void listar(fila *f);
void pop(fila *f, int *c);
bool push(fila *f, int *c);
bool full(fila *f);
bool empty(fila *f);
void reset(fila *f);
int valores_impares(fila *f1);
int main(int argc, char const *argv[])
{
fila *f1 = (fila*) malloc (sizeof(fila));
int content, tamanho1,c;
tamanho1 = 5;//alterar aqui os tamanhos das filas
printf("---PREENCHA A FILA.---\n");
for(c =0;c<tamanho1;c++){
scanf("%d",&content);
push(f1,&content);
}
printf("--FILA--\n");
listar(f1);
content = valores_impares(f1);
printf("\nA fila possui %d elementos ímpares\n",content );
free(f1);
return 0;
}
void reset(fila *f){
f->first = NULL;
f->last = NULL;
}
bool empty(fila *f){
return f->first==NULL;
}
bool full(fila *f){
return false;
}
bool push(fila *f,int *c){
nodo *novo = (nodo*) malloc (sizeof(nodo));
if(novo==NULL){
printf("Erro de alocação.");
return false;
}
novo->n = *c;
novo->next = NULL;
if(f->last != NULL){
f->last->next=novo;
}
else{
f->first = novo;
}
f->last = novo;
return true;
}
void pop(fila *f, int *c){
nodo *nodo_aux;
if(f->first == NULL){
printf("--EMPTY STACK. CANNOT DELETE--\n");
return;
}
else{
nodo_aux = f->first;
*c = f->first->n;//recebe o conteudo do primeiro item da fila
f->first = f->first->next;
}
if(f->first == NULL){
f->last = NULL;
}
free(nodo_aux);
}
void listar(fila *f){
nodo *count;
if(f->first == NULL){
printf("FILA VAZIA");
return;
}
for(count = f->first;count!=NULL;count= count ->next){
printf(" %d ",count->n);
}
free(count);
}
int valores_impares(fila *f1){
int ret =0,aux;
while(!empty(f1)){
pop(f1,&aux);
if(aux%2==1){//impar
ret++;
}
}
return ret;
}
|
TypeScript
|
UTF-8
| 1,251 | 3.640625 | 4 |
[
"MIT"
] |
permissive
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @ignore
*/
function P0 (t: number, p: number): number
{
const k = 1 - t;
return k * k * k * p;
}
/**
* @ignore
*/
function P1 (t: number, p: number): number
{
const k = 1 - t;
return 3 * k * k * t * p;
}
/**
* @ignore
*/
function P2 (t: number, p: number): number
{
return 3 * (1 - t) * t * t * p;
}
/**
* @ignore
*/
function P3 (t: number, p: number): number
{
return t * t * t * p;
}
/**
* A cubic bezier interpolation method.
*
* https://medium.com/@adrian_cooney/bezier-interpolation-13b68563313a
*
* @function Phaser.Math.Interpolation.CubicBezier
* @since 3.0.0
*
* @param {number} t - The percentage of interpolation, between 0 and 1.
* @param {number} p0 - The start point.
* @param {number} p1 - The first control point.
* @param {number} p2 - The second control point.
* @param {number} p3 - The end point.
*
* @return {number} The interpolated value.
*/
export function CubicBezierInterpolation (t: number, p0: number, p1: number, p2: number, p3: number): number
{
return P0(t, p0) + P1(t, p1) + P2(t, p2) + P3(t, p3);
}
|
Java
|
UTF-8
| 569 | 1.65625 | 2 |
[] |
no_license
|
package com.zhang.upms.rpc.api;
import com.zhangle.common.base.BaseService;
import com.zhang.upms.dao.model.UpmsUserOrganization;
import com.zhang.upms.dao.model.UpmsUserOrganizationExample;
/**
* UpmsUserOrganizationService接口
* Created by shuzheng on 2017/12/17.
*/
public interface UpmsUserOrganizationService extends BaseService<UpmsUserOrganization, UpmsUserOrganizationExample> {
/**
* 用户组织
* @param organizationIds 组织ids
* @param id 用户id
* @return
*/
int organization(String[] organizationIds, int id);
}
|
Markdown
|
UTF-8
| 1,213 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
## http.zlib
An abstraction layer over the various lua zlib libraries.
### `engine` <!-- --> {#http.zlib.engine}
Currently either [`"lua-zlib"`](https://github.com/brimworks/lua-zlib) or [`"lzlib"`](https://github.com/LuaDist/lzlib)
### `inflate()` <!-- --> {#http.zlib.inflate}
Returns a closure that inflates (uncompresses) a zlib stream.
The closure takes a string of compressed data and an end of stream flag (`boolean`) as parameters and returns the inflated output as a string. The function will throw an error if the input is not a valid zlib stream.
### `deflate()` <!-- --> {#http.zlib.deflate}
Returns a closure that deflates (compresses) a zlib stream.
The closure takes a string of uncompressed data and an end of stream flag (`boolean`) as parameters and returns the deflated output as a string.
### Example {#http.zlib-example}
```lua
local zlib = require "http.zlib"
local original = "the racecar raced around the racecar track"
local deflater = zlib.deflate()
local compressed = deflater(original, true)
print(#original, #compressed) -- compressed should be smaller
local inflater = zlib.inflate()
local uncompressed = inflater(compressed, true)
assert(original == uncompressed)
```
|
Markdown
|
UTF-8
| 596 | 2.671875 | 3 |
[] |
no_license
|
# 7 States you can have with other characters, as well as governments
The higher your state with someone / an entity the more information you have about their characteristics and respective states with other characters / governments.
The player's own
1. Enemy
- You know nothing and get attacked on sight
2. Distrusted
- You can see state affiliations that are ally or higher
3. Neutral
- You can see all affiliations that are ally or higher
4. Trusted
- You can see all affiliations that are trusted or higher
5. Ally
- You can see characteristics
6. Lover / Leader
- You can see
|
Markdown
|
UTF-8
| 10,708 | 3.125 | 3 |
[] |
no_license
|
# 设计文档
[TOC]
## 需求
设计一个扣费服务管理的后台系统,需要具备功能:
- 查看扣费服务列表
- 开通扣费服务
- 关闭扣费服务
原型参考微信支付扣费服务。
## 模型设计
### 总体思路
将商户与用户对扣费服务的约定抽象为**代扣协议(Contract)**。
同一商户对不同用户提供的扣费服务通常具有相同的属性,为了方便审核/管理/风控,抽象出**代扣方案(Plan)**,包括扣费用途、扣费限额等。
商户需要先向平台报备**代扣方案**,经过审批后,基于代扣方案补充签约周期等属性派生**代扣协议**,与用户签约代扣协议。
协议过期、解约、吊销后即失效,商户可以凭有效代扣协议发起扣费。
### 关系拓扑
```mermaid
erDiagram
Merchant ||--o{ Plan : provides
Plan ||--o{ Contract : instantiates
Merchant ||--o{ App : has
App ||--o{ Contract : binds
Merchant ||--o{ Contract : admits
User ||--o{ Contract : admits
```
### 代扣方案
Demo未展开设计代扣方案模型,只要求必需属性:
| 属性名称 | 类型 | 描述 | 示例 |
| --------- | ------ | ------------ | ---------------------------- |
| mch_id | uint64 | 商户ID | 10590 |
| plan_id | uint64 | 代扣方案ID | 808 |
| plan_name | string | 代扣方案名称 | 腾讯视频会员连续包月 |
| plan_desc | string | 代扣方案描述 | 每月自动续费腾讯视频会员业务 |
### 代扣协议
**商户**与**用户**按**代扣方案**完成签约,因此**代扣方案**需要关联**用户ID**、**商户ID**、**代扣方案ID**。
相同的商户、用户,针对同一个代扣方案只能有一个有效代扣协议,可以解约后再签,或同时签约不同代扣方案的协议。
签约通常在商户的一个应用发起(公众号、小程序、H5等),因此需要关联**签约来源应用ID**,方便统计、回调等。
加入代扣协议本身的属性后,完整属性如下:
| 属性名称 | 类型 | 描述 | 示例 |
| -------------- | ------ | ---------- | ---------------- |
| user_id | uint64 | 用户ID | 10086 |
| mch_id | uint64 | 商户ID | 10590 |
| app_id | uint64 | 签约来源应用ID | 707 |
| plan_id | uint64 | 代扣方案ID | 808 |
| contract_id | uint64 | 代扣协议ID,自动生成,全局唯一 | 518060 |
| contract_code | string | 商户侧生成的代扣协议号,同商户唯一 | RP20210809220243 |
| contract_state | enum | 协议状态,详见下表 | Valid(1) |
| display_account | string | 开通账户名称,用于签约时展示 | QQ用户(10001) |
| signed_time | string | 协议签约时间,UMT+8 | 2021-08-09 22:17:05 |
| expired_time | string | 协议过期时间,UMT+8 | 2021-08-09 22:17:34 |
| terminated_time | string | 协议解除时间,UMT+8 | 2021-08-09 22:18:21 |
代扣协议状态枚举值:
| 值 | 名称 | 描述 |
| ---- | ------------------ | ---------------- |
| 0 | Pending | 待签约/签约中 |
| 1 | Valid | 有效签约 |
| 2 | Expired | 签约过期 |
| 3 | Revoked | 签约已被平台吊销 |
| 4 | UserTerminated | 用户终止签约 |
| 5 | MerchantTerminated | 商户终止签约 |
Protobuf描述:
```protobuf
// 代扣协议
message ContractInfo {
uint64 user_id = 1; // 用户ID
uint64 mch_id = 2; // 商户ID
string mch_name = 3; // 商户名称
uint64 app_id = 4; // 应用ID
string app_name = 5; // 应用名称
uint64 contract_id = 6; // 协议ID
string contract_code = 7; // 商户协议号
ContractState contract_state = 8; // 协议状态
uint64 plan_id = 9; // 代扣方案ID
string plan_name = 10; // 代扣方案名称
string plan_desc = 11; // 代扣方案描述
string display_account = 12; // 开通账户名称
string signed_time = 13; // 协议签署时间
string expired_time = 14; // 协议到期时间
string terminated_time = 15; // 协议解约时间
}
// 代扣协议状态
enum ContractState {
Pending = 0; // 签约中
Valid = 1; // 有效签约
Expired = 2; // 签约过期
Revoked = 3; // 已被吊销
UserTerminated = 4; // 用户终止签约
MerchantTerminated = 5; // 商户终止签约
}
```
### 用户、商户、应用
这三项模型不在扣费服务设计范围内,从简设计:
用户属性:
| 属性名称 | 类型 | 描述 | 示例 |
| --------- | ------ | -------- | ------- |
| user_id | uint64 | 用户ID | 10086 |
| user_name | string | 用户昵称 | Tencent |
商户属性:
| 属性名称 | 类型 | 描述 | 示例 |
| -------- | ------ | -------- | -------- |
| mch_id | uint64 | 商户ID | 10590 |
| mch_name | string | 商户名称 | 腾讯视频 |
应用属性:
| 属性名称 | 类型 | 描述 | 示例 |
| -------- | ------ | -------- | ----------- |
| app_id | uint64 | 应用ID | 707 |
| app_name | string | 应用名称 | 腾讯视频App |
## 接口设计
### 签约流程
```mermaid
sequenceDiagram
participant 商户
participant 用户
participant 平台
autonumber
商户->>+平台: 配置扣费方案
平台-->>-商户: 返回扣费方案ID
商户->>+平台: 准备代扣协议
平台-->>-商户: 返回预签约代码
商户->>用户: 使用预签约代码调用客户端签约API
用户->>+平台: 核对协议并签名确认
平台-->>用户: 签约完成
平台-->>-商户: 签约结果回调
```
### 商户端接口
#### 准备扣费协议
商户指定代扣方案生成一份待签约的代扣协议,获取预签约代码`contract_token`。
请求方法:`PrepareContract`
请求参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| mch_id | uint64 | 商户ID |
| app_id | uint64 | 应用ID |
| plan_id | uint64 | 代扣方案ID |
| contract_code | string | 商户协议号 |
| display_account | string | 开通账户名称 |
| callback_url | string | 签约结果回调URl |
| signature | string | 商户签名 |
响应参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| err_code | int32 | 错误码,请求成功时为0 |
| err_msg | string | 错误提示,错误码非0时才有意义 |
| contract_token | string | 预签约代码 |
| expired_time | string | 签约时限 |
#### 终止扣费协议
由商户侧发起代扣协议的解约,需要商户签名。
请求方法:`TerminateContract`
请求参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| contract_id | uint64 | 协议ID |
| mch_id | uint64 | 商户ID |
| signature | string | 签名 |
响应参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| err_code | int32 | 错误码,请求成功时为0 |
| err_msg | string | 错误提示,错误码非0时才有意义 |
### 客户端接口
#### 签约扣费协议
用户确认签约商家生成的扣费协议,需要用户签名。
请求方法:`SignContract`
请求参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| user_id | uint64 | 用户ID |
| contract_token | string | 待签约协议token |
| signature | string | 用户签名 |
响应参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| err_code | int32 | 错误码,请求成功时为0 |
| err_msg | string | 错误提示,错误码非0时才有意义 |
#### 终止扣费协议
由用户侧发起代扣协议的解约,需要用户签名。
请求方法:`TerminateContract`
请求参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| contract_id | uint64 | 协议ID |
| user_id | uint64 | 用户ID |
| signature | string | 签名 |
响应参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| err_code | int32 | 错误码,请求成功时为0 |
| err_msg | string | 错误提示,错误码非0时才有意义 |
#### 查看扣费服务列表
获取当前用户的代扣协议列表,只返回状态为`有效(Valid)`的协议。
请求方法:`GetUserContractList`
请求参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| user_id | uint64 | 用户ID |
| limit | uint32 | (分页)每页条数 |
| offset | uint32 | (分页)偏移数量 |
响应参数:
| 参数名称 | 类型 | 描述 |
| --- | --- | --- |
| err_code | int32 | 错误码,请求成功时为0 |
| err_msg | string | 错误提示,错误码非0时才有意义 |
| total | uint32 | 总数 |
| limit | uint32 | (分页)每页条数 |
| offset | uint32 | (分页)偏移数量 |
| contract_list | ContractInfo[] | 协议列表 |
## 数据安全
### 传输安全
#### 传输加密
接口请求过程必须加密,以防中间人攻击(泄漏、篡改)。
我们假设客户端已经获取到了服务器的RSA公钥(通过证书验证或者直接写死在客户端),客户端需要先与服务器建立“会话”:
1. 客户端生成足够长的随机字符串,作为会话秘钥;
2. 客户端使用服务器公钥加密会话秘钥,并发送给服务端;
3. 服务端响应确认会话秘钥,并给出会话ID。
随后,客户端的每次请求都应带上会话ID,并使用会话秘钥对请求体进行AES加密,再发送到服务器。服务器的响应也是会话秘钥AES加密后的数据,客户端需要解密后使用。这样避免了第三方读取请求、响应内容。
如果接口采用HTTP协议,则可直接强制使用HTTPS,做好服务器证书的验证即可。
#### 防重放攻击
请求中需要带上**请求时间戳**和**请求序列号**,约定X小时内请求序列号不得重复,服务端缓存X小时内的请求序列号,丢弃重复请求,以防重放攻击。
### 存储安全
Demo采用MySQL数据库进行存储,除了运维角度进行权限控制外,明文存储的`contract_code`、`display_account`等字段也可使用AES加密后进行存储,但需要考虑性能开销、检索场景。
### 隐私保护
Demo简化设计中,各实体的ID字段均为`uint64`类型。
如果递增生成,有遍历风险,可以将**商户ID**、**APP ID**、**扣费计划ID**、**用户ID**设计为随机生成的唯一标识,使其不具备规律性。
不同商户的用户ID相同,可能被非法建立关联,泄漏用户隐私。可以参考微信`open_id`设计,为每个商户、应用分配`open_id秘钥`,对用户ID进行AES加密,永远对商户、应用侧提供用户ID的加密值,保证无法被关联分析。
|
Markdown
|
UTF-8
| 14,769 | 2.765625 | 3 |
[] |
no_license
|
# Service层接口说明文档
- 更新时间:2019/09/20
[TOC]
# 简介
欢迎使用CAS统一认证平台。
本文档主要描述CAS统一认证平台的Service层相关技术内容。
## 请求格式
- **请求格式为http://{ip}:{port}/{path}**
| 参数 | 说明 |
| ---- | ------------------------- |
| ip | Service程序运行的服务器IP |
| port | Service程序运行的端口 |
| path | Service调用路径 |
## 文档阅读说明
ip是指服务器地址,port是指端口号。
在文档中,ip是127.0.0.1,port是8051。
# clients基本参数表
| 字段 | 类型 | 说明 |
| ------------ | ------- | ----------------------------------------------------------- |
| client_id | String | 应用客户端id |
| name | String | 系统名称 |
| secret | String | 密钥 |
| token | String | 令牌,用于验证client是否合法,内部系统颁发的token属于永久性 |
| isInternal | Boolean | 是否为内部系统 client |
| created_time | String | 创建时间 |
# id_tokens基本参数表
| 字段 | 类型 | 说明 |
| -------------------- | ------ | ------------------------------------------------- |
| value | String | id_token的值 |
| client_id | String | 应用客户端id |
| account_id | String | 用户id |
| expired_time | String | 过期时间 |
| refresh_token | String | 由统一认证中心颁发的刷新令牌,更新id_token(value) |
| refresh_expired_time | String | 更新token的refresh_token的过期时间 |
# id_token
## 1.查找id_token
### 接口描述
查找一条id_token数据
### 请求说明
- HTTP方法:**POST**
- Path:``auth/id_token/find``
- URL示例:``http://localhost:8051/auth/id_token/find``
- 请求参数说明:
| 参数 | 类型 | 是否必选 | 说明 |
| -------------------- | ------ | -------- | -------------------------- |
| _id | String | 否 | 这条数据的_id值 |
| client_id | String | 否 | client的id值 |
| account_id | String | 否 | id_token对应的account的_id |
| refresh_expired_time | String | 否 | 刷新过期的时间 |
| refresh_token | String | 否 | 用来刷新的标志token |
| expired_time | String | 否 | 过期时间 |
| value | String | 否 | id_token的值 |
- 请求示例:
```json
//查找client_id和refresh_token都为3的数据
{
"client_id": "3",
"refresh_token":"3"
}
```
### 返回说明
- 返回成功说明:
| 参数 | 类型 | 说明 |
| -------------------- | ------ | -------------------------- |
| _id | String | 这条数据的_id值 |
| client_id | String | client的id值 |
| account_id | String | id_token对应的account的_id |
| refresh_expired_time | String | 刷新过期的时间 |
| refresh_token | String | 用来刷新的标志token |
| expired_time | String | 过期时间 |
| value | String | id_token的值 |
| _v | Number | 系统自动生成不影响 |
- 返回示例:
```json
{
"_id": "5d774a70e490b49508be1ce9",
"client_id": "3",
"account_id": "5d25a9fb3d99198801f13028",
"refresh_expired_time": "6",
"refresh_token": "3",
"expired_time": "2019-09-11 16:02:08",
"value": "3",
"__v": 0
}
```
## 2.增加id_token
### 接口描述
增加一条id_token数据
### 请求说明
- HTTP方法:**POST**
- Path:``auth/id_token/add``
- URL示例:``http://localhost:8051/auth/id_token/add``
- 请求参数说明:
| 参数 | 类型 | 是否必选 | 说明 |
| -------------------- | ------ | -------- | -------------------------- |
| client_id | String | 是 | client的id值 |
| account_id | String | 否 | id_token对应的account的_id |
| refresh_expired_time | String | 是 | 刷新过期的时间 |
| refresh_token | String | 是 | 用来刷新的标志token |
| expired_time | String | 是 | 过期时间 |
| value | String | 是 | id_token的值 |
- 请求示例:
```json
{
"client_id": "3",
"account_id": "5d25a9fb3d99198801f13028",
"refresh_expired_time": "6",
"refresh_token": "3",
"expired_time": "2019-09-11 16:02:08",
"value": "3"
}
```
### 返回说明
- 返回成功说明:
| 参数 | 类型 | 说明 |
| -------------------- | ------ | -------------------------- |
| _id | String | 这条数据的_id值 |
| client_id | String | client的id值 |
| account_id | String | id_token对应的account的_id |
| refresh_expired_time | String | 刷新过期的时间 |
| refresh_token | String | 用来刷新的标志token |
| expired_time | String | 过期时间 |
| value | String | id_token的值 |
| _v | Number | 系统自动生成不影响 |
- 返回示例:
```json
{
"_id": "5d789f19eb49ce45a4f1d1ba",
"client_id": "3",
"account_id": "5d25a9fb3d99198801f13028",
"refresh_expired_time": "6",
"refresh_token": "3",
"expired_time": "2019-09-11 16:02:08",
"value": "3",
"__v": 0
}
```
## 3.修改id_token
### 接口描述
修改一条id_token数据
### 请求说明
- HTTP方法:**PUT**
- Path:``auth/id_token/update``
- URL示例:``http://localhost:8051/auth/id_token/update``
- 请求参数说明:
| 对象名 | 参数 | 类型 | 是否必选 | 说明 |
| ------ | -------------------- | ------ | -------- | -------------------------- |
| filter | | Object | 是 | 需要修改的数据的筛选条件 |
| params | | Object | 是 | 需要修改数据的值 |
| | client_id | String | 否 | client的id值 |
| | account_id | String | 否 | id_token对应的account的_id |
| | refresh_expired_time | String | 否 | 刷新过期的时间 |
| | refresh_token | String | 否 | 用来刷新的标志token |
| | expired_time | String | 否 | 过期时间 |
| | value | String | 否 | id_token的值 |
- 请求示例:
```json
//将client_id为123的这条数据的value值修改为qwe
{
"filter":{
"client_id":"123"
},
"params":{
"value":"qwe"
}
}
```
### 返回说明
- 返回参数说明:
| 参数 | 类型 | 说明 |
| --------- | ------ | -------------------- |
| n | Number | 符合查询结果的条目数 |
| nModified | Number | 修改的条目数 |
| ok | Number | 修改成功的数量 |
- 返回示例:
```json
//成功修改一条数据
{
"n": 1,
"nModified": 1,
"ok": 1
}
```
## 4.删除id_token
### 接口描述
删除一条id_token数据
### 请求说明
- HTTP方法:**DELETE**
- Path:``auth/id_token/delete/:_id``
- URL示例:``http://localhost:8051/auth/id_token/delete/5d789171c37bcc2ab4475203``
### 返回说明
- 返回参数说明:
| 参数 | 类型 | 说明 |
| ------------ | ------ | -------------------- |
| n | Number | 符合查询结果的条目数 |
| ok | Number | 删除成功的数量 |
| deletedCount | Number | 删除的条目数 |
- 返回示例:
```json
//成功删除一条数据
{
"n": 1,
"ok": 1,
"deletedCount": 1
}
```
# client_token
## 1.查找client_token
### 接口描述
查找一条client_token数据
### 请求说明
- HTTP方法:**POST**
- Path:``auth/client_token/find``
- URL示例:``http://localhost:8051/auth/client_token/find``
- 请求参数说明:
| 参数 | 类型 | 是否必选 | 说明 |
| ------------ | ------ | -------- | --------------- |
| _id | String | 否 | 这条数据的_id值 |
| name | String | 否 | client的名字 |
| client_id | String | 否 | client的id值 |
| secret | String | 否 | client的加密值 |
| token | String | 否 | client的token |
| isInternal | String | 否 | 是否为内部系统 |
| created_time | String | 否 | 创建时间 |
- 请求示例:
```json
//查找client_id为3的数据
{
"client_id": "3"
}
```
### 返回说明
- 返回成功说明:
| 参数 | 类型 | 说明 |
| ------------ | ------ | ------------------ |
| _id | String | 这条数据的_id值 |
| name | String | client的名字 |
| client_id | String | client的id值 |
| secret | String | client的加密值 |
| token | String | client的token |
| isInternal | String | 是否为内部系统 |
| created_time | String | 创建时间 |
| __v | Number | 系统自动生成不影响 |
- 返回示例:
```json
{
"_id": "5d72233234ff68421811dd70",
"name": "手机",
"client_id": "12333",
"secret": "123456",
"token": "10000",
"isInternal": true,
"created_time": "2099",
"__v": 0
}
```
## 2.增加client_token
### 接口描述
增加一条client_token数据
### 请求说明
- HTTP方法:**POST**
- Path:``auth/client_token/add``
- URL示例:``http://localhost:8051/auth/client_token/add``
- 请求参数说明:
| 参数 | 类型 | 是否必选 | 说明 |
| ---------- | ------ | -------- | ------------------ |
| name | String | 是 | client的名字 |
| client_id | String | 是 | client的id值 |
| secret | String | 是 | 验证client的加密值 |
| token | String | 是 | client的token |
| isInternal | String | 是 | 是否为内部系统 |
- 请求示例:
```json
{
"name": "123123",
"client_id": "123313",
"secret": "123456",
"token": "10000",
"isInternal": true
}
```
### 返回说明
- 返回成功说明:
| 参数 | 类型 | 说明 |
| ------------ | ------ | ------------------ |
| _id | String | 这条数据的_id值 |
| name | String | client的名字 |
| client_id | String | client的id值 |
| secret | String | client的加密值 |
| token | String | client的token |
| isInternal | String | 是否为内部系统 |
| created_time | String | 创建时间 |
| __v | Number | 系统自动生成不影响 |
- 返回示例:
```json
{
"_id": "5d78a623a2dffa55f48b106f",
"name": "123123",
"client_id": "123313",
"secret": "123456",
"token": "10000",
"isInternal": true,
"created_time": "2019-09-11 15:45:39",
"__v": 0
}
```
## 3.修改client_token
### 接口描述
修改一条client_token数据
### 请求说明
- HTTP方法:**PUT**
- Path:``auth/client_token/update``
- URL示例:``http://localhost:8051/auth/client_token/update``
- 请求参数说明:
| 对象名 | 参数 | 类型 | 是否必选 | 说明 |
| ------ | ------------ | ------ | -------- | ------------------------ |
| filter | | Object | 是 | 需要修改的数据的筛选条件 |
| params | | Object | 是 | 需要修改数据的值 |
| | client_id | String | 否 | client的id值 |
| | name | String | 否 | client的name |
| | secret | String | 否 | 验证client的值 |
| | token | String | 否 | client的token |
| | isInternal | String | 否 | 过期时间 |
| | created_time | String | 否 | 创建时间 |
- 请求示例:
```json
//将name为123123的这条数据的name值修改为123123123
{
"filter":{
"name":"123123"
},
"params":{
"name": "123123123"
}
}
```
### 返回说明
- 返回参数说明:
| 参数 | 类型 | 说明 |
| --------- | ------ | -------------------- |
| n | Number | 符合查询结果的条目数 |
| nModified | Number | 修改的条目数 |
| ok | Number | 修改成功的数量 |
- 返回示例:
```json
//成功修改一条数据
{
"n": 1,
"nModified": 1,
"ok": 1
}
```
## 4.删除client_token
### 接口描述
删除一条client_token数据
### 请求说明
- HTTP方法:**DELETE**
- Path:``auth/client_token/delete/:_id``
- URL示例:``http://localhost:8051/auth/client_token/delete/5d789171c37bcc2ab4475203``
### 返回说明
- 返回参数说明:
| 参数 | 类型 | 说明 |
| ------------ | ------ | -------------------- |
| n | Number | 符合查询结果的条目数 |
| ok | Number | 删除成功的数量 |
| deletedCount | Number | 删除的条目数 |
- 返回示例:
```json
//成功删除一条数据
{
"n": 1,
"ok": 1,
"deletedCount": 1
}
```
|
Swift
|
UTF-8
| 3,505 | 2.8125 | 3 |
[] |
no_license
|
//
// Execute1.swift
// TestCoreData
//
// Created by Sergey Garazha on 8/1/18.
//
import CoreData
class Test1 {
let q1 = DispatchQueue(label: "com.test.db1", qos: DispatchQoS.default)
let q2 = DispatchQueue(label: "com.test.db2", qos: DispatchQoS.default)
let applicationDocumentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var store1: NSPersistentStore?
var store2: NSPersistentStore?
lazy var coordinator1: NSPersistentStoreCoordinator = {
let model = NSManagedObjectModel.mergedModel(from: nil)!
let coordinator1 = NSPersistentStoreCoordinator(managedObjectModel: model)
let url1 = self.applicationDocumentsDirectory.appendingPathComponent("Yo1.sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
store1 = try! coordinator1.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url1, options: options)
return coordinator1
}()
lazy var coordinator2: NSPersistentStoreCoordinator = {
let model = NSManagedObjectModel.mergedModel(from: nil)!
let coordinator2 = NSPersistentStoreCoordinator(managedObjectModel: model)
let url2 = self.applicationDocumentsDirectory.appendingPathComponent("Yo2.sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
store2 = try! coordinator2.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url2, options: options)
return coordinator2
}()
var mocPrivate1: NSManagedObjectContext {
let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator1
return managedObjectContext
}
var mocPrivate2: NSManagedObjectContext {
let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator2
return managedObjectContext
}
func start() -> Bool {
for _ in 1...10 {
if !execute() {
return false
}
}
return true
}
func execute() -> Bool {
var res1 = false
var res2 = false
q1.sync {
let ctx = mocPrivate1
let entity = NSEntityDescription.entity(forEntityName: "Yo", in: ctx)!
let y = NSManagedObject(entity: entity, insertInto: ctx) as! Yo
y.yo = "yo1 db"
do {
try ctx.save()
res1 = true
} catch {
let nserror = error as NSError
print("\(nserror)\n\n\(nserror.userInfo)")
res1 = false
}
}
q2.sync {
let ctx = mocPrivate2
let entity2 = NSEntityDescription.entity(forEntityName: "Yo", in: ctx)!
let y2 = NSManagedObject(entity: entity2, insertInto: ctx) as! Yo
y2.yo = "yo2 db"
do {
try ctx.save()
res2 = true
} catch {
let nserror = error as NSError
print("\(nserror)\n\n\(nserror.userInfo)")
res2 = false
}
}
return res1 && res2
}
}
|
PHP
|
UTF-8
| 5,033 | 2.734375 | 3 |
[] |
no_license
|
<?php
class AppModel extends Model {
var $export_file = 'files/export.csv';
// var $useDbConfig = 'test';
// kontroluje, jestli se jedna o obycejneho uzivatele a jestli nevyzaduje pristup
// k datum jineho uzivatele
function checkUser($user, $checked_id) {
if ($user['User']['user_type_id'] == 3) {
if ($checked_id != $user['User']['id']) {
return false;
}
}
return true;
}
/**
*
* Z data ve formatu array udela retezec pro ulozeni do db
* @param array $date
*/
function built_date($date) {
if (strlen($date['month']) == 1) {
$date['month'] = '0' . $date['month'];
}
if (strlen($date['day']) == 1) {
$date['day'] = '0' . $date['day'];
}
return $date['year'] . '-' . $date['month'] . '-' . $date['day'];
}
/**
*
* z data ve stringu udela pole
* @param string $date
*/
function unbuilt_date($date) {
$date = explode('-', $date);
return array('day' => $date[2], 'month' => $date[1], 'year' => $date[0]);
}
/**
*
* provadi export dat, pouzije zadany find a data zapise do xls
* @param array $find
*/
function xls_export($find, $export_fields, $virtualFields = array()) {
// pole kde jsou data typu datetim
$datetime_fields = array(
/* 'BusinessSession.date',
'BusinessSession.created',
'Imposition.created',
'Offer.created'*/
);
// pole kde jsou data typu date
$date_fields = array(
/* 'Solution.accomplishment_date',
'Cost.date',
'DeliveryNote.date',
'Sale.date',
'Transaction.date'*/
);
$month_fields = array(
'["Contract"]["month"]'
);
// exportuju udaj o tom, ktera pole jsou soucasti vystupu
$find['fields'] = Set::extract('/field', $export_fields);
// vyhledam data podle zadanych kriterii
if (!empty($virtualFields)) {
foreach ($virtualFields as $key => $value) {
$this->virtualFields[$key] = $value;
}
}
$data = $this->find('all', $find);
$file = fopen($this->export_file, 'w');
// zjistim aliasy, pod kterymi se vypisuji atributy v csv souboru
$aliases = Set::extract('/alias', $export_fields);
$line = implode(';', $aliases);
// do souboru zapisu hlavicku csv (nazvy sloupcu)
fwrite($file, iconv('utf-8', 'windows-1250', $line . "\r\n"));
$positions = Set::extract('/position', $export_fields);
// do souboru zapisu data (radky vysledku)
foreach ($data as $item) {
$line = '';
$results = array();
foreach ($positions as $index => $position) {
$expression = '$item' . $position;
$escape_quotes = true;
if (array_key_exists('escape_quotes', $export_fields[$index])) {
$escape_quotes = $export_fields[$index]['escape_quotes'];
}
if ($escape_quotes) {
$expression = str_replace('"', '\'', $expression);
}
eval("\$result = ". $expression . ";");
if (in_array($position, $month_fields)) {
$months = months();
$result = $months[$result];
} else {
// prevedu sloupce s datetime
$result = preg_replace('/^(\d{4})-(\d{2})-(\d{2}) (.+)$/', '$3.$2.$1 $4', $result);
// prevedu sloupce s datem
$result = preg_replace('/^(\d{4})-(\d{2})-(\d{2})$/', '$3.$2.$1', $result);
// nahradim desetinnou tecku carkou
$result = preg_replace('/^(-?\d+)\.(\d+)$/', '$1,$2', $result);
// odstranim nove radky
$result = str_replace("\r\n", ' ', $result);
}
$results[] = $result;
}
$line = implode(';', $results);
// ulozim radek
fwrite($file, iconv('utf-8', 'windows-1250', $line . "\n"));
}
fclose($file);
return true;
}
function getFieldValue($id, $field) {
$item = $this->find('first', array(
'conditions' => array('id' => $id),
'contain' => array(),
'fields' => array($field)
));
if (empty($item)) {
return false;
}
return $item[$this->name][$field];
}
function getIdByField($value, $field) {
$item = $this->find('first', array(
'conditions' => array($field => $value),
'contain' => array(),
'fields' => array('id')
));
if (empty($item)) {
return false;
}
return $item[$this->name]['id'];
}
function getItemById($id) {
$item = $this->find('first', array(
'conditions' => array('id' => $id),
'contain' => array()
));
return $item;
}
function setAttribute($id, $attName, $attValue) {
$save = array(
$this->name => array(
'id' => $id,
$attName => $attValue
)
);
return $this->save($save);
}
function getTotalQuantity($conditions, $contain, $joins) {
return $this->getTotal($conditions, $contain, $joins, $this->getTotalQuantityOptions());
}
function getTotalPrice($conditions, $contain, $joins) {
return $this->getTotal($conditions, $contain, $joins, $this->getTotalPriceOptions());
}
function getTotal($conditions, $contain, $joins, $options) {
$total = $this->find('first', array(
'conditions' => $conditions,
'contain' => $contain,
'joins' => $joins,
'fields' => array('SUM(' . $options['col_expr'] . ') AS ' . $options['col_name'])
));
return $total[0][$options['col_name']];
}
}
|
Ruby
|
UTF-8
| 1,205 | 3.609375 | 4 |
[] |
no_license
|
# frozen_string_literal: true
require './lib/connect_four'
# class handles switching between players
class TwoPlayerGame
PLAYER_1 = 0
PLAYER_2 = 1
def initialize(game = ConnectFour.new, player_1 = PLAYER_1, player_2 = PLAYER_2, current_player = PLAYER_1)
@game = game
@player_one = player_1
@player_two = player_2
@current_player = current_player
end
def play
@game.welcome_message
players
until @game.done?
@game.start_of_turn_message
puts "It's #{@current_player}'s turn.'"
input = ask_for_valid_input
@game.play_a_turn(@current_player, input)
switch_players
end
@game.final_message
end
private
def players
@player_one = @game.player_one
@player_two = @game.player_two
@current_player = @player_one
end
def ask_for_valid_input
input = ''
until @game.valid_input?(input)
puts "#{@game.message_to_ask_for_input}"
input = gets.chomp
@game.invalid_input_message(input) unless @game.valid_input?(input)
end
input
end
def switch_players
@current_player = @current_player == @player_one ? @player_two : @player_one
end
end
game = TwoPlayerGame.new
game.play
|
Java
|
UTF-8
| 228 | 2.640625 | 3 |
[] |
no_license
|
package com.mishadoff.algo.matrix;
/**
* @author mishadoff
*/
public class Matrix<T> {
private T[][] data;
public Matrix(int n, int m) {
}
public void setData(T[][] data) {
this.data = data;
}
}
|
C#
|
UTF-8
| 560 | 2.875 | 3 |
[] |
no_license
|
using System;
using System.Security.Cryptography;
using System.Text;
namespace Enyim.Caching.Memcached.KeyTransformers
{
/// <summary>
/// A key transformer which converts the item keys into their SHA1 hash.
/// </summary>
public sealed class SHA1KeyTransformer : IMemcachedKeyTransformer
{
string IMemcachedKeyTransformer.Transform(string key)
{
SHA1Managed sh = new SHA1Managed();
byte[] data = sh.ComputeHash(Encoding.Unicode.GetBytes(key));
return Convert.ToBase64String(data, Base64FormattingOptions.None);
}
}
}
|
Python
|
UTF-8
| 1,445 | 2.875 | 3 |
[] |
no_license
|
f1 = open("family.ged", "r")
f2 = open("answer.txt", "w")
base = {}
for line in f1.readlines():
words = line.split(" ")
if len(words) >= 3:
s1 = words[1]
s2 = words[2]
if s2[0] == "I":
key = words[1]
if s1 == "GIVN":
name = words[2]
if s1 == "SURN":
surn = words[2]
value = (name[:-1], surn[:-1])
newElem = {key:value}
base.update(newElem)
if s1 == "SEX":
if s2[:-1] == "F":
s = "female(\'%s\').\n" % (name[:-1] + " " + surn[:-1])
f2.write(s)
if s2[:-1] == "M":
s = "male(\'%s\').\n" % (name[:-1] + " " + surn[:-1])
f2.write(s)
if s1 == "HUSB":
husb = words[2]
for k, (a, b) in base.items():
if k == husb[:-1]:
father = a + " " + b
if s1 == "WIFE":
wife = words[2]
for k, (a, b) in base.items():
if k == wife[:-1]:
mother = a + " " + b
if s1 == "CHIL":
chil = words[2]
for k, (a, b) in base.items():
if k == chil[:-1]:
child = a + " " + b
s = "child('%s', '%s').\n" % (child, father)
f2.write(s)
s = "child('%s', '%s').\n" % (child, mother)
f2.write(s)
f2.close()
f1.close()
|
Java
|
UTF-8
| 2,929 | 2.4375 | 2 |
[] |
no_license
|
package com.shcepp.shdippsvr.sys.util.mail;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import kr.pe.kwonnam.slf4jlambda.LambdaLoggerFactory;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
public class MailUtils {
private static final LambdaLogger logger = LambdaLoggerFactory.getLogger(MailUtils.class);
private static Properties p;
/**
* 方法描述:发送邮件
*
* @param title
* @param context
* @param emails
* @author liming
* @time 2011-7-19 下午03:45:08
*/
public static void sendEmail(String mailFrom, String host, String userName,
String userPassword, String title, String context, String[] emails) {
logger.info("sendEmail called");
logger.info("mailFrom:" + mailFrom);
logger.info("host:" + host);
logger.info("context:" + context);
try {
if(emails != null && emails.length > 0) {
if(p == null) {
try {
p = new Properties();
p.put("mail.smtp.auth", "false");
p.put("mail.from.address", "no-reply@shcepp.com");
p.put("mail.smtp.host", host);
p.put("mail.user.name", userName);
p.put("mail.user.pass", userPassword);
p.put("mail.transport.protocol", "smtp");
}
catch(Exception e) {
e.printStackTrace();
}
}
if(p != null) {
// 建立会话
Session session = Session.getInstance(p);
Message msg = new MimeMessage(session); // 建立信息
msg.setFrom(new InternetAddress(mailFrom)); // 发件人
msg.setSentDate(new Date()); // 发送日期
msg.setContent(context, "text/html; charset=utf-8");
msg.setSubject(title); // 主题
for(String add : emails) {
msg.setRecipient(Message.RecipientType.TO,
new InternetAddress(add)); // 收件人
// 邮件服务器进行验证
Transport tran = session.getTransport("smtp");
tran.connect(host, userName, userPassword);
tran.sendMessage(msg, msg.getAllRecipients()); // 发送邮件
logger.info("to:" + add);
}
}
}
}
catch(Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
}
|
Python
|
UTF-8
| 3,818 | 3.5 | 4 |
[
"MIT"
] |
permissive
|
import sqlite3
from db import db
# class UserModel:
class UserModel(db.Model): # tells SQLAlchemy it's something to save/add to db
"""
This is not a resource because the API cannot receive data into this class
or send as a JSON representation. It is a helper used to store data about
the user & contains methods to retrieve user objects from a DB.
This is now an API. (Just not a REST API)
These 2 methods are an interface into another part of the program
"""
# tell ALchemy which table items will be stored in
__tablename__ = "users"
# tell ALchemy which columns it will contain
# creates an index & makes it easier to search
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80)) # can limit size of username
password = db.Column(db.String(80))
# def __init__(self, _id, username, password):
# # these items must match the columns above
# # if they're not created above, they won't be stored to the DB
# self.id = _id
def __init__(self, username, password):
# these items must match the columns above
# if they're not created above, they won't be stored to the DB
self.username = username
self.password = password
@classmethod
# def find_by_username(self, username):
def find_by_username(cls, username):
"""
This function takes in a username string and will search the database.
If found, returns user otherwise None.
"""
# connection = sqlite3.connect("data.db")
# cursor = connection.cursor()
#
# # WHERE limits the selection to only be rows that match
# query = "SELECT * FROM users WHERE username=?"
# result = cursor.execute(query, (username,))
# row = result.fetchone() # returns None if not found
# if row:
# # each element of row should match the init method input items
# # user = User(row[0], row[1], row[2])
# # user = cls(row[0], row[1], row[2]) # use curr. class vs hard code
# user = cls(*row) # use curr. class vs hard code - pass in *args
# else:
# user = None
#
# connection.close()
# return user
# this is a classmethod so cls
# using SQLAlchemy's query builder
# - ability to do a DB query (SELECT * FROM users)
# then filtered on username & returning the 1st "row" as a UserModel obj
return cls.query.filter_by(username=username).first()
@classmethod
def find_by_id(cls, _id):
"""
This function takes in a username string and will search the database.
If found, returns user otherwise None.
"""
# connection = sqlite3.connect("data.db")
# cursor = connection.cursor()
#
# # WHERE limits the selection to only be rows that match
# query = "SELECT * FROM users WHERE id=?"
# result = cursor.execute(query, (_id,))
# row = result.fetchone() # returns None if not found
# if row:
# # each element of row should match the init method input items
# user = cls(*row) # use curr. class vs hard code - pass in *args
# else:
# user = None
#
# connection.close()
# return user
return cls.query.filter_by(id=_id).first() # no way 2 avoid id in SQLAlchemy
def save_to_db(self):
"""
This function takes in a UserModel object and saves it to the DB.
"""
db.session.add(self)
db.session.commit()
def del_from_db(self):
"""
This function deletes a UserModel object from the DB.
"""
db.session.add(self)
db.session.commit()
|
JavaScript
|
UTF-8
| 2,662 | 2.53125 | 3 |
[] |
no_license
|
require("./config/config.js");
const path = require("path");
const bodyParsers = require("body-parser");
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const {generateMessage, generateLocationMessage} = require("./utils/message.js");
const {isRealString} = require("./utils/validation.js");
const {Users} = require("./utils/users.js");
const publicPath = path.join(__dirname, "../public");
const port = process.env.PORT;
let app = express();
let server = http.createServer(app); // manually create http server
let io = socketIO(server);
let users = new Users();
app.use(express.static(publicPath));
io.on("connection", (socket) => {
console.log("New user connected");
socket.on("join", (params, callback) => {
if (!isRealString(params.name) || !isRealString(params.channel)) {
return callback("Name and room name are required.");
}
// join the channel:
socket.join(params.channel);
// Update users list:
users.removeUser(socket.id); // user can be in only one room
users.addUser(socket.id, params.name, params.channel);
io.to(params.channel).emit("updateUserList", users.getUserList(params.channel));
// socket.emit sends it to self:
socket.emit("newMessage", generateMessage(
"Admin",
`Welcome to channel #${params.channel}, user ${params.name}`
));
// socket.broadcast sends it to everyone *else* (not self):
socket.broadcast.to(params.channel).emit("newMessage", generateMessage(
"Admin",
`${params.name} joined the channel`
));
callback();
});
socket.on("createMessage", (msg, callback) => {
let user = users.getUser(socket.id);
if (user && isRealString(msg.text)) {
// io.emit sends it to everyone:
io.to(user.channel).emit("newMessage", generateMessage(
user.name,
msg.text
));
}
callback();
});
socket.on("createLocationMessage", (coords) => {
let user = users.getUser(socket.id);
if (user) {
io.to(user.channel).emit("newLocationMessage", generateLocationMessage(
user.name,
coords.latitude,
coords.longitude
));
}
});
socket.on("disconnect", () => {
console.log("User disconnected.");
let user = users.removeUser(socket.id);
if (user) {
io.to(user.channel).emit("updateUserList", users.getUserList(user.channel));
io.to(user.channel).emit("newMessage", generateMessage(
"Admin",
`${user.name} has left the channel`
));
}
});
});
// Start server
server.listen(port, () => {
console.log(`Started on port ${port}.`);
});
|
Java
|
UTF-8
| 421 | 2.125 | 2 |
[] |
no_license
|
package com.users.demo.dao;
import com.users.demo.entities.Customer;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
@Repository
public interface CustomerDao {
List getAllCustomers();
Customer getCustomerById(int id);
void deleteCustomerById(int id);
void insertCustomer(Customer customer);
void updateCustomerById(int id,Customer customer);
}
|
Markdown
|
UTF-8
| 1,612 | 3.40625 | 3 |
[] |
no_license
|
# 1541 - 잃어버린 괄호
<hr/>
## 1. 문제 설명
세준이는 양수와 +, -, 그리고 괄호를 가지고 길이가 최대 50인 식을 만들었다. 그리고 나서 세준이는 괄호를 모두 지웠다.
그리고 나서 세준이는 괄호를 적절히 쳐서 이 식의 값을 최소로 만들려고 한다.
괄호를 적절히 쳐서 이 식의 값을 최소로 만드는 프로그램을 작성하시오.
[잃어버린 괄호](<https://www.acmicpc.net/problem/1541>)
------
## 2. 입력
첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다 많이 연속되는 숫자는 없다. 수는 0으로 시작할 수 있다.
------
## 3. 출력
첫째 줄에 정답을 출력한다.
------
## 4. 문제 풀이
1. 문제를 너무 어렵게 생각했다
2. 예제 입력에 `55-50+40`인데 `55-5(0+40)`을 하게 되면은 `55-200`이 나와서 `-145`가 나온다
3. 이렇게 되면은 예제 출력이 잘못된 값이 되버리는데 답을 못찾던 중 `55-(50+40)`을 하게 되면은 예제 출력이 나온다는 것을 알게 됐다
4. 즉 `-`가 처음 나온 이후의 모든 숫자들은 앞에 `-`가 나오건, `+`가 나오건 기존 값에서 빼주면 된다
5. 내 코드의 경우 마지막 값을 계산해주는 것이 없는데 이전에 `-`가 나왔었는지 여부를 확인하여 그냥 더해줄지 `-`를 해줄지 확인하여 더하는 코드를 추가했다
|
Java
|
UTF-8
| 3,947 | 2.640625 | 3 |
[] |
no_license
|
package cn.com.example.customermanagement.utils;
import com.google.gson.*;
import com.google.gson.internal.bind.DateTypeAdapter;
import java.io.Reader;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* JSON转换工具类
*
* @author liyuanming
* @version 2010-12-24
*/
public class JsonUtil {
private static Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(ArrayList.class, new ListInstanceCreator()).registerTypeAdapter(Date.class, new DateTypeAdapter()).registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create();
public static class ListInstanceCreator implements InstanceCreator<List<Object>> {
public List<Object> createInstance(Type type) {
return new ArrayList<Object>();
}
}
public static class StringDeserializer implements JsonDeserializer<String> {
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) {
return json.getAsString();
}
return "";
}
}
public static <T> T fromJson(Reader read, Class<T> clazz) {
try {
T object = gson.fromJson(read, clazz);
return object;
} catch (Exception ex) {
return new GsonBuilder().registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(ArrayList.class, new ListInstanceCreator()).registerTypeAdapter(Date.class, new DateTypeAdapter()).registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create().fromJson(read, clazz);
}
}
public static <T> T fromJson(String json, Class<T> clazz) {
try {
T object = gson.fromJson(json, clazz);
return object;
} catch (Exception ex) {
return new GsonBuilder().registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(ArrayList.class, new ListInstanceCreator()).registerTypeAdapter(Date.class, new DateTypeAdapter()).registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create().fromJson(json, clazz);
}
}
@SuppressWarnings("unchecked")
public static <T> T fromJson(String json, Type TypeOfT) {
try {
T object = (T)gson.fromJson(json, TypeOfT);
return object;
} catch (Exception ex) {
return (T)new GsonBuilder().registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(ArrayList.class, new ListInstanceCreator()).registerTypeAdapter(Date.class, new DateTypeAdapter()).registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create().fromJson(json, TypeOfT);
}
}
public static String toJson(Object obj) {
try {
String str = gson.toJson(obj);
return str;
} catch (Exception ex) {
return new GsonBuilder().registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(ArrayList.class, new ListInstanceCreator()).registerTypeAdapter(Date.class, new DateTypeAdapter()).registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create().toJson(obj);
}
}
public static String toJson(Object obj,Type type) {
try {
String str = gson.toJson(obj, type);
return str;
} catch (Exception ex) {
return new GsonBuilder().registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(String.class, new StringDeserializer()).registerTypeAdapter(ArrayList.class, new ListInstanceCreator()).registerTypeAdapter(Date.class, new DateTypeAdapter()).registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create().toJson(obj,type);
}
}
}
|
Java
|
UTF-8
| 433 | 2.546875 | 3 |
[] |
no_license
|
package com.redwood.wiki.parser;
import com.redwood.wiki.utilities.ParseUtility;
public class SuperScriptParser implements Parseable {
private static final String REG_EXPR = "\\^.+?\\^";
/**
* replace ^superscript^
* with {SUP()}superscript{SUP}
*/
public String parseToTiki(String toParse) {
return ParseUtility.replacer("{SUP()}%s{SUP}", "\\^", toParse);
}
public String getRegExpr() {
return REG_EXPR;
}
}
|
C#
|
UTF-8
| 5,398 | 2.671875 | 3 |
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer.Data;
using IdentityServer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace IdentityServer
{
public class SeedUsers
{
private ApplicationDbContext _context;
private ILogger<SeedUsers> _logger;
private UserManager<ApplicationUser> _userManager;
public SeedUsers(ApplicationDbContext context, ILogger<SeedUsers> logger, UserManager<ApplicationUser> userManager)
{
_context = context;
_logger = logger;
_userManager = userManager;
}
public async Task Seed()
{
_logger.LogInformation("Seeding Class......");
// check if users exists
var usersExists = _context.Users.Any();
if (usersExists)
{
_logger.LogInformation("Users already exist. Not need to seed users.");
return;
}
if (!usersExists)
{
_logger.LogInformation("Checking if to seed users.......");
// seed users
var alice = new ApplicationUser { UserName = "alice", Email = "alice@test.com" };
var bob = new ApplicationUser { UserName = "bob", Email = "bob@test.com" };
var aliceResult = new IdentityResult();
try
{
aliceResult = await _userManager.CreateAsync(alice, "Pass123$");
}
catch (System.Exception ex)
{
}
// https://stackoverflow.com/questions/32459670/resolving-instances-with-asp-net-core-di
if (aliceResult.Succeeded)
{
_logger.LogInformation($"Alice created successfully");
// add alice claims
await AddUserClaims(alice, "Alice", GetAliceClaims());
}
else
{
var errors = GetErrors(aliceResult.Errors);
_logger.LogInformation($"Alice could not be added to database, Errors: {errors}");
}
var bobResult = await _userManager.CreateAsync(bob, "Pass123$");
if (bobResult.Succeeded)
{
_logger.LogInformation($"Bob created successfully");
// add alice claims
await AddUserClaims(alice, "Bob", GetBobClaims());
}
else
{
var errors = GetErrors(bobResult.Errors);
_logger.LogInformation($"Bob could not be added to database, Errors: {errors}");
}
}
}
private async Task AddUserClaims(ApplicationUser applicationUser, string user, IEnumerable<Claim> claims)
{
var response = await _userManager.AddClaimsAsync(applicationUser, claims);
if (response.Succeeded)
{
_logger.LogInformation($"{user} claims added to database");
}
else
{
var errors = GetErrors(response.Errors);
_logger.LogInformation($"Could not add claims for {user} to database, Errors: {errors}");
}
}
private string GetErrors(IEnumerable<IdentityError> identityErrors)
{
var response = identityErrors.Select(x => x.Description)
.ToList();
var joinedErrors = string.Join(',', response);
return joinedErrors;
}
private static IEnumerable<Claim> GetAliceClaims()
{
return new List<Claim>
{
new Claim(JwtClaimTypes.Name, "Alice Smith"),
new Claim(JwtClaimTypes.GivenName, "Alice"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json)
};
}
private static IEnumerable<Claim> GetBobClaims()
{
return new List<Claim>
{
new Claim(JwtClaimTypes.Name, "Alice Smith"),
new Claim(JwtClaimTypes.GivenName, "Alice"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json)
};
}
}
}
|
C++
|
UTF-8
| 1,308 | 3.609375 | 4 |
[] |
no_license
|
#pragma once
#include <mutex>
#include <queue>
#include <condition_variable>
#include <limits>
template <typename Value, size_t MaxCapacity = std::numeric_limits<size_t>::max()>
class Queue
{
public:
Queue() {}
Queue(const Queue&) = delete;
Queue& operator=(const Queue&) = delete;
Queue(Queue&& other) noexcept {
std::exchange(m_que, other.m_que);
}
Queue& operator=(Queue&& other) noexcept
{
if (&other == this)
return *this;
std::exchange(m_que, other.m_que);
return *this;
}
bool enqueue(Value&& value) {
std::unique_lock<std::mutex> locker(m_mtx);
if (m_que.size() >= MaxCapacity)
return false;
m_que.push(std::move(value));
locker.unlock();
m_cond.notify_all();
return true;
}
Value dequeue() {
std::unique_lock<std::mutex> locker(m_mtx);
m_cond.wait(locker, [this] () { return !m_que.empty(); });
Value item(std::move(m_que.front()));
m_que.pop();
locker.unlock();
m_cond.notify_one();
return std::move(item);
}
bool isEmpty() {
std::lock_guard<std::mutex> locker(m_mtx);
return m_que.empty();
}
private:
std::mutex m_mtx;
std::condition_variable m_cond;
std::queue<Value> m_que;
};
|
C#
|
UTF-8
| 2,054 | 2.828125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace MassSpecStudio.Core.DataProvider
{
public static class XicHelper
{
public static void GetIntensities(IList<double> mzValues, IList<double> intensityValues, double rt, double mass1, double mzTolerance, List<double> msLevelXVals, List<double> msLevelYVals)
{
if (mzValues.Count > 0)
{
int indexOfMass = IndexOfMassInSpectrum(mzValues, mass1, mzTolerance);
if (WasMassFound(indexOfMass))
{
indexOfMass = FindIndexOfHighestIntensityWithinTolerance(mzValues, intensityValues, indexOfMass, mass1, mzTolerance);
if (DoesThisMassBelongWithThePreviousRt(msLevelXVals, rt))
{
msLevelYVals[msLevelYVals.Count - 1] += (double)intensityValues[indexOfMass];
}
else
{
msLevelXVals.Add(rt);
msLevelYVals.Add((double)intensityValues[indexOfMass]);
}
}
else
{
msLevelXVals.Add(rt);
msLevelYVals.Add(0);
}
}
}
private static int IndexOfMassInSpectrum(IList<double> mzValues, double mass1, double mzTolerance)
{
for (int j = 0; j < mzValues.Count; ++j)
{
double d = (double)mzValues[j];
if (Math.Abs(mass1 - d) <= mzTolerance)
{
return j;
}
}
return -1;
}
private static bool WasMassFound(int indexOfMass)
{
return indexOfMass >= 0;
}
private static int FindIndexOfHighestIntensityWithinTolerance(IList<double> mzValues, IList<double> intensityValues, int foundIndex, double mass1, double mzTolerance)
{
for (int k = foundIndex; k < mzValues.Count; k++)
{
double d = (double)mzValues[k];
if (Math.Abs(mass1 - mzValues[k]) <= mzTolerance)
{
// select index with greatest intensity
if (intensityValues[k] > intensityValues[foundIndex])
{
foundIndex = k;
}
}
else
{
break;
}
}
return foundIndex;
}
private static bool DoesThisMassBelongWithThePreviousRt(IList<double> xValues, double rt)
{
return xValues.Count > 0 && xValues.Last() == rt;
}
}
}
|
C#
|
UTF-8
| 2,931 | 3.34375 | 3 |
[] |
no_license
|
using AssignmentThree.Enemies;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssignmentThree
{
class Player
{
private string name;
private int lvl = 1;
private int hp = 200;
private int maxHp = 200;
private int atkDmg = 20;
private int exp;
private int expToNxtLvl = 100;
private int gold;
private int strength;
private int toughness;
private bool dead;
Random rnd = new Random();
public int attack(IAnimal monster)
{
int dmg = rnd.Next(1, atkDmg);
dmg += rnd.Next(strength, strength * 2);
monster.takeDamage(dmg);
return dmg;
}
public void takeDamage(int monsterdmg)
{
monsterdmg -= Toughness;
hp -= monsterdmg;
}
public int getGold(IAnimal monster)
{
gold += monster.getGold();
return gold;
}
public int getExp(IAnimal monster)
{
exp += monster.getExp();
return exp;
}
public void CheckLevelUp()
{
if (exp >= expToNxtLvl)
{
Lvl++;
maxHp += 100;
atkDmg += 10;
exp -= expToNxtLvl;
expToNxtLvl += 10;
hp = maxHp;
Console.WriteLine($"Congrats you leveled up and are now level {Lvl}");
Console.WriteLine($"Your powers increased and you healed to full HP: {hp}/{maxHp}");
}
}
public bool isDead()
{
if (this.hp <= 0)
{
this.dead = true;
}
else
{
this.dead = false;
}
return this.dead;
}
public void GodMode()
{
if (string.Equals(name.Trim(), "Robin", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Hello Robin, GodMode Activated!");
AtkDmg = 1000;
}
}
public string Name { get => name; set => name = value; }
public int Lvl { get => lvl; set => lvl = value; }
public int Hp { get => hp; set => hp = value; }
public int MaxHp { get => maxHp; set => maxHp = value; }
public int AtkDmg { get => atkDmg; set => atkDmg = value; }
public int Exp { get => exp; set => exp = value; }
public int ExpToNxtLvl { get => expToNxtLvl; set => expToNxtLvl = value; }
public int Gold { get => gold; set => gold = value; }
public int Strength { get => strength; set => strength = value; }
public int Toughness { get => toughness; set => toughness = value; }
public bool Dead { get => dead; set => dead = value; }
}
}
|
Markdown
|
UTF-8
| 1,112 | 2.578125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# FitMiddleware
Simply Middleware Implementation.
## Installation
```
composer require fitdev-pro/middleware
```
## Usage
Base usage
```php
<?php
$hundler = new MiddlewareHundler(new Resolver(), new Queue());
$hundler->append(Foo/Bar/SomeClass::class);
$hundler->append(function ($input, $output, $next){
$data += 1;
return $next($data);
});
$hundler->append(function ($input, $output, $next){
$data += 2;
if($data > 4){
return $data;
}
return $next($data);
});
$hundler->append(function ($input, $output, $next){
$data += 3;
return $next($data);
});
$newData = $hundler->hundle(2);
```
## Contribute
Please feel free to fork and extend existing or add new plugins and send a pull request with your changes!
To establish a consistent code quality, please provide unit tests for all your changes and may adapt the documentation.
## License
The MIT License (MIT). Please see [License File](https://github.com/fitdev-pro/middleware/blob/master/LISENCE) for more information.
|
C++
|
UTF-8
| 7,377 | 2.71875 | 3 |
[] |
no_license
|
/*
* Copyright (c) 2018-2021 Steven Varga, Toronto,ON Canada
* Author: Varga, Steven <steven@vargaconsulting.ca>
*/
#ifndef H5CPP_SALL_HPP
#define H5CPP_SALL_HPP
#include <hdf5.h>
#include "H5config.hpp"
#include "H5Iall.hpp"
#include "H5meta.hpp"
#include <initializer_list>
#include <array>
namespace h5::impl {
struct max_dims_t{}; struct current_dims_t{};
struct dims_t{}; struct chunk_t{}; struct offset_t{}; struct stride_t{}; struct count_t{}; struct block_t{};
template <typename T, int N=H5CPP_MAX_RANK>
struct array {
array( size_t rank, hsize_t value ) : rank( rank ) {
for(int i=0; i<rank; i++) data[i] = value;
}
array( const std::initializer_list<size_t> list ) : rank( list.size() ) {
for(int i=0; i<rank; i++) data[i] = *(list.begin() + i);
}
// support linalg objects upto 3 dimensions or cubes
template<class A> array( const std::array<A,0> l ) : rank(0), data{} {}
template<class A> array( const std::array<A,1> l ) : rank(1), data{l[0]} {}
template<class A> array( const std::array<A,2> l ) : rank(2), data{l[0],l[1]} {}
template<class A> array( const std::array<A,3> l ) : rank(3), data{l[0],l[1],l[2]} {}
/** @brief computes the total space
*/
explicit operator const hsize_t () const {
hsize_t size = 1;
for(hsize_t i=0; i<rank; i++) size *= data[i];
return size;
}
// automatic conversion to std::array means to collapse tail dimensions
template<class A>
operator const std::array<A,0> () const {
return {};
}
template<class A>
operator const std::array<A,1> () const {
size_t a = data[0];
for(int i=1;i<rank;i++) a*=data[i];
return {a};
}
template<class A>
operator const std::array<A,2> () const {
size_t a,b; a = data[0]; b = data[1];
for(int i=2;i<rank;i++) b*=data[i];
return {a,b};
}
template<class A>
operator const std::array<A,3> () const {
size_t a,b,c; a = data[0]; b = data[1]; c = data[2];
for(int i=3;i<rank;i++) c*=data[i];
return {a,b,c};
}
array() : rank(0){};
array( array&& arg ) = default;
array( array& arg ) = default;
array(const array& arg) = default;
array& operator=( array&& arg ) = default;
array& operator=( array& arg ) = default;
template<class C>
explicit operator array<C>(){
array<C> arr;
arr.rank = rank;
hsize_t i=0;
for(; i<rank; i++) arr[i] = data[i];
// the shape/dimension may be different, be certain the
// remaining is initilized to ones
for(; i<N; i++) arr[i] = 1;
return arr;
}
hsize_t& operator[](size_t i){ return *(data + i); }
const hsize_t& operator[](size_t i) const { return *(data + i); }
hsize_t* operator*() { return data; }
const hsize_t* operator*() const { return data; }
using type = T;
size_t size() const { return rank; }
const hsize_t* begin()const { return data; }
hsize_t* begin() { return data; }
size_t rank;
hsize_t data[N];
};
template <class T> inline
size_t nelements( const h5::impl::array<T>& arr ){
size_t size = 1;
for( int i=0; i<arr.rank; i++) size *= arr[i];
return size;
}
}
/*PUBLIC CALLS*/
namespace h5 {
using max_dims_t = impl::array<impl::max_dims_t>;
using current_dims_t = impl::array<impl::current_dims_t>;
using dims_t = impl::array<impl::dims_t>;
using chunk_t = impl::array<impl::chunk_t>;
using offset_t = impl::array<impl::offset_t>;
using stride_t = impl::array<impl::stride_t>;
using count_t = impl::array<impl::count_t>;
using block_t = impl::array<impl::block_t>;
using offset = offset_t;
using stride = stride_t;
using count = count_t;
using block = block_t;
using dims = dims_t;
using current_dims = current_dims_t;
using max_dims = max_dims_t;
//*< usage: `const h5::stride_t& stride = h5::impl::arg::get( h5::default_stride, args...);` */
const static h5::count_t default_count{1,1,1,1,1,1,1}; /**< used as block in hyperblock selection as default value */
const static h5::offset_t default_offset{0,0,0,0,0,0,0}; /**< used as offset in hyperblock selection as default value */
const static h5::stride_t default_stride{1,1,1,1,1,1,1}; /**< used as stride in hyperblock selection as default value */
const static h5::block_t default_block{1,1,1,1,1,1,1}; /**< used as block in hyperblock selection as default value */
const static h5::block_t default_current_dims{0,0,0,0,0,0,0}; /**< used as block in hyperblock selection as default value */
const static h5::block_t default_max_dims{0,0,0,0,0,0,0}; /**< used as block in hyperblock selection as default value */
}
namespace h5::impl {
/** \ingroup internal
* @brief computes `h5::current_dims_t` considering the context
* Current and maximum dimension of an HDF5 object is how much space is available for immediate or further use within a dataset.
* This routing computes the size along each dimesnion of `current_dims` and it considers the object size given by `count`, its
* coordinates within the filespace `h5::offset`, how it is spaced `h5::stride` and the `h5::block` size.
* @param count rank and size of the object along each dimension
* @tparam T C++ type of dataset being written into HDF5 container
*
* <br/>The following arguments are context sensitive, may be passed in arbitrary order and with the exception
* of `T object` being saved, the arguments are optional. The arguments are set to sensible values, and in most cases
* will provide good performance by default, with that in mind, it is an easy high level fine tuning mechanism to
* get the best experience witout trading readability.
*
* @param h5::stride_t skip this many blocks along given dimension
* @param h5::block_t only used when `stride` is specified
* @param h5::offset_t writes `T object` starting from this coordinates, considers this shift into `h5::current_dims` when applicable
*/
template <class... args_t> inline
h5::current_dims_t get_current_dims(const h5::count_t& count, args_t&&... args ){
// premise: h5::current_dims{} is not present
using toffset = typename arg::tpos<const h5::offset_t&,const args_t&...>;
using tstride = typename arg::tpos<const h5::stride_t&,const args_t&...>;
using tblock = typename arg::tpos<const h5::block_t&,const args_t&...>;
h5::current_dims_t current_dims;
hsize_t rank = current_dims.rank = count.rank;
for(hsize_t i =0; i < rank; i++ )
current_dims[i] = count[i];
// TODO: following syntax looks better
//auto current_dims = static_cast<h5::current_dims_t>(count);
if constexpr( tstride::present ){ // when stride is not specified block == count
const h5::stride_t& stride = std::get<tstride::value>( std::forward_as_tuple( args...) );
if constexpr( tblock::present ){ // tricky, we have block as well
const h5::block_t& block = std::get<tblock::value>( std::forward_as_tuple( args...) );
for(hsize_t i=0; i < rank; i++)
current_dims[i] *= (stride[i] - block[i] + 1);
} else // block is not present, we are stretching `current_dims` with `stride`
for(hsize_t i=0; i < rank; i++)
current_dims[i] *= stride[i];
}
// we increment dimension with the specified offset, if any
if constexpr( toffset::present ){
const h5::offset_t& offset = std::get<toffset::value>( std::forward_as_tuple( args...) );
for(hsize_t i=0; i < rank; i++)
current_dims[i]+=offset[i];
}
return current_dims;
}
}
#endif
|
Java
|
UTF-8
| 1,944 | 2.296875 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package com.ctrip.zeus.model.tools;
public class CheckSlbreleaseResponse {
private Integer m_code;
private String m_status;
private String m_commitId;
public CheckSlbreleaseResponse() {
}
protected boolean equals(Object o1, Object o2) {
if (o1 == null) {
return o2 == null;
} else if (o2 == null) {
return false;
} else {
return o1.equals(o2);
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CheckSlbreleaseResponse) {
CheckSlbreleaseResponse _o = (CheckSlbreleaseResponse) obj;
if (!equals(m_code, _o.getCode())) {
return false;
}
if (!equals(m_status, _o.getStatus())) {
return false;
}
if (!equals(m_commitId, _o.getCommitId())) {
return false;
}
return true;
}
return false;
}
public Integer getCode() {
return m_code;
}
public String getCommitId() {
return m_commitId;
}
public String getStatus() {
return m_status;
}
@Override
public int hashCode() {
int hash = 0;
hash = hash * 31 + (m_code == null ? 0 : m_code.hashCode());
hash = hash * 31 + (m_status == null ? 0 : m_status.hashCode());
hash = hash * 31 + (m_commitId == null ? 0 : m_commitId.hashCode());
return hash;
}
public CheckSlbreleaseResponse setCode(Integer code) {
m_code = code;
return this;
}
public CheckSlbreleaseResponse setCommitId(String commitId) {
m_commitId = commitId;
return this;
}
public CheckSlbreleaseResponse setStatus(String status) {
m_status = status;
return this;
}
}
|
Java
|
UTF-8
| 1,323 | 2.21875 | 2 |
[] |
no_license
|
package jp.co.gfam.gits.integration.dao.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import jp.co.gfam.gits.integration.dao.UserCriteria;
import jp.co.gfam.gits.integration.dao.UserDaoImpl;
import jp.co.gfam.gits.integration.entity.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Kenichi Masuda
*
*/
public class UserDaoImplTest {
private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>();
private UserDaoImpl target = new UserDaoImpl();
@Before
public void open() throws Exception {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/gits", "gfam", "gfam");
connectionHolder.set(connection);
}
@After
public void close() {
}
/**
* {@link jp.co.gfam.gits.integration.dao.UserDaoImpl#select(jp.co.gfam.gits.integration.dao.UserCriteria)}
* のためのテスト・メソッド。
*/
@Test
public void testSearch() throws Exception {
UserCriteria criteria = new UserCriteria();
criteria.setUserId(123);
Connection con = connectionHolder.get();
List<User> results = target.select(criteria);
}
}
|
Ruby
|
UTF-8
| 996 | 2.609375 | 3 |
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts "Creation de 5 restaurants"
entrecote = Restaurant.new(name: "entrecote", category: "french", address: "2 rue des lilas")
entrecote.save!
quick = Restaurant.new(name: "quick", category: "belgian", address: "2 place du commerce")
quick.save!
grande_muraille = Restaurant.new(name: "grande muraille", category: "japanese", address: "rue des champs")
grande_muraille.save!
sushi = Restaurant.new(name: "sushi shop", category: "chinese", address: "rues des ponts")
sushi.save!
pizza = Restaurant.new(name: "pizza etna", category: "italian", address: "rues des chevaux")
pizza.save!
puts "Fin de la creation de 5 restaurant"
|
JavaScript
|
UTF-8
| 3,794 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
import React, { Component } from 'react';
import JourneyService from './journey-service';
import JourneyDetailsService from './journey-details-service';
import EditJourneyDetail from './EditJourneyDetail';
import EditJourneyMilestones from './EditJourneyMilestones';
class JourneyDetails extends Component {
state = {journeyDetails: [], journey: {}, mode: 'view'};
journeyService = new JourneyService();
journeyDetailsService = new JourneyDetailsService();
getListItem = () => {
const {id} = this.props.match.params
this.journeyService.getJourney(id)
.then(response => this.setState({journey: response}))
.catch(err => console.log(err))
}
setEditMode = (component) => {
component === 'Journey' ? this.setState({mode: 'editJourney'}) : this.setState({mode: 'editJourneyMilestones'});
}
setViewMode = () => {
this.setState({mode: 'view'});
}
getJourneyDetails = () => {
const {id} = this.props.match.params
this.journeyDetailsService.getJourneyDetails(id)
.then(response => this.setState({journeyDetails: response}))
.catch(err => console.log(err))
}
deleteItem = () => {
const { params } = this.props.match;
this.journeyService.deleteJourney(params.id)
.then(() =>{
this.getJourneys();
this.props.history.push('/canvas');
})
.catch((err)=>{console.log(err)})
}
componentDidMount() {
this.getListItem();
this.getJourneyDetails();
}
componentDidUpdate(prevProps) {
if(prevProps.match.params.id !== this.props.match.params.id) {
this.getListItem();
this.getJourneyDetails();
}
}
render() {
const {name, expectedDuration} = this.state.journey
const journeyDetails = this.state.journeyDetails
return (
<div className="bg-blue col-md-8 d-flex flex-column align-items-stretch justify-content-start">
{this.state.mode === 'view' && <div>
<div>
<div className='d-flex flex-row justify-content-end'>
<h4 className='mt-3 flex-grow-1 text-start ps-4'>{name}</h4>
<button className='mx-2 mt-3 btn btn-dark-blue' onClick={() => this.setEditMode('Journey')}>Edit</button>
<button className='mx-2 mt-3 btn btn-danger' onClick={() => this.deleteItem()}>Delete</button>
</div>
<p className='text-start ps-4 fs-5 pb-3'><b>Expected duration:</b> {expectedDuration}h</p>
</div>
<hr></hr>
<div>
<div className='d-flex flex-row justify-content-end'>
<h4 className='mt-3 flex-grow-1 text-start ps-4'>Milestones:</h4>
<button className='mx-2 mt-3 btn btn-dark-blue' onClick={() => this.setEditMode('JourneyMilestones')}>Edit</button>
</div>
{journeyDetails.length === 0 && <p className='pb-4'>No milestones yet!</p>}
{journeyDetails.length !==0 && <ul className='pb-3'>
{journeyDetails.sort((a, b) => a.order - b.order)
.map((detail) => <li className='text-start fs-5 list-unstyled' key={detail._id}>{detail.order} - {detail.milestone.name}</li>)}
</ul>}
</div>
<hr></hr>
</div>}
{this.state.mode === 'editJourney' && <EditJourneyDetail journeyDetails={journeyDetails} journey={this.state.journey}
setViewMode={this.setViewMode} getListItem={this.getListItem} getJourneyDetails={this.getJourneyDetails} {...this.props}/>}
{this.state.mode === 'editJourneyMilestones' && <EditJourneyMilestones journeyDetails={journeyDetails} getJourneyDetails={this.getJourneyDetails}
setViewMode={this.setViewMode} getListItem={this.getListItem} {...this.props}/>}
</div>
)
}
}
export default JourneyDetails;
|
C++
|
UTF-8
| 930 | 2.53125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int, int> pi;
/*
Disjoint-Set
*/
int n, m;
const int maxN = 1e5;
int link[maxN+1], sz[maxN+1];
int numComponent, sizeLargest;
int find(int x) {
while(x != link[x]) x = link[x];
return x;
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if(x==y) return false;
if(sz[x] < sz[y]) swap(x, y);
link[y] = x;
sz[x] += sz[y];
numComponent--;
sizeLargest = max(sizeLargest, sz[x]);
return true;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
numComponent = n;
sizeLargest = 1;
for(int i = 1; i <= n; ++i) {
link[i] = i;
sz[i] = 1;
}
while(m--) {
int x, y;
cin >> x >> y;
unite(x, y);
cout << numComponent << " " << sizeLargest << "\n";
}
}
|
PHP
|
UTF-8
| 2,712 | 2.84375 | 3 |
[] |
no_license
|
<?php
namespace Zeeml\MachineLearning\Tests\Traits;
use PHPUnit\Framework\TestCase;
use Zeeml\Algorithms\Prediction\Linear\LinearRegression;
use Zeeml\Algorithms\Prediction\Logistic\LogisticRegression;
use Zeeml\MachineLearning\Traits\MLHash;
class MLHashTest extends TestCase
{
protected $class;
public function setUp()
{
parent::setUp();
$this->class = new class() {
use MLHash;
public function testHash(array $algorithms, int $nbEpochs, float $learningRate, float $split): string
{
return $this->hash($algorithms, $nbEpochs, $learningRate, $split);
}
};
}
/**
* @test
*/
public function hash_should_be_a_string()
{
$hash = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$this->assertInternalType('string', $hash);
$this->assertTrue(strlen($hash) === 64);
}
/**
* @test
*/
public function hash_should_be_same_when_params_not_changes()
{
$hash1 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$hash2 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$this->assertEquals($hash1, $hash2);
$hash1 = $this->class->testHash([LinearRegression::class], 0, 0, 0);
$hash2 = $this->class->testHash([LinearRegression::class], 0, 0, 0);
$this->assertEquals($hash1, $hash2);
}
/**
* @test
*/
public function hash_should_be_different_when_one_param_changes()
{
$hash1 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$hash2 = $this->class->testHash([LinearRegression::class], 30, 0.004, 0.8);
$this->assertNotEquals($hash1, $hash2);
$hash1 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$hash2 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 31, 0.004, 0.8);
$this->assertNotEquals($hash1, $hash2);
$hash1 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.0041, 0.8);
$hash2 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$this->assertNotEquals($hash1, $hash2);
$hash1 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 2);
$hash2 = $this->class->testHash([LinearRegression::class, LogisticRegression::class], 30, 0.004, 0.8);
$this->assertNotEquals($hash1, $hash2);
}
}
|
Java
|
UTF-8
| 1,463 | 2.46875 | 2 |
[] |
no_license
|
import java.util.*;
import Jakarta.util.FixDosOutputStream;
import java.io.*;
/** production
[ AST_Modifiers ] UnmodifiedTypeDeclaration ::ModTypeDecl
*
* @layer<preprocess>
*/
public class ModTypeDecl {
// returns true only for Ute
public boolean isExtension() {
return ( ( UnmodifiedTypeDeclaration ) arg[1] ).isExtension();
}
/** returns name of UnmodifiedTypeDecl
* @layer<preprocess>
*/
public String GetName() {
return ( ( UnmodifiedTypeDeclaration ) arg[1] ).GetName();
}
/** returns type signature of UnmodifiedTypeDecl
* @layer<preprocess>
*/
public String GetType() {
return ( ( UnmodifiedTypeDeclaration ) arg[1] ).GetType();
}
/** composition of ModTypeDecls done in two steps:
(a) compose modifier lists
(b) compose unmodified type decls
*
* @layer<preprocess>
*/
/** composes base ModTypeDecl with extension ModTypeDecl<br>
composition done in two steps:<br>
(a) compose modifier lists<br>
(b) compose unmodified type decls <br>
*/
public void compose( AstNode etree ) {
ModTypeDecl e = ( ModTypeDecl ) etree;
// Step 1: compose modifier lists -- if base list is null
// just use the extension list
arg[0].compose( e.arg[0] );
// Step 2: compose unmodifiedtype declarations
arg[1].compose( e.arg[1] );
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.