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
| 2,917
| 2.5625
| 3
|
[] |
no_license
|
// delicaey
const hotDelicaeyImg = document.querySelectorAll('.hotDelicaey-contain li img')
const hotDelicaeyName = document.querySelectorAll('.hotDelicaey-contain p')
const hotDelicaeyAddress = document.querySelectorAll('.hotDelicaey-block span')
const hotDelicaeyContain = document.querySelector('.hotDelicaey-contain')
// Accommodation
const hotAccommodationImg = document.querySelectorAll(
'.hotAccommodation-contain li img',
)
const hotAccommodationName = document.querySelectorAll(
'.hotAccommodation-contain p',
)
const hotAccommodationAddress = document.querySelectorAll(
'.hotAccommodation-block span',
)
const hotAccommodationContain = document.querySelector(
'.hotAccommodation-contain',
)
axios
.get(
`https://ptx.transportdata.tw/MOTC/v2/Tourism/Restaurant?$top=10&$format=JSON
`,
{
headers: getAuthorizationHeader(),
},
)
.then(function (response) {
let str = ''
let img = ''
response.data.forEach((item) => {
// 檢查有無照片
if (item.Picture.PictureUrl1 != undefined) {
img = item.Picture.PictureUrl1
} else {
img = 'img/noImage.png'
}
str += `<li>
<img src=${img} alt="noImg" />
<p>${item.Name}</p>
<div class="hotDelicaey-block">
<i class="fas fa-map-marker-alt"></i><span>${item.Address}</span>
</div>
</li>`
})
hotDelicaeyContain.innerHTML = str
})
.catch(function (error) {
console.log(error)
})
axios
.get(
`https://ptx.transportdata.tw/MOTC/v2/Tourism/Hotel?$top=10&$format=JSON
`,
{
headers: getAuthorizationHeader(),
},
)
.then(function (response) {
let str = ''
let img = ''
response.data.forEach((item) => {
// 檢查有無照片
if (item.Picture.PictureUrl1 != undefined) {
img = item.Picture.PictureUrl1
} else {
img = 'img/noImage.png'
}
str += `<li>
<img src=${img} alt="noImg" />
<p>${item.Name}</p>
<div class="hotAccommodation-block">
<i class="fas fa-map-marker-alt"></i><span>${item.Address}</span>
</div>
</li>`
})
hotAccommodationContain.innerHTML = str
})
.catch(function (error) {
console.log(error)
})
function getAuthorizationHeader() {
// 填入自己 ID、KEY 開始
// let AppID = '9d5eccb4-ca4a-4f97-b829-7fa73264f550'
// let AppKey = '0oBJLHiS-raca-0HT6-omY8-K6imx7Q'
let AppID = '9d5eccb4ca4a4f97b8297fa73264f550'
let AppKey = '0oBJLHiSraca0HT6omY8K6imx7Q'
// 填入自己 ID、KEY 結束
let GMTString = new Date().toGMTString()
let ShaObj = new jsSHA('SHA-1', 'TEXT')
ShaObj.setHMACKey(AppKey, 'TEXT')
ShaObj.update('x-date: ' + GMTString)
let HMAC = ShaObj.getHMAC('B64')
let Authorization =
'hmac username="' +
AppID +
'", algorithm="hmac-sha1", headers="x-date", signature="' +
HMAC +
'"'
return { Authorization: Authorization, 'X-Date': GMTString }
}
|
C++
|
UTF-8
| 3,073
| 3.421875
| 3
|
[] |
no_license
|
#include "PID_CONTROL.h"
/*
How to use:
The setpoint is the desired reading from your sensor (ie a gyroscope value that reads 90 degrese after a right turn)
The SensorReading is the current value (ie the current gyroscope value)
The OutputVar is the Variable to store or write the output
Kp, Ki, and Kd are constants. To set them, see https://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
MinError is the amount of error that can be tolerated. This needs to be set to avoid error accumulating and causing large response when small ones are needed.
MaxOutput is the maximum value of your output variable. (ie a max motor speed)
MinOutput is assumed to be the opposite of your max output
*/
void PID_CONTROL::PIDLoop(int &Setpoint, int &SensorReading, int Kp, int Ki, int Kd, int MinError, int MaxOutput, int MinOutput)
{
//Read Input and determine the amount error
ErrorAmt = Setpoint - SensorReading;
//The integral is the area under the curve of graphed values
//This keeps track of past error and helps prevent smaller errors as it gets closer to the setpoint
Integral = Integral + ErrorAmt * DELTA_TIME;
//The derivative estimates future error from past error changes
Derivative = (SensorReading - PreviousSensorReading)/DELTA_TIME;
//Output the New Value, ensuring it is inside of the possible values
Output = (Kp * ErrorAmt) + (Ki * Integral) + (Kd * Derivative);
if(Output > MaxOutput)
{
Output = MaxOutput;
}
if(Output < MinOutput)
{
Output = MinOutput;
}
//Ensure the Integral does not grow massive from a small, consistent error
if(Integral < MinIntegralVal)
{
Integral = 0;
}
//Set the previous error, if it need to be set because it is outside of the acceptable parameters
if(ErrorAmt < MinError)
{
PreviousError = 0;
}
else
{
PreviousError = ErrorAmt;
}
PreviousSensorReading = SensorReading;
}
/*How to use: This is a P (Proportional) loop only. This is used when a full PID or PI loop is unnessescary.
The setpoint is the desired reading from your sensor (ie a gyroscope value that reads 90 degrese after a right turn)
The SensorReading is the current value (ie the current gyroscope value)
The OutputVar is the variable to store the output
Kp is a constant. To set it, see https://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
MinError is the amount of error that can be tolerated. This needs to be set to avoid error accumulating and causing large adjustments when small ones are needed.
MaxOutput is the maximum value of your output variable. (ie a max motor speed)
MinOutput is assumed to be the opposite of your max output
*/
void PID_CONTROL::PLoop(int Setpoint, int SensorReading, int OutputVar, int Kp, int MinError, int MaxOutput, int MinOutput)
{
ErrorAmt = Setpoint - SensorReading;
OutputVar = (Kp*ErrorAmt)+Setpoint;
}
|
Markdown
|
UTF-8
| 5,643
| 2.53125
| 3
|
[] |
no_license
|
# 科学网—SCC 2008:我的科研起点 - 王东明的博文
# SCC 2008:我的科研起点 精选
已有 8869 次阅读2014-10-31 22:01|系统分类:[科研笔记](http://blog.sciencenet.cn/home.php?mod=space&do=blog&view=all&uid=1362128&catid=1)|关键词:国际会议,组织工作,科研|[科研](misc.php?mod=tag&id=274), [国际会议](misc.php?mod=tag&id=3152), [组织工作](misc.php?mod=tag&id=151829)
SCC是一个国际会议系列的缩写,其全称是International Conference on Symbolic Computation and Cryptography,主要研讨符号计算中的理论、方法、工具和软件在密码学中的应用。在大大小小的国际学术会议之中,SCC算是新丁,目前仅有三届:
首届(SCC 2008)在中国北京举行:[http://www.cc4cm.org/scc2008/](http://www.cc4cm.org/scc2008/)
第二届(SCC 2010)在英国Egham举行:[http://scc2010.rhul.ac.uk/](http://scc2010.rhul.ac.uk/)
第三届(SCC 2012)在西班牙Castro Urdiales举行:[http://scc2012.unican.es/](http://scc2012.unican.es/)
我不时想起SCC 2008,因为那次会议是我科研事业的起点,它让当时仍觉迷顿的我豁然开朗、茅塞顿开。
2008年的我是直博第一年的懵懂少年,对学术世界充满向往,总觉得科研离我很近也很远:作为一名博士生,我的主要工作是科研,但刚刚离开本科多彩生活的我却对科研的前沿知之甚少,又难觅入门之道。就在我无所适从的时候,导师安排我协助组织SCC 2008,让我负责与会议当地组织有关的各种事宜,于是我瞬间忙碌起来。
忙碌的一天往往有得有失,我既会因为顺利完成海报设计而沾沾自喜,也可能由于邮件漏掉附件而怏怏不乐。所幸的是,我有了更多的机会与导师交流,感受到了他的严谨、缜密和有序,也学到了不少为人处事的道理。时间一天一天地过去了,网站、海报、酒店、餐饮、宴会、交通、通知等等事宜也在我的直接参与下一件一件地完成了。如果说这些锻炼了我的能力的话,也许与国内外学者的接触才是使我豁然开朗、茅塞顿开的关键:我终于有机会近距离地领略到大师的风范,感受到最前沿的科研究竟是什么样子。
在SCC 2008会上,欧洲科学院院士B.Buchberger(ACM Kanellakis奖得主、奥地利开普勒大学教授)就深刻的符号计算理论与方法高谈阔论,而在会下他又与我们这些年轻人亲切交流,展现出极强的亲和力。ACM图灵奖得主A. Shamir(以色列魏茨曼科学研究所教授)以高屋建瓴的方式讨论整个学科的发展趋势,而他如手术刀般敏锐的科研洞察力更是令人折服。他们让我发现,我处在一个开放、合作、友好的环境之中。与会者乐于分享、乐于共同进步、乐于鼓励与提携年轻人。这里似乎没有年龄和背景的差异,有的只是知识的交流和传承。我仿佛看到了思想的河流汇聚于此,又借由参与者传播于世界的各个角落。于是,那个对科研世界向往却知之甚少的我突然抓住了科研世界的特征,也描绘出了心目中学者的轮廓。眼前的奋斗道路愈发清晰,而日后的奋斗目标也逐渐显现。
众多与会者之中有一位最为特殊,那就是我日后博士论文的联合指导导师Jean-Charles Faugère研究员。正是在SCC 2008这次会议上,我结识了身为程序委员会联合主席的他,并最终有幸赴法国巴黎第六大学在他和王老师的共同指导下攻读联合培养博士学位。在我看来,导师犹如博士在科研生命中的父母一般,将其科研操守、科研态度和科研方法都提升到一个全新的高度。遇到好的导师,是博士一生之幸。那么有两位好导师的我,更是坐拥双份的幸运,而其中一份就源于SCC 2008。除了Jean-Charles,我在会议的组织和举行期间还结识了许多专家学者,其中有些老师更是一直以来关心帮助着我,实为我人生中不可或缺的良师益友。
诚然,国际会议的组织耗时耗力,要求组织者事无巨细、随机应变:小到会议代表纸笔的准备,大到特邀报告人的选择与邀请,再加上随时可能出现的突发状况,不说组织者非得有三头六臂也着实相差不多。但一切的辛苦劳神随着会议的举行也慢慢地烟消云散,今日回想起来,沉淀下来最多的还是成就感。后来,凭借着积攒下的宝贵经验,我也逐步更加深入地参与到一些国际会议的组织工作之中,为我自己的科研事业不断地添砖加瓦。
谨以此文致我终将逝去的青春。
SCC 2008会议海报

SCC 2008的三位特邀报告人

Bruno Buchberger教授

Adi Shamir教授

王小云教授
(牟晨琪)
转载本文请联系原作者获取授权,同时请注明本文来自王东明科学网博客。
链接地址:[http://blog.sciencenet.cn/blog-1362128-840164.html](http://blog.sciencenet.cn/blog-1362128-840164.html)
上一篇:[AISC 2006之于我](blog-1362128-836541.html)
下一篇:[我与Hironaka教授的一面之缘](blog-1362128-843445.html)
|
Java
|
UTF-8
| 323
| 1.757813
| 2
|
[] |
no_license
|
package com.redwrench.android.framework;
public interface Game {
public Input getInput();
public FileOps getFileIO();
public Graphics getGraphics();
public Audio getAudio();
public void setScreen(Screen screen);
public void onResume();
public void onPause();
public Screen getStartScreen();
}
|
C#
|
UTF-8
| 1,085
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace odev2
{
public class BinaryTree
{
public string veri;
public int indis;
public BinaryTree sag, sol;
public string isim;
public List<string> s1, s3, s4, s6;
public List<int> s2, s5;
public List<string> h1, h3, h4, h6;
public List<int> h2, h5;
public BinaryTree()
{
s1 = new List<string>();
s3 = new List<string>();
s4 = new List<string>();
s6 = new List<string>();
s2 = new List<int>();
s5 = new List<int>();
h1 = new List<string>();
h3 = new List<string>();
h4 = new List<string>();
h6 = new List<string>();
h2 = new List<int>();
h5 = new List<int>();
sag = null;
sol = null;
}
public override string ToString()
{
return
"isim :" + isim + " ";
}
}
}
|
PHP
|
UTF-8
| 852
| 3.03125
| 3
|
[] |
no_license
|
<h2>Liste des articles</h2>
<?php
$query = $pdo->query("SELECT * FROM article");
// fetchAll retourne tous les résultats d'un coup
$articles = $query->fetchAll();
echo '<ul>'; // unordered list
foreach ($articles as $article) {
echo '<li>' // list item
// titre de l'article dans un lien pour readArticle
.'<a href="index.php?page=readArticle&id='.$article['id'].'">'
.$article['titre'].'</a> - '
// lien d'édition
.'<a href="index.php?page=editArticle&id='.$article['id'].'">'
.'éditer</a> - '
// lien de suppression
.'<a href="index.php?page=deleteArticle&id='.$article['id'].'">'
.'supprimer</a>'
.'</li>';
}
echo '</ul>';
// lien pour ajouter un article
echo '<p><a href="index.php?page=newArticle">Ajouter un article</a></p>';
$query->closeCursor();
|
Markdown
|
UTF-8
| 852
| 2.859375
| 3
|
[] |
no_license
|
java int 类整数的最大值是 2 的 31 次方 - 1 = **2147483648 - 1** = **2147483647**
bai -231——231-1,即-2147483648——2147483647
可以用 **Integer.MAX_VALUE** 表示它,即 int value = Integer.MAX_VALUE;
Integer.MAX_VALUE + 1 = Integer.MIN_VALUE = **-2147483648**
再大的数就要用 long (最大值 2 的 63 次方 - 1 )或者 BigDecimal 表示
前缀和、前缀积也称前缀和数组,前缀积数组。
给一数组A,
前缀和:新建一数组B,数组中每一项B[i]保存A中[0…i]的和;
后缀和:新建一数组B,数组中每一项B[i]保存A中[i…n-1]的和;
前缀积:新建一数组B,数组中每一项B[i]保存A中[0…i]的积;
后缀积:新建一数组B,数组中每一项B[i]保存A中[i…n-1]的积;
前缀和数组比原数组长度+1,前缀和第一项为0
|
Java
|
UTF-8
| 714
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
package com.mprzybylak.minefields.jpa.relationships.onetomany.uni;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Reader {
@Id
private long id;
@OneToMany(
fetch=FetchType.LAZY // eager fetch by default but it can be changed by "fetch" parameter
)
private Collection<Book> books = new ArrayList<>();
public Reader() {
}
public Reader(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void addBook(Book book) {
books.add(book);
}
public Collection<Book> getBooks() {
return books;
}
}
|
C++
|
UTF-8
| 1,868
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
#include <Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{ '0', '1', '2', '3' },
{ '4', '5', '6', '7' },
{ '8', '9', 'A', 'B' },
{ 'C', 'D', 'E', 'F' }
};
byte rowPins[ROWS] = { 9, 8, 7, 6 }; // row pins
byte colPins[COLS] = { 5, 4, 3, 2 }; // column pins
// init keypad object
Keypad myKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup(){
pinMode(8, OUTPUT);
}
void loop(){
char key_getter = myKeypad.getKey();
if (key_getter != NO_KEY){
if (key_getter == '0')
tone(13, 440, 100); // play tone 57 (A4 = 440 Hz)
if (key_getter == '1')
tone(13, 466, 100); // play tone 58 (A#4 = 466 Hz)
if (key_getter == '2')
tone(13, 494, 100); // play tone 59 (B4 = 494 Hz)
if (key_getter == '3')
tone(13, 523, 100); // play tone 60 (C5 = 523 Hz)
if (key_getter == '4')
tone(13, 554, 100); // play tone 61 (C#5 = 554 Hz)
if (key_getter == '5')
tone(13, 587, 100); // play tone 62 (D5 = 587 Hz)
if (key_getter == '6')
tone(13, 622, 100); // play tone 63 (D#5 = 622 Hz)
if (key_getter == '7')
tone(13, 659, 100); // play tone 64 (E5 = 659 Hz)
if (key_getter == '8')
tone(13, 698, 100); // play tone 65 (F5 = 698 Hz)
if (key_getter == '9')
tone(13, 740, 100); // play tone 66 (F#5 = 740 Hz)
if (key_getter == 'A')
tone(13, 784, 100); // play tone 67 (G5 = 784 Hz)
if (key_getter == 'B')
tone(13, 831, 100); // play tone 68 (G#5 = 831 Hz)
if (key_getter == 'C')
tone(13, 880, 100); // play tone 69 (A5 = 880 Hz)
if (key_getter == 'D')
tone(13, 932, 100); // play tone 70 (A#5 = 932 Hz)
if (key_getter == 'E')
tone(13, 988, 100); // play tone 71 (B5 = 988 Hz)
if (key_getter == 'F')
tone(13, 1047, 100); // play tone 72 (C6 = 1047 Hz)
}
}
|
C++
|
UTF-8
| 826
| 3.09375
| 3
|
[] |
no_license
|
#include <unordered_set>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode()
: val(0)
, next(nullptr)
{
}
ListNode(int x)
: val(x)
, next(nullptr)
{
}
ListNode(int x, ListNode* next)
: val(x)
, next(next)
{
}
};
class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums)
{
unordered_set<int> subset(nums.begin(), nums.end());
int res = 0, is_component = 0;
while (head) {
if (subset.count(head->val)) {
is_component = 1;
} else {
res += is_component;
is_component = 0;
}
head = head->next;
}
return res + is_component;
}
};
|
SQL
|
UTF-8
| 536
| 2.640625
| 3
|
[] |
no_license
|
CREATE TABLE [Resource].[Gatherer]
(
[GathererId] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
[ResourceTypeID] INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Range] INT,
[CycleUnits] NVARCHAR(50) NOT NULL,
[CycleTime] NVARCHAR(50) NOT NULL,
[CycleAmount] NVARCHAR(50) NOT NULL,
[SkillID1] INT NOT NULL,
[SkillID2] INT NOT NULL,
[SkillID3] INT NOT NULL,
[SkillID4] INT NOT NULL,
[SkillID5] INT NOT NULL,
[SkillID6] INT NOT NULL,
[SkillID7] INT NOT NULL,
[SkillID8] INT NOT NULL
)
|
Rust
|
UTF-8
| 1,081
| 2.84375
| 3
|
[] |
no_license
|
use std::net::{TcpStream, TcpListener, Ipv4Addr};
use std::thread;
use std::io::Write;
use process;
use serde_json;
pub trait OpServer {
fn ip(&self) -> Ipv4Addr;
fn hostname(&self) -> String;
}
pub struct TcpServer<'a> {
listener: &'a TcpListener,
}
impl<'a> OpServer for TcpServer<'a> {
fn ip(&self) -> Ipv4Addr {
Ipv4Addr::new(127, 0, 0, 1)
}
fn hostname(&self) -> String {
"localhost".to_owned()
}
}
fn handle_client(stream: &mut TcpStream) {
stream.write(serde_json::to_string(&process::ps().unwrap()).unwrap().as_bytes());
// stream.write(&[1]);
}
impl<'a> TcpServer<'a> {
pub fn new(l: &'a TcpListener) -> TcpServer {
TcpServer { listener: l }
}
pub fn serve(&self) {
for stream in self.listener.incoming() {
match stream {
Ok(mut s) => {
// s.write(b"hello, world!");
thread::spawn(move || { handle_client(&mut s); });
}
Err(e) => println!("{:?}", e),
}
}
}
}
|
C#
|
UTF-8
| 3,886
| 2.703125
| 3
|
[] |
no_license
|
using UnityEngine;
using System.Collections;
using UnityEditor;
/// <summary>
/// Author: Mauricio Galvez
/// Date Created: 30/03/15
/// Last Edited: 30/03/15
/// Armor Creator - Editor Window used to create Armor
/// </summary>
public class ArmorCreator : EditorWindow
{
public string Name; // Name value
public int Defense; // Defense points value
public GameObject Model; // Armor 3D Model
/// ===================
/// INIT
/// <summary>
/// Init this instance.
/// </summary>
/// ===================
[MenuItem("Create/New Armor... %#a")]
static void Init()
{
ArmorCreator window = (ArmorCreator) EditorWindow.GetWindow(typeof(ArmorCreator));
window.Show ();
}
/// ====================
/// ON GUI
/// <summary>
/// Updates window
/// </summary>
/// ====================
public void OnGUI()
{
GUILayout.Label ("Create New Armor", EditorStyles.boldLabel);
// Obtain Model from property field
GUILayout.BeginHorizontal();
GUILayout.Label("3D Model");
Model = (GameObject)EditorGUILayout.ObjectField(Model, typeof(GameObject), true);
GUILayout.EndHorizontal();
// Obtain Name from textfield
Name= EditorGUILayout.TextField("Name", Name);
// Obtain damage from int slider
Defense = EditorGUILayout.IntSlider ("Defense",Defense,0,100);
ProgressBar (Defense/ 100.0f, "Defense");
// Check if Create Armor weapon has been pressed
if(GUILayout.Button("Create Armor"))
{
// check if a model has not been provided
if (!Model)
{
EditorUtility.DisplayDialog("Not Model Provided", "You must provide a 3D model to create an armor!", "Ok");
return;
}
// Assign localpath
string LocalPath = "Assets/Resources/Armor/"+ Name + ".prefab";
//----------
// CHECK IF WEAPON ALREADY EXISTS
//-----------
// create instance of game object
GameObject prefab = null;
// invoke prefab as a gameobject
prefab = (GameObject) AssetDatabase.LoadAssetAtPath(LocalPath, typeof(GameObject));
// check if prefab exists
if (prefab)
{
// If it exists, prompt message
if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes","No"))
OverrideArmor (prefab);
}
else
// Create new weapon
CreateNewArmor(LocalPath);
}
}
/// ====================
/// CREATE NEW ARMOR
/// <summary>
/// Creates the new armor.
/// </summary>
/// <param name="path">Path. Path where prefab will be stored</param>
/// <param name="name">Name. Name of armor</param>
/// <param name="defense">defense. defense of armor</param>
/// <param name="model">Model. GameObject of armor</param>
/// ====================
void CreateNewArmor(string path)
{
// Add ArmorData to gameObject /
ArmorData armor = Model.AddComponent<ArmorData>();
armor.Name = Name;
armor.DefensePoints = Defense;
// Create an Empty Prefab
Object prefab = PrefabUtility.CreatePrefab(path,Model);
}
/// ====================
/// OVERRIDE armor
/// <summary>
/// Overrides the armor.
/// </summary>
/// <param name="prefab">Prefab. Existent prefab of armor</param>
/// <param name="name">Name. New name of armor</param>
/// <param name="defense">defense. New defense value</param>
/// <param name="model">Model. New Model</param>
/// ====================
void OverrideArmor(GameObject prefab)
{
ArmorData armor = prefab.GetComponent<ArmorData>();
if(armor)
{
armor.Name = Name;
armor.DefensePoints = Defense;
}
}
// ====================
//Custom GUILayout progress bar.
// ====================
void ProgressBar (float value, string label)
{
// Get a rect for the progress bar using the same margins as a textfield:
Rect rect = GUILayoutUtility.GetRect (18, 18, "TextField");
EditorGUI.ProgressBar (rect, value, label);
EditorGUILayout.Space ();
}
}
|
PHP
|
UTF-8
| 10,458
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* This file is part of cyberspectrum/i18n-contao.
*
* (c) 2018 CyberSpectrum.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package cyberspectrum/i18n-contao
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @copyright 2018 CyberSpectrum.
* @license https://github.com/cyberspectrum/i18n-contao/blob/master/LICENSE MIT
* @filesource
*/
declare(strict_types = 1);
namespace CyberSpectrum\I18N\Contao;
use CyberSpectrum\I18N\Contao\Extractor\ExtractorInterface;
use CyberSpectrum\I18N\Contao\Extractor\MultiStringExtractorInterface;
use CyberSpectrum\I18N\Contao\Mapping\MappingInterface;
use CyberSpectrum\I18N\Dictionary\WritableDictionaryInterface;
use CyberSpectrum\I18N\Exception\NotSupportedException;
use CyberSpectrum\I18N\TranslationValue\TranslationValueInterface;
use CyberSpectrum\I18N\TranslationValue\WritableTranslationValueInterface;
use Doctrine\DBAL\Connection;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
/**
* This provides access to a Contao table.
*/
class ContaoTableDictionary implements WritableDictionaryInterface
{
use LoggerAwareTrait;
/**
* The table name.
*
* @var string
*/
private $tableName;
/**
* The source language.
*
* @var string
*/
private $sourceLanguage;
/**
* The target language.
*
* @var string
*/
private $targetLanguage;
/**
* Connection.
*
* @var Connection
*/
private $connection;
/**
* The page map.
*
* @var MappingInterface
*/
private $idMap;
/**
* The extractors.
*
* @var ExtractorInterface[]
*/
private $extractors = [];
/**
* Create a new instance.
*
* @param string $tableName The table name.
* @param string $sourceLanguage The source language.
* @param string $targetLanguage The target language.
* @param Connection $connection The database connection.
* @param MappingInterface $idMap The page map.
* @param ExtractorInterface[] $extractors The extractors.
*
* @throws \InvalidArgumentException When one of the passed extractors does not implement the interface.
*/
public function __construct(
string $tableName,
string $sourceLanguage,
string $targetLanguage,
Connection $connection,
MappingInterface $idMap,
array $extractors
) {
$this->tableName = $tableName;
$this->sourceLanguage = $sourceLanguage;
$this->targetLanguage = $targetLanguage;
$this->connection = $connection;
$this->idMap = $idMap;
$this->setLogger(new NullLogger());
foreach ($extractors as $extractor) {
if (!$extractor instanceof ExtractorInterface) {
throw new \InvalidArgumentException('Object is not an extractor ' . \get_class($extractor));
}
$this->extractors[$extractor->name()] = $extractor;
}
}
/**
* {@inheritDoc}
*/
public function keys(): \Traversable
{
foreach ($this->idMap->sourceIds() as $sourceId) {
if (!$this->idMap->hasTargetFor($sourceId)) {
continue;
}
foreach ($this->getKeysForSource($sourceId) as $propKey) {
yield $sourceId . '.' . $propKey;
}
}
}
/**
* {@inheritDoc}
*
* @throws NotSupportedException When the key is in bad format or the extractor can not be found.
*/
public function get(string $key): TranslationValueInterface
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
throw new NotSupportedException(
$this,
'Key ' . $key . ' is in bad format (need: [id].[prop-name])'
);
}
// Format is: [id].propname
if (null === ($extractor = $this->getExtractor($chunks[1]))) {
throw new NotSupportedException(
$this,
'Key "' . $key . '" is not supported (no extractor for "' . $chunks[1] . '" found)'
);
}
$sourceId = (int) $chunks[0];
$targetId = $this->idMap->getTargetIdFor($sourceId);
return $this->createValueReader($sourceId, $targetId, $extractor, implode('.', \array_slice($chunks, 2)));
}
/**
* {@inheritDoc}
*/
public function has(string $key): bool
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
return false;
}
// Format is: [id].propname
if (null === $this->getExtractor($chunks[1])) {
return false;
}
return $this->idMap->hasTargetFor((int) $chunks[0]);
}
/**
* {@inheritDoc}
*/
public function getSourceLanguage(): string
{
return $this->sourceLanguage;
}
/**
* {@inheritDoc}
*/
public function getTargetLanguage(): string
{
return $this->targetLanguage;
}
/**
* {@inheritDoc}
*
* @throws NotSupportedException Adding is not supported by this class.
*/
public function add(string $key): WritableTranslationValueInterface
{
throw new NotSupportedException(
$this,
'Can not add key to Contao database: ' . $key
);
}
/**
* {@inheritDoc}
*
* @throws NotSupportedException Removing is not supported by this class.
*/
public function remove(string $key): void
{
throw new NotSupportedException(
$this,
'Can not remove key from Contao database: ' . $key
);
}
/**
* {@inheritDoc}
*
* @throws NotSupportedException When the key is in bad format or the extractor can not be found.
*/
public function getWritable($key): WritableTranslationValueInterface
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
throw new NotSupportedException($this, 'Key ' . $key . ' is in bad format (need: [id].[prop-name])');
}
// Format is: [id].propname
if (null === ($extractor = $this->getExtractor($chunks[1]))) {
throw new NotSupportedException($this, 'Key ' . $key . ' is not supported (no extractor found)');
}
$sourceId = (int) $chunks[0];
$targetId = $this->idMap->getTargetIdFor($sourceId);
return $this->createValueWriter($sourceId, $targetId, $extractor, implode('.', \array_slice($chunks, 2)));
}
/**
* Retrieve connection.
*
* @return Connection
*/
public function getConnection(): Connection
{
return $this->connection;
}
/**
* Fetch a row.
*
* @param int $idNumber The id to fetch.
*
* @return array
*/
public function getRow(int $idNumber): array
{
return (array) $this->getConnection()->createQueryBuilder()
->select('*')
->from($this->tableName)
->where('id=:id')
->setParameter('id', $idNumber)
->setMaxResults(1)
->execute()
->fetch(\PDO::FETCH_ASSOC);
}
/**
* Fetch a row.
*
* @param int $idNumber The id to fetch.
* @param array $values The row values to update.
*
* @return void
*/
public function updateRow(int $idNumber, array $values): void
{
$this->connection->update($this->tableName, $values, ['id' => $idNumber]);
}
/**
* Get the keys for the source id.
*
* @param int $sourceId The source id.
*
* @return \Traversable|string[]
*
* @throws \InvalidArgumentException When the extractor is unknown.
*/
protected function getKeysForSource(int $sourceId): \Traversable
{
$row = $this->getRow($sourceId);
foreach ($this->extractors as $extractor) {
switch (true) {
case $extractor instanceof MultiStringExtractorInterface:
foreach ($extractor->keys($row) as $key) {
yield $extractor->name() . '.' . $key;
}
break;
case $extractor instanceof ExtractorInterface:
if ($extractor->supports($row)) {
yield $extractor->name();
}
break;
default:
throw new \InvalidArgumentException('Unknown extractor type ' . \get_class($extractor));
}
}
}
/**
* Try to get the extractor for a property path.
*
* @param string $propName The property path.
*
* @return ExtractorInterface|null
*/
protected function getExtractor(string $propName): ?ExtractorInterface
{
return ($this->extractors[$propName] ?? null);
}
/**
* Create a value reader instance.
*
* @param int $sourceId The source id.
* @param int $targetId The target id.
* @param ExtractorInterface $extractor The extractor to use.
* @param string $trail The trailing sub path.
*
* @return TranslationValueInterface
*/
protected function createValueReader(
int $sourceId,
int $targetId,
ExtractorInterface $extractor,
string $trail
): TranslationValueInterface {
return new TranslationValue($this, $sourceId, $targetId, $extractor, $trail);
}
/**
* Create a value writer instance.
*
* @param int $sourceId The source id.
* @param int $targetId The target id.
* @param ExtractorInterface $extractor The extractor to use.
* @param string $trail The trailing sub path.
*
* @return WritableTranslationValueInterface
*/
protected function createValueWriter(
int $sourceId,
int $targetId,
ExtractorInterface $extractor,
string $trail
): WritableTranslationValueInterface {
return new WritableTranslationValue($this, $sourceId, $targetId, $extractor, $trail);
}
}
|
Java
|
UTF-8
| 8,384
| 1.75
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2004 Anite - Central Government Division
* http://www.anite.com/publicsector
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.anite.antelope;
import org.apache.fulcrum.security.GroupManager;
import org.apache.fulcrum.security.PermissionManager;
import org.apache.fulcrum.security.RoleManager;
import org.apache.fulcrum.security.SecurityService;
import org.apache.fulcrum.security.UserManager;
import org.apache.fulcrum.security.entity.Group;
import org.apache.fulcrum.security.entity.Permission;
import org.apache.fulcrum.security.entity.Role;
import org.apache.fulcrum.security.entity.User;
import org.apache.fulcrum.security.model.dynamic.DynamicModelManager;
import org.apache.fulcrum.testcontainer.BaseUnitTest;
import org.apache.turbine.util.TurbineConfig;
import com.anite.antelope.security.UserGroupPermissionsHelper;
import com.anite.antelope.utils.AntelopeConstants;
/**
* This in a absract class the will build up a set of users/groups/roles and
* premission for Antelope.
*
* @author <a href="mailTo:michael.jones@anite.com">Michael.Jones </a>
*
*/
public abstract class AbstractCreateUsersTest extends BaseUnitTest {
private static final String BASIC = "basic";
private static final String ANTELOPE = "antelope";
private static final String SYSTEMACCESS = "systemAccess";
/**
* @param arg0
*/
public AbstractCreateUsersTest(String arg0) {
super(arg0);
// Initialise Fake Turbine so it can resolve Avalon
// In theory calling this twice should only initialise once
TurbineConfig config = null;
config = new TurbineConfig("./src/webapp/", "WEB-INF/conf/TurbineResources.properties");
config.initialize();
}
protected SecurityService securityService;
protected DynamicModelManager modelManager;
protected UserManager userManager;
protected GroupManager groupManager;
protected RoleManager roleManager;
protected PermissionManager permissionManager;
public void testCreateUsers() throws Exception {
User user;
Group group;
Role role;
Permission permission;
// build up a simple dynanic user permission model
modelManager = (DynamicModelManager) securityService.getModelManager();
// get all the managers
userManager = securityService.getUserManager();
groupManager = securityService.getGroupManager();
roleManager = securityService.getRoleManager();
permissionManager = securityService.getPermissionManager();
// Add all the permissions
permission = permissionManager
.getPermissionInstance(AntelopeConstants.PERMISSION_ADD_USER);
permissionManager.addPermission(permission);
permission = permissionManager
.getPermissionInstance(AntelopeConstants.PERMISSION_EDIT_PERMISSIONS);
permissionManager.addPermission(permission);
permission = permissionManager
.getPermissionInstance(AntelopeConstants.PERMISSION_CHANGE_PASSWORD);
permissionManager.addPermission(permission);
permission = permissionManager.getPermissionInstance("security_add");
permissionManager.addPermission(permission);
permission = permissionManager.getPermissionInstance("security_edit");
permissionManager.addPermission(permission);
permission = permissionManager.getPermissionInstance("security_delete");
permissionManager.addPermission(permission);
permission = permissionManager
.getPermissionInstance(AntelopeConstants.PERMISSION_SYSTEM_ACCESS);
permissionManager.addPermission(permission);
// Add all roles
role = roleManager.getRoleInstance(AntelopeConstants.ROLE_USER_ADMIN);
roleManager.addRole(role);
role = roleManager.getRoleInstance("security");
roleManager.addRole(role);
role = roleManager.getRoleInstance(AntelopeConstants.ROLE_USER_BASIC);
roleManager.addRole(role);
role = roleManager.getRoleInstance(SYSTEMACCESS);
roleManager.addRole(role);
// Add all Groups
UserGroupPermissionsHelper.getInstance().createOrFetchGroup(
AntelopeConstants.GROUP_ADMIN);
UserGroupPermissionsHelper.getInstance().createOrFetchGroup(
AntelopeConstants.GROUP_BASIC);
UserGroupPermissionsHelper.getInstance().createOrFetchGroup("test2");
UserGroupPermissionsHelper.getInstance().createOrFetchGroup("test3");
// add all users
UserGroupPermissionsHelper.getInstance().createUser(ANTELOPE, "test");
UserGroupPermissionsHelper.getInstance().createUser(BASIC, "test");
// set up the stutcuture
// add perms to roles
modelManager
.grant(
roleManager
.getRoleByName(AntelopeConstants.ROLE_USER_ADMIN),
permissionManager
.getPermissionByName(AntelopeConstants.PERMISSION_ADD_USER));
modelManager
.grant(
roleManager
.getRoleByName(AntelopeConstants.ROLE_USER_ADMIN),
permissionManager
.getPermissionByName(AntelopeConstants.PERMISSION_EDIT_PERMISSIONS));
modelManager
.grant(
roleManager
.getRoleByName(AntelopeConstants.ROLE_USER_ADMIN),
permissionManager
.getPermissionByName(AntelopeConstants.PERMISSION_CHANGE_PASSWORD));
modelManager
.grant(
roleManager
.getRoleByName(AntelopeConstants.ROLE_USER_BASIC),
permissionManager
.getPermissionByName(AntelopeConstants.PERMISSION_CHANGE_PASSWORD));
modelManager.grant(roleManager.getRoleByName("security"),
permissionManager.getPermissionByName("security_add"));
modelManager.grant(roleManager.getRoleByName("security"),
permissionManager.getPermissionByName("security_edit"));
modelManager.grant(roleManager.getRoleByName("security"),
permissionManager.getPermissionByName("security_delete"));
modelManager
.grant(
roleManager.getRoleByName(SYSTEMACCESS),
permissionManager
.getPermissionByName(AntelopeConstants.PERMISSION_SYSTEM_ACCESS));
// add roles to groups
modelManager.grant(groupManager
.getGroupByName(AntelopeConstants.GROUP_ADMIN), roleManager
.getRoleByName(AntelopeConstants.ROLE_USER_ADMIN));
modelManager.grant(groupManager
.getGroupByName(AntelopeConstants.GROUP_ADMIN), roleManager
.getRoleByName("security"));
modelManager.grant(groupManager
.getGroupByName(AntelopeConstants.GROUP_BASIC), roleManager
.getRoleByName(AntelopeConstants.ROLE_USER_BASIC));
modelManager.grant(groupManager
.getGroupByName(AntelopeConstants.GROUP_BASIC), roleManager
.getRoleByName(SYSTEMACCESS));
modelManager.grant(groupManager
.getGroupByName(AntelopeConstants.GROUP_ADMIN), roleManager
.getRoleByName(SYSTEMACCESS));
// add groups to users
modelManager.grant(userManager.getUser(ANTELOPE), groupManager
.getGroupByName(AntelopeConstants.GROUP_ADMIN));
modelManager.grant(userManager.getUser(BASIC), groupManager
.getGroupByName(AntelopeConstants.GROUP_BASIC));
}
}
|
PHP
|
UTF-8
| 1,800
| 2.59375
| 3
|
[] |
no_license
|
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* [all description]
*
* @return [type] [description]
*/
public function all()
{
return User::all();
}
/**
* Create user record
*
*
*/
protected function create()
{
return view('user.create');
}
/**
* Edit User record
*
* @param Request $request [description]
* @return [type] [description]
*/
protected function edit()
{
$user = User::find($id);
return view('user.edit');
}
/**
* Update User record
*
* @param Request $request [description]
* @return [type] [description]
*/
protected function update()
{
$user = User::find($id);
$user->update($request->all());
return back();
}
/**
* register via Ajax
*
* @param Request $request [description]
* @return [type] [description]
*/
protected function register(Request $request)
{
User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
return response()->json(['success' => true, 'message' => 'User Created!']);
}
/**
*
* //
*
*/
public function destroy($id)
{
$user = User::find($id);
$user->delete();
if(request()->expectsJson()) {
return response(['status' => 'User removed']);
}
return back();
}
}
|
C++
|
UTF-8
| 821
| 3.078125
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Car.cpp
* Author: Administrator
*
* Created on April 28, 2016, 8:20 AM
*/
#include "Car.h"
Car::Car(int year, string make) {
this->year = year;
this->make = make;
this->speed = 0;
}
//Car::Car(const Car& orig) {
//}
//
//Car::~Car() {
//}
string Car::getMake() const {
return make;
}
int Car::getSpeed() const {
return speed;
}
int Car::getYear() const {
return year;
}
void Car::brake() {
if (speed > 0 && speed <= 5)
speed = 0;
else if (speed > 5)
speed -= 5;
else
cout << "ths car has stop" << endl;
}
void Car::setSpeed(int s){
speed =s;
}
|
Markdown
|
UTF-8
| 786
| 2.546875
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Module Info Dialog Box
description: "The Module Info dialog box displays all the kernel mode modules loaded on the system from which the event log trace was gathered."
ms.date: 05/10/2022
---
# Module Info Dialog Box
The **Module Info** dialog box displays all the kernel mode modules loaded on the system from which the event log trace was gathered. Its context is alphabetical to help the user quickly locate module versions. This is useful when investigating known issues on known module versions.
The information displayed in the dialog's list takes the form module name, followed by the version, followed by the friendly name and corporation. Video drivers are fairly easy to find in this list.

|
PHP
|
UTF-8
| 2,587
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Base\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;
use App\Http\Base\Traits\ModuleTrait;
/**
* ModuleServiceProvider
*
* The service provider for the modules. After being registered
* it will make sure that each of the modules are properly loaded
* i.e. with their routes, views etc.
*
* @author Saniyat Hossain <saniyat1000@gmail.com>
* @package App\Base\Providers
*/
class ModulesServiceProvider extends ServiceProvider
{
use ModuleTrait;
/**
* boot
*
* Will make sure that the required modules have been fully loaded
*
* @return void
*/
public function boot(): void
{
$this->loadModules();
}
/**
* register
*
* @return void
*/
public function register()
{
//
}
/**
* loadModules
*
* @return void
*/
private function loadModules(): void
{
// dd($this->app->router);
(object) $router = $this->app->router;
(array) $modules = config('module.modules');
// If modules array is not empty then for each modules, require_once routes and views
if (!empty($modules)):
(string) $moduleNamespace = config('module.namespace');
(string) $modulesDir = config('module.directory');
(string) $modulesDirectory = sprintf('%s%s%s', base_path(), $this->ds(), $modulesDir);
(array) $noPrefix = config('module.no-prefix');
foreach ($modules as $module):
// Load the routes for each of the modules
(string) $routeDirectory = sprintf('%s%s%s%sRoutes', $modulesDirectory, $this->ds(), $module, $this->ds());
if (is_dir($routeDirectory)):
(array) $routeFiles = glob(sprintf('%s%s*.%s', $routeDirectory, $this->ds(), $this->fileExtension));
if (!empty($routeFiles)):
(string) $controllerNamespace = sprintf('%s%s%s%sControllers', $moduleNamespace, $this->ns(), $module, $this->ns());
foreach ($routeFiles as $routeFile):
(array) $routeGroup = [
// 'middleware' => ['web'],
'namespace' => $controllerNamespace
];
if (!in_array($module, $noPrefix)):
$routeGroup['prefix'] = strtolower($module);
endif;
$router->group($routeGroup, function() use($routeFile) {
$this->loadRoutesFrom($routeFile);
});
endforeach;
endif;
endif;
(string) $viewsDirectory = sprintf('%s%s%s%sViews', $modulesDirectory, $this->ds(), $module, $this->ds());
// Load the views
if (is_dir($viewsDirectory)):
$this->loadViewsFrom($viewsDirectory, $module);
endif;
endforeach;
endif;
}
}
|
TypeScript
|
UTF-8
| 2,251
| 3.8125
| 4
|
[] |
no_license
|
/**
* https://leetcode.com/problems/largest-rectangle-in-histogram/
*/
export function largestRectangleArea(heights: number[]): number {
if (!heights.length) {
return 0
}
const stack = [0]
let maxArea = 0
for (let index = 1; index < heights.length; index++) {
if (heights[index] > heights[stack[stack.length - 1]]) {
stack.push(index)
} else {
while (
stack.length > 0 &&
heights[stack[stack.length - 1]] > heights[index]
) {
const height = heights[stack.pop()]
const area =
height *
(stack.length === 0 ? index : index - stack[stack.length - 1] - 1)
maxArea = Math.max(maxArea, area)
}
stack.push(index)
}
}
while (stack.length > 0) {
const height = heights[stack.pop()]
const area =
height *
(stack.length === 0
? heights.length
: heights.length - stack[stack.length - 1] - 1)
maxArea = Math.max(maxArea, area)
}
return maxArea
}
/**
* nlogn
*/
function largestRectangleAreaNLogN(heights: number[]): number {
if (!heights.length) {
return 0
}
function largestRectangle(start: number, end: number): number {
console.log(start, end)
if (start < 0 || end >= heights.length || start > end) {
return 0
}
if (start === end) {
return heights[start]
}
let min = heights[start]
let minIndex = start
for (let index = start + 1; index <= end; index++) {
if (min > heights[index]) {
min = heights[index]
minIndex = index
}
}
return Math.max(
min * (end - start + 1),
largestRectangle(start, minIndex - 1),
largestRectangle(minIndex + 1, end),
)
}
return largestRectangle(0, heights.length - 1)
}
/**
* n^2
*/
function largestRectangleAreaN2(heights: number[]): number {
if (!heights.length) {
return 0
}
let maxResult = heights[0]
for (let i = 1; i < heights.length; i++) {
let max = heights[i]
let minValue = heights[i]
for (let j = i - 1; j >= 0; j--) {
minValue = Math.min(minValue, heights[j])
max = Math.max(max, minValue * (i - j + 1))
}
maxResult = Math.max(max, maxResult)
}
return maxResult
}
|
JavaScript
|
UTF-8
| 5,514
| 2.71875
| 3
|
[] |
no_license
|
var container;
var camera, scene, renderer, controls;
var clock = new THREE.Clock();
var cubes= [];
var objectURL;
var buffer;
initDragDrop();
init();
animate();
function loadSample(url) {
var contextClass = (window.AudioContext ||
window.webkitAudioContext ||
window.mozAudioContext ||
window.oAudioContext ||
window.msAudioContext);
if (contextClass) {
// Web Audio API is available.
var context = new contextClass();
} else {
// Web Audio API is not available. Ask the user to use a supported browser.
}
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(theBuffer) {
buffer = theBuffer;
});
}
request.send();
}
function initDragDrop(){
// DragAndDrop
var holder = document.getElementById('holder');
holder.ondragover = function () {
this.className = 'hover';
return false;
};
holder.ondragend = function () {
this.className = '';
return false;
};
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0];
var reader = new FileReader(file);
reader.onload = function (event) {
// Load music ds player
document.getElementById("holder").innerHTML = file.name;
var player = document.getElementById("player");
objectURL = window.URL.createObjectURL(file);
player.src = objectURL;
player.load();
loadSample(objectURL);
};
reader.readAsDataURL(file);
return false;
};
}
function init() {
// Scene
renderer = new THREE.WebGLRenderer({ antialias: true, clearColor: 0x000000, clearAlpha: 1 });
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 0, 200, 500 );
controls = new THREE.FirstPersonControls( camera );
controls.movementSpeed = 50;
controls.lookSpeed = 0.2;
scene = new THREE.Scene();
scene.position.set( 0, 200, 0 );
camera.lookAt(scene.position);
controls.target.x = scene.position.x ;
controls.target.y = scene.position.y ;
controls.target.z = scene.position.z ;
//Horizontal Grid
var lineH_material = new THREE.LineBasicMaterial( { color: 0x303030 } );
var geometry = new THREE.Geometry();
var step = 10;
for ( var i = 0; i <= 40; i ++ ) {
geometry.vertices.push( new THREE.Vector3( - 200, 0, i * step - 200 ) );
geometry.vertices.push( new THREE.Vector3( 200, 0, i * step - 200 ) );
geometry.vertices.push( new THREE.Vector3( i * step - 200, 0, -200 ) );
geometry.vertices.push( new THREE.Vector3( i * step - 200, 0, 200 ) );
}
var line = new THREE.Line( geometry, lineH_material, THREE.LinePieces );
scene.add( line );
//Vertical Grid
var lineV_material = new THREE.LineBasicMaterial( { color: 0x303030 } );
var geometry = new THREE.Geometry();
var step = 10;
for ( var i = 0; i <= 40; i ++ ) {
geometry.vertices.push( new THREE.Vector3( -200, i * step , 0 ) );
geometry.vertices.push( new THREE.Vector3(200, i * step , 0 ) );
geometry.vertices.push( new THREE.Vector3( i * step - 200, 0, 0 ) );
geometry.vertices.push( new THREE.Vector3( i * step - 200, 400, 0 ) );
}
var line = new THREE.Line( geometry, lineV_material, THREE.LinePieces );
scene.add( line );
//Triangle base
var triangle_material = new THREE.LineBasicMaterial( { color: 0x909090 } );
var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3(-200, 0 , 0) );
geometry.vertices.push( new THREE.Vector3( 200, 400, 0 ) );
geometry.vertices.push( new THREE.Vector3( 200, 400, 0 ) );
geometry.vertices.push( new THREE.Vector3(200, 0, 0 ) );
geometry.vertices.push( new THREE.Vector3(200, 0, 0 ) );
geometry.vertices.push( new THREE.Vector3(-200, 0, 0 ) );
var line = new THREE.Line( geometry, triangle_material, THREE.LinePieces );
scene.add( line );
//Cube
var geometry = new THREE.CubeGeometry( 50, 50, 50 );
var texture = THREE.ImageUtils.loadTexture( 'img/crate.gif' );
texture.anisotropy = renderer.getMaxAnisotropy();
var material = new THREE.MeshBasicMaterial( { map: texture } );
mesh = new THREE.Mesh( geometry, material );
mesh.position.y = 100;
mesh.position.z = 100;
scene.add( mesh );
cubes.push( mesh );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
alert(buffer.length);
}
function animate() {
requestAnimationFrame( animate );
var timer = 0.0005 * Date.now();
cubes[0].position.x = Math.cos( timer ) * 100;
cubes[0].rotation.z = Math.sin( timer )*5;
cubes[0].rotation.y = Math.cos( timer )*5;
render();
}
function render() {
controls.update( clock.getDelta() );
renderer.render( scene, camera );
}
|
Markdown
|
UTF-8
| 837
| 3.46875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
###Synopsis
`#include <stdio.h>`
`int fgetpos(FILE *stream, fpos_t *pos);`
###Description
The function gets the current file position of the <u>stream</u> and writes it to <u>pos</u>.
Arguments:
<u>stream</u> - the stream to be examined,
<u>pos</u> - a pointer to an object, in which the current file position of the <u>stream</u> is stored.
###Return value
The function returns `0` on success, otherwise it returns `-1` and sets `errno` to indicate the type of error.
###Errors
[`EBADF`] The file descriptor underlying stream is not valid.
[`EOVERFLOW`] The current value of the file position cannot be represented correctly in an object of type `fpos_t`.
[`ESPIPE`] The file descriptor underlying stream is associated with a pipe, FIFO, or socket.
###Implementation tasks
* Implement the `fgetpos()` function.
|
SQL
|
UTF-8
| 11,100
| 3.828125
| 4
|
[] |
no_license
|
--
--DROP TABLE IF EXISTS "IBF-pipeline-output".dashboard_calculated_affected_adm3;
--select cast('ZMB' as varchar) as country_code
-- ,*
-- ,cattle_affected * 1 +
-- goat_affected * 0.1 +
-- sheep_affected * 0.1 +
-- pig_affected * 0.28 +
-- chicken_affected * 0.01
-- as livestock_affected
----INTO "IBF-pipeline-output".dashboard_calculated_affected_adm3
--from (
--select pcode
-- ,date
-- ,current_prev
-- ,lead_time
-- ,sum(case when exposure_class = 'population' then affected end) as population_affected
-- ,sum(case when exposure_class = 'chicken' then affected end) as chicken_affected
-- ,sum(case when exposure_class = 'cattle' then affected end) as cattle_affected
-- ,sum(case when exposure_class = 'goat' then affected end) as goat_affected
-- ,sum(case when exposure_class = 'pig' then affected end) as pig_affected
-- ,sum(case when exposure_class = 'sheep' then affected end) as sheep_affected
-- ,sum(case when exposure_class = 'cropland' then affected end) as cropland_affected
--from (
-- SELECT source as exposure_class
-- , case when length(cast(district as varchar)) = 8 then '0' || cast(district as varchar) else cast(district as varchar) end as pcode
-- , t0.date
-- , case when date_part('day',age(current_date,to_date(t0.date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
-- , '3-day' as lead_time
-- , case when sum = '--' then 0
-- when t1b.fc_trigger = 0 then 0
-- else cast(sum as float)
-- end as affected
-- , t1b.fc_trigger
-- FROM "IBF-pipeline-output".calculated_affected_short t0
-- left join "IBF-static-input".pcode_mapping_wards_new_distcode t1a
-- on t0.district = t1a.pcode
-- left join "IBF-pipeline-output".dashboard_forecast_per_district t1b
-- on case when length(cast(t1a.pcode_level2_new as varchar)) = 3 then '0' || cast(t1a.pcode_level2_new as varchar) else cast(t1a.pcode_level2_new as varchar) end = t1b.pcode
-- and t1b.lead_time = '3-day'
-- and t0.date = t1b.date
-- where to_date(t0.date,'yyyy-mm-dd') >= current_date - 1
--
-- UNION ALL
--
-- SELECT source as exposure_class
-- , case when length(cast(district as varchar)) = 8 then '0' || cast(district as varchar) else cast(district as varchar) end as pcode
-- , t0.date
-- , case when date_part('day',age(current_date,to_date(t0.date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
-- , '7-day' as lead_time
-- , case when sum = '--' then 0
-- when t1b.fc_trigger = 0 then 0
-- else cast(sum as float)
-- end as affected
-- , t1b.fc_trigger
-- select *
-- FROM "IBF-pipeline-output".calculated_affected_long t0
-- left join "IBF-static-input".pcode_mapping_wards_new_distcode t1a
-- on t0.district = t1a.pcode
-- left join "IBF-pipeline-output".dashboard_forecast_per_district t1b
-- on case when length(cast(t1a.pcode_level2_new as varchar)) = 3 then '0' || cast(t1a.pcode_level2_new as varchar) else cast(t1a.pcode_level2_new as varchar) end = t1b.pcode
-- and t1b.lead_time = '7-day'
-- and t0.date = t1b.date
-- where to_date(t0.date,'yyyy-mm-dd') >= current_date - 1
-- ) aa
--group by 1,2,3,4
--) bb
--;
DROP TABLE IF EXISTS "IBF-pipeline-output".dashboard_calculated_affected_adm2;
select *
,cattle_affected * 1 +
goat_affected * 0.1 +
sheep_affected * 0.1 +
pig_affected * 0.28 +
chicken_affected * 0.01
as livestock_affected
INTO "IBF-pipeline-output".dashboard_calculated_affected_adm2
from (
select country_code
,pcode
,date
,current_prev
,lead_time
,sum(case when exposure_class = 'population' then affected end) as population_affected
,sum(case when exposure_class = 'chicken' then affected end) as chicken_affected
,sum(case when exposure_class = 'cattle' then affected end) as cattle_affected
,sum(case when exposure_class = 'goat' then affected end) as goat_affected
,sum(case when exposure_class = 'pig' then affected end) as pig_affected
,sum(case when exposure_class = 'sheep' then affected end) as sheep_affected
,sum(case when exposure_class = 'cropland' then affected end) as cropland_affected
from (
SELECT country_code
, source as exposure_class
, case when length(cast(district as varchar)) = 8 then '0' || cast(district as varchar) else cast(district as varchar) end as pcode
, t0.date
, case when date_part('day',age(current_date,to_date(t0.date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
, '3-day' as lead_time
, case when sum = '--' then 0
when t1.fc_trigger = 0 then 0
else cast(sum as float)
end as affected
, t1.fc_trigger
FROM "IBF-pipeline-output".calculated_affected_short t0
-- left join "IBF-pipeline-output".pcode_mapping_wards_new_distcode t1a
-- on t0.district = t1a.pcode
left join "IBF-pipeline-output".dashboard_forecast_per_district t1
on case when length(cast(t0.district as varchar)) = 3 then '0' || cast(t0.district as varchar) else cast(t0.district as varchar) end = t1.pcode
and t1.lead_time = '3-day'
and t0.date = t1.date
where to_date(t0.date,'yyyy-mm-dd') >= current_date - 1
UNION ALL
SELECT country_code
, source as exposure_class
, case when length(cast(district as varchar)) = 8 then '0' || cast(district as varchar) else cast(district as varchar) end as pcode
, t0.date
, case when date_part('day',age(current_date,to_date(t0.date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
, '7-day' as lead_time
, case when sum = '--' then 0
when t1.fc_trigger = 0 then 0
else cast(sum as float)
end as affected
, t1.fc_trigger
FROM "IBF-pipeline-output".calculated_affected_long t0
-- left join "IBF-pipeline-output".pcode_mapping_wards_new_distcode t1a
-- on t0.district = t1a.pcode
left join "IBF-pipeline-output".dashboard_forecast_per_district t1
on case when length(cast(t0.district as varchar)) = 3 then '0' || cast(t0.district as varchar) else cast(t0.district as varchar) end = t1.pcode
and t1.lead_time = '7-day'
and t0.date = t1.date
where to_date(t0.date,'yyyy-mm-dd') >= current_date - 1
) aa
group by 1,2,3,4,5
) bb
;
--select * from "IBF-pipeline-output".dashboard_calculated_affected_adm2 where country_code = 'UGA'
--truncate TABLE "IBF-pipeline-output".data_adm3;
--insert into "IBF-pipeline-output".data_adm3
--select t1.*
-- ,fc_trigger
-- ,fc_trigger2
----into "IBF-pipeline-output".data_adm3
--from {} t0
--left join "IBF-pipeline-output".dashboard_calculated_affected_adm3 t1
-- ON t0.pcode = t1.pcode
--left join "IBF-pipeline-output".dashboard_forecast_per_district t2
-- ON t0.pcode_parent = t2.pcode and t1.current_prev = t2.current_prev and t1.lead_time = t2.lead_time
--;
drop table if exists "IBF-pipeline-output".help_table;
select 'Current' as current_prev
,'3-day' as lead_time
into "IBF-pipeline-output".help_table
union all
select 'Previous' as current_prev
,'3-day' as lead_time
union all
select 'Current' as current_prev
,'7-day' as lead_time
union all
select 'Previous' as current_prev
,'7-day' as lead_time
;
--drop table if exists "IBF-pipeline-output".data_adm2 cascade;
TRUNCATE TABLE "IBF-pipeline-output".data_adm2;
insert into "IBF-pipeline-output".data_adm2
select t3.country_code
,t0.pcode
,t3.date
,t0a.current_prev
,t0a.lead_time
,fc,fc_trigger,fc_rp,fc_perc,fc_prob,fc_trigger2
,other_lead_time_trigger
,coalesce(population_affected,0) as population_affected
,coalesce(livestock_affected,0) as livestock_affected
,chicken_affected,cattle_affected,goat_affected,pig_affected,sheep_affected
,coalesce(cropland_affected,0) as cropland_affected
,t0.indicators
--into "IBF-pipeline-output".data_adm2
from "IBF-static-input"."CRA_data_2" t0
left join "IBF-pipeline-output".help_table t0a
on 1=1
left join "IBF-pipeline-output".waterstation_per_district t1
on t0.pcode = case when length(cast(t1.pcode as varchar)) = 3 then '0' || cast(t1.pcode as varchar) else cast(t1.pcode as varchar) end
left join "IBF-pipeline-output".dashboard_forecast_per_station t2
ON ((t2.lead_time = '7-day' and t0a.lead_time = t2.lead_time and t1."station_code_7day" = t2.station_code) OR (t2.lead_time = '3-day' and t0a.lead_time = t2.lead_time and t1."station_code_3day" = t2.station_code))
and t0a.current_prev = t2.current_prev
and t0a.lead_time = t2.lead_time
left join (
select case when length(cast(pcode as varchar)) = 3 then '0' || cast(pcode as varchar) else cast(pcode as varchar) end as pcode_level2
, *
from "IBF-pipeline-output".dashboard_calculated_affected_adm2
--select
-- case when length(cast(t1.pcode_level2_new as varchar)) = 3 then '0' || cast(t1.pcode_level2_new as varchar) else cast(t1.pcode_level2_new as varchar) end as pcode_level2
-- ,lead_time
-- ,current_prev
-- ,date
-- ,sum(population_affected) as population_affected
-- ,sum(chicken_affected) as chicken_affected
-- ,sum(cattle_affected) as cattle_affected
-- ,sum(goat_affected) as goat_affected
-- ,sum(pig_affected) as pig_affected
-- ,sum(sheep_affected) as sheep_affected
-- ,sum(livestock_affected) as livestock_affected
-- ,sum(cropland_affected) as cropland_affected
--from "IBF-pipeline-output".dashboard_calculated_affected_adm3 t0
--left join "IBF-pipeline-output".pcode_mapping_wards_new_distcode t1
-- on t0.pcode = case when length(cast(t1.pcode as varchar)) = 8 then '0' || cast(t1.pcode as varchar) else cast(t1.pcode as varchar) end
--group by 1,2,3,4
) t3
ON t0.pcode = t3.pcode_level2 and t0a.lead_time = t3.lead_time and t0a.current_prev = t3.current_prev
;
--select * from "IBF-pipeline-output".data_adm2 where country_code = 'UGA'
--truncate TABLE "IBF-pipeline-output".data_adm1;
--insert into "IBF-pipeline-output".data_adm1
--select t1.fc_trigger,t1.fc_trigger2
-- ,t2.*
----into "IBF-pipeline-output".data_adm1
--from {} t0
--left join (
--select
-- substring(case when length(cast(t1.pcode_level2_new as varchar)) = 3 then '0' || cast(t1.pcode_level2_new as varchar) else cast(t1.pcode_level2_new as varchar) end,1,2) as pcode
-- ,lead_time
-- ,current_prev
-- ,date
-- ,sum(population_affected) as population_affected
-- ,sum(chicken_affected) as chicken_affected
-- ,sum(cattle_affected) as cattle_affected
-- ,sum(goat_affected) as goat_affected
-- ,sum(pig_affected) as pig_affected
-- ,sum(sheep_affected) as sheep_affected
-- ,sum(livestock_affected) as livestock_affected
-- ,sum(cropland_affected) as cropland_affected
--from "IBF-pipeline-output".dashboard_calculated_affected_adm3 t0
--left join "IBF-pipeline-output".pcode_mapping_wards_new_distcode t1
-- on t0.pcode = case when length(cast(t1.pcode as varchar)) = 8 then '0' || cast(t1.pcode as varchar) else cast(t1.pcode as varchar) end
--group by 1,2,3,4
--) t2
--ON t0.pcode = t2.pcode
--left join (
--select substring(pcode,1,2) as pcode
-- ,lead_time
-- ,current_prev
-- ,date
-- ,max(fc_trigger) as fc_trigger
-- ,max(fc_trigger2) as fc_trigger2
--from "IBF-pipeline-output".data_adm2
--group by 1,2,3,4
--) t1
--on t2.pcode = t1.pcode and t2.lead_time = t1.lead_time and t2.date = t1.date
--;
|
TypeScript
|
UTF-8
| 5,846
| 2.6875
| 3
|
[] |
no_license
|
import NamedError from '../../../helpers/NamedError'
const enum PoolParamsByteLengths {
POOL_HASH = 28,
VRF = 32,
IPV4 = 4,
IPV6 = 16,
OWNER = 28,
REWARD = 29,
METADATA_HASH = 32,
}
export type PoolOwnerParams = {
stakingPath?: any //BIP32Path
stakingKeyHashHex?: string
}
export type SingleHostIPRelay = {
portNumber?: number
ipv4?: string
ipv6?: string
}
export type SingleHostNameRelay = {
portNumber?: number
dnsName: string
}
export type MultiHostNameRelay = {
dnsName: string
}
export type RelayParams = {
type: number // single host ip = 0, single hostname = 1, multi host name = 2
params: SingleHostIPRelay | SingleHostNameRelay | MultiHostNameRelay
}
export type PoolMetadataParams = {
metadataUrl: string
metadataHashHex: string
}
export type Margin = {
numeratorStr: string
denominatorStr: string
}
export type PoolParams = {
poolKeyHashHex: string
vrfKeyHashHex: string
pledgeStr: string
costStr: string
margin: Margin
rewardAccountHex: string
poolOwners: Array<PoolOwnerParams>
relays: Array<RelayParams>
metadata: PoolMetadataParams
}
const buf2hexLengthCheck = (buffer, correctByteLength, variableName) => {
if (!Buffer.isBuffer(buffer) || Buffer.byteLength(buffer) !== correctByteLength) {
throw NamedError('PoolRegIncorrectBufferLength', {message: variableName})
}
return buffer.toString('hex')
}
const checkedNumber = (number, variableName) => {
if (!Number.isInteger(number)) {
throw NamedError('PoolRegInvalidNumber', {message: variableName})
}
return number
}
const transformPoolOwners = (poolOwners, ownerCredentials) => {
const hexOwners: Array<string> = poolOwners.map((owner) =>
buf2hexLengthCheck(owner, PoolParamsByteLengths.OWNER, 'Owner key hash')
)
const constainsDuplicates = new Set(hexOwners).size !== hexOwners.length
if (constainsDuplicates) {
throw NamedError('PoolRegDuplicateOwners')
}
let isWalletTheOwner = false
const transformedOwners = hexOwners.map((owner) => {
if (owner === ownerCredentials.pubKeyHex) {
isWalletTheOwner = true
return {
stakingPath: ownerCredentials.path,
pubKeyHex: ownerCredentials.pubKeyHex, // retain key hex for inverse operation
}
}
return {stakingKeyHashHex: owner}
})
if (!isWalletTheOwner) {
throw NamedError('PoolRegNotTheOwner')
}
return transformedOwners
}
const transformMargin = (marginObj) => {
if (
!marginObj ||
!marginObj.hasOwnProperty('denominator') ||
!marginObj.hasOwnProperty('numerator') ||
checkedNumber(marginObj.numerator, 'Numerator') < 0 ||
checkedNumber(marginObj.denominator, 'Denominator') <= 0 ||
marginObj.numerator > marginObj.denominator
) {
throw NamedError('PoolRegInvalidMargin')
}
return {
numeratorStr: marginObj.numerator.toString(),
denominatorStr: marginObj.denominator.toString(),
}
}
const ipv4BufToAddress = (ipv4Buf) => {
buf2hexLengthCheck(ipv4Buf, PoolParamsByteLengths.IPV4, 'Ipv4 Relay')
return Array.from(new Uint8Array(ipv4Buf)).join('.')
}
const ipv6BufToAddress = (ipv6Buf) => {
const copy = Buffer.from(ipv6Buf)
const endianSwappedBuf = copy.swap32()
const ipv6Hex = buf2hexLengthCheck(endianSwappedBuf, PoolParamsByteLengths.IPV6, 'Ipv6 Relay')
const ipv6AddressSemicolons = ipv6Hex.replace(/(.{4})/g, '$1:').slice(0, -1)
return ipv6AddressSemicolons
}
export const ipv4AddressToBuf = (ipv4Address: string) => {
const splitAddressNumbers = ipv4Address.split('.').map((x) => +x)
return Buffer.from(splitAddressNumbers)
}
export const ipv6AddressToBuf = (ipv6Address: string) => {
const ipv6NoSemicolons = ipv6Address.replace(/:/g, '')
const ipv6Buf = Buffer.from(ipv6NoSemicolons, 'hex')
const copy = Buffer.from(ipv6Buf)
const endianSwappedBuf = copy.swap32()
return endianSwappedBuf
}
const transformRelays = (relays) =>
relays.map((relay) => {
let params
switch (relay.type) {
case 0:
params = {
portNumber: checkedNumber(relay.portNumber, 'Port number'),
ipv4: relay.ipv4 ? ipv4BufToAddress(relay.ipv4) : null,
ipv6: relay.ipv6 ? ipv6BufToAddress(relay.ipv6) : null,
}
break
case 1:
params = {
portNumber: checkedNumber(relay.portNumber, 'Port number'),
dnsName: relay.dnsName,
}
break
case 2:
params = {
dnsName: relay.dnsName,
}
break
default:
throw NamedError('PoolRegInvalidRelay')
}
return {
type: relay.type,
params,
}
})
const transformMetadata = (metadata) => {
if (!metadata) {
return null
}
if (!metadata.metadataHash || !metadata.metadataUrl) {
throw NamedError('PoolRegInvalidMetadata')
}
return {
metadataUrl: metadata.metadataUrl,
metadataHashHex: buf2hexLengthCheck(
metadata.metadataHash,
PoolParamsByteLengths.METADATA_HASH,
'Metadata hash'
),
}
}
export const transformPoolParamsTypes = (
{
type,
poolKeyHash,
vrfPubKeyHash,
pledge,
cost,
margin,
rewardAddress,
poolOwnersPubKeyHashes,
relays,
metadata,
},
ownerCredentials
) => ({
poolKeyHashHex: buf2hexLengthCheck(poolKeyHash, PoolParamsByteLengths.POOL_HASH, 'Pool key hash'),
vrfKeyHashHex: buf2hexLengthCheck(vrfPubKeyHash, PoolParamsByteLengths.VRF, 'VRF key hash'),
pledgeStr: checkedNumber(pledge, 'Pledge').toString(),
costStr: checkedNumber(cost, 'Fixed cost').toString(),
margin: transformMargin(margin),
rewardAccountHex: buf2hexLengthCheck(
rewardAddress,
PoolParamsByteLengths.REWARD,
'Reward account'
),
poolOwners: transformPoolOwners(poolOwnersPubKeyHashes, ownerCredentials),
relays: transformRelays(relays),
metadata: transformMetadata(metadata),
})
|
C
|
UTF-8
| 171
| 3.5
| 4
|
[] |
no_license
|
#include <stdio.h>
int main()
{
int i = 1, sum = 0;
while (i < 11)
{
sum += i;
i++;
}
printf("THe Sum is %d\n", sum);
return 0;
}
|
C++
|
UTF-8
| 2,575
| 2.90625
| 3
|
[] |
no_license
|
// you can do it now shubham
#include<bits/stdc++.h>
# define ll long long
using namespace std;
struct node
{
ll pro;
ll b;
};
bool compare(node n,node m)
{
if(n.pro==m.pro)
{
return n.b<m.b;
}
return n.pro<m.pro;
}
ll findsome(node* product ,ll n, ll mid)
{
int i,j;
ll some=0;
for(i=0;i<n;i++)
{
if(product[i].pro>mid)
some+=ceil((long double)(product[i].pro-mid)/product[i].b);
}
return some;
}
void dofinalthings(node* product,ll n,ll mid)
{
// dofinal things
// cout<<"now we are in dofinalthings"<<endl;
cout<<"mid is "<<mid<<endl;
ll countt=0;
ll i,j;
for(i=0;i<n;i++)
{
if(product[i].pro>mid)
{
countt=ceil((long double)(product[i].pro-mid)/product[i].b);
product[i].pro=product[i].pro-(product[i].b)*countt;
}
}
return ;
}
void dosearch(node* product,ll n,ll start,ll endd,ll m)
{
ll mid;
while(start<=endd)
{
mid=start +(endd-start)/2;
cout<<"mid is "<<mid<<endl;
ll some=findsome(product,n,mid);
// cout<<"some that we get is "<<some<<endl;
if(some==m)
{
// means we are getting the things
dofinalthings(product,n,mid);
return ;
}
if(some>m)
{
// we need to just shipt right side
// cout<<"shifting right side"<<endl;
//dosearch(product,n,mid+1,endd,m);
start=mid+1;
}
else
{
// cout<<"shifging left side"<<endl;
//dosearch(product,n,start,mid-1,m);
endd=mid-1;
}
}
}
int main()
{
ll test,a,b,c,d,i,j,k,l,n,m;
cin>>n>>m;
ll arr[n];
ll brr[n];
node product[n];
ll total=0;
for(i=0;i<n;i++)
{
cin>>arr[i];
total+=arr[i];
}
for(i=0;i<n;i++)
{
cin>>brr[i];
product[i].pro=arr[i]*brr[i];
product[i].b=brr[i];
}
sort(product,product+n,compare);
// cout<<"initially we get is "<<endl;
for(i=0;i<n;i++)
{
//cout<<product[i].pro<<" "<<product[i].b<<endl;
}
if(total<=m)
{
cout<<0<<endl;
}
else
{
ll value=1000000000000000000;
dosearch(product,n,0,value,m);
//cout<<"now we are again inthe main funciton"<<endl;
ll maxx=0;
for(i=0;i<n;i++)
{
cout<<product[i].pro<<" "<<product[i].b<<endl;
maxx=max(maxx,product[i].pro);
}
cout<<maxx<<endl;
}
}
|
JavaScript
|
UTF-8
| 4,021
| 3.984375
| 4
|
[] |
no_license
|
// Créer une variable nomVoiture, lui assigner la valeur suivante : "Peugeot"
var nomVoiture = "Peugeot";
// En une seule ligne de code, déclarer trois variables :
var identite = {prenom : "John", nom : "doe", age : 35};
// Créer une variable appelée x, lui assigner la valeur suivante : 50
// Créer deux variables appelées z et w permettant de calculer 5+10
// Créer une variable appelée d et assigner le résultat de z+w
var x = 50;
var z = 5;
var w = 10;
var d = z+w;
var demo = document.getElementById('demo');
demo.innerHTML = 'z vaut ' +z+', w vaut '+w+', le résultat est : '+z+'+'+w+'.';
// alert(d);
// alert(z*w);
// alert(w/2);
// alert(d%9);
// Déclarer deux variables : l = 10 , k = 5, en une seule ligne et sous forme raccourcie,
// Faire en sorte que l soit égal à 15 en utilisant la variable k
var l = 10;
var k = 5;
l = l+k;
// Créer une fonction appelée "maFonction"
function maFonction ()
{
//alert('Salut tout le monde !');
};
maFonction ();
function maFonctionDeRetour() {
var demoRetour = document.getElementById('demoRetour');
demoRetour.innerHTML = "Bonjour !"
};
maFonctionDeRetour();
// Créer un bouton sur la page html et attribuez-lui l'id suivant : "monBouton"
var monBouton = document.getElementById('monBouton');
monBouton.addEventListener('click', function () {
alert();
});
// Créer un div dans la page ayant pour id "changeSurOver"
var changeSurOver = document.getElementById('changeSurOver');
changeSurOver.style.border = '1px solid black';
changeSurOver.style.height = '25px';
changeSurOver.style.width = '45px';
changeSurOver.addEventListener('mouseover', function () {
changeSurOver.style.background = 'red';
});
// Créer une variable appelée txt
var txt = "une longue phrase";
var longueur = txt.length;
// alert(longueur);
// Créer deux variables appelées str1 et str2
var str1 = "Bonjour";
var str2 = " le monde !";
// alert(str1+str2);
// Créer un tableau appelé listeVoitures
var listeVoitures = ["Renault","Volvo","Citroen"];
var maVoiture = listeVoitures[1];
listeVoitures[0] = "Ford";
// alert(listeVoitures.length);
listeVoitures.pop();
listeVoitures.push("Ferrari");
// Créer une variable appelée rNumber
var rNumber = Math.random()*10;
// Créer une variable appelée fNumber, lui associer comme valeur un nombre à virgule
// de votre choix (par exemple : 15.7)
var fNumber = 15.7;
fNumber = Math.floor(fNumber);
fNumber = Math.ceil(fNumber);
// Créer deux variables : nombreUn et nombreDeux, assigner comme valeurs respectivement 10 et 5
var nombreUn = 10;
var nombreDeux = 5;
if (nombreUn>nombreDeux)
{
// alert(nombreUn+ " est supérieur à "+nombreDeux);
}
// Créer deux variables : nombreTrois et nombreQuatre, assigner comme valeur 10 aux deux variables
var nombreTrois = 10;
var nombreQuatre = 10;
if (nombreTrois === nombreQuatre)
{
// alert(nombreTrois+' est égal à '+nombreQuatre);
}
if (nombreUn!=nombreDeux)
{
// alert(nombreUn+" n'est pas égal à "+nombreDeux);
}
// Créer une boucle qui s'exécute de 0 à 9, dans la boucle, utiliser console.log()
// pour afficher l'index de la boucle
for (var i=0; i<9; i++)
{
console.log([i]);
};
var fruits = ["pomme","banane","poire"];
for (var i=0; i<fruits.length; i++ )
{
console.log([i]+' '+fruits[i]);
};
// Créer une boucle qui s'éxécute de 0 à 10, dans la boucle quand la valeur d'index est égale à 5,
// afficher une boite d'alerte affichant le message de votre choix.
for (var i=0; i<10; i++)
{
if (i===5)
{
// alert(i + ' est égal à '+i);
};
};
// Créer une boucle qui s'exécute tant que la variable i est inférieure à 10
// (utiliser l'instruction while)
var n=0;
while(n<=10)
{
document.write('bonjour ');
n++;
}
// Créer une boucle qui s'éxécute tant que la variable i est inférieure à 10
// mais qui incrémente i de 2 à chaque itération (utiliser un while)
var n=0;
while(n<10)
{
n = n+2;
console.log(n);
}
|
C#
|
UTF-8
| 479
| 2.765625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Extract
{
public class ColumnModel
{
public readonly string name;
public readonly string type;
public readonly ReadOnlyCollection<string> values;
public ColumnModel(string name, string type, List<string> values = null) {
this.name = name;
this.type = type;
this.values = new ReadOnlyCollection<string>((values == null) ? new List<string>() : values);
}
}
}
|
Python
|
UTF-8
| 232
| 3.90625
| 4
|
[] |
no_license
|
print "Lacos"
a = 1
x = input("1-Para contar de 1 a 10\n2-Para contar de 10 a 1\n")
if x == 1:
while True:
print a
a = a + 1
if a == 11:
break
elif x == 2:
a = 10
while True:
print a
a = a -1
if a == -1:
break
|
C++
|
UTF-8
| 2,266
| 2.71875
| 3
|
[] |
no_license
|
#include "CMSprite.h"
namespace CML
{
CMSprite::CMSprite()
{
_x = 0.0f;
_y = 0.0f;
_widht = 200.0f;
_height = 300.0f;
_texturePositionX = { 0.0f }, _texturePositionY = { 0.0f };
_image = nullptr;
}
CMSprite::CMSprite(float xPosition, float yPosition, float widht, float height)
{
_x = xPosition;
_y = yPosition;
_widht = widht;
_height = height;
_texturePositionX = { 0.0f }, _texturePositionY = { 0.0f };
_image = nullptr;
_textureHeight = 0;
_textureWidht = 0;
}
CMSprite::CMSprite(float xPosition, float yPosition, float widht, float height, char* imageLocation)
{
_x = xPosition;
_y = yPosition;
_widht = widht;
_height = height;
_image = CML::CMImage::CMImage(imageLocation);
_texturePositionX = { 0.0f }, _texturePositionY = { 0.0f };
_textureHeight = _image.getHeight();
_textureWidht = _image.getWidth();
}
CMSprite::CMSprite(float xPosition, float yPosition, float widht, float height, CMImage image)
{
_x = xPosition;
_y = yPosition;
_widht = widht;
_height = height;
_image = image;
_texturePositionX = { 0.0f }, _texturePositionY = { 0.0f };
_textureHeight = _image.getHeight();
_textureWidht = _image.getWidth();
}
CMSprite::~CMSprite()
{
}
float CMSprite::GetWidht()
{
return _widht;
}
void CMSprite::SetWidht(float widht)
{
_widht = widht;
}
float CMSprite::GetHeight()
{
return _height;
}
void CMSprite::SetHeight(float height)
{
_height = height;
}
CMImage CMSprite::GetImage()
{
return _image;
}
void CMSprite::SetImage(char* imageLocation)
{
_image = CML::CMImage::CMImage(imageLocation);
}
float CMSprite::GetTexturePositionX()
{
return _texturePositionX;
}
void CMSprite::SetTexturePositionX(float texPosX)
{
_texturePositionX = texPosX;
}
float CMSprite::GetTexturePositionY()
{
return _texturePositionY;
}
void CMSprite::SetTexturePositionY(float texPosY)
{
_texturePositionY = texPosY;
}
float CMSprite::GetTextureHeight()
{
return _textureHeight;
}
void CMSprite::SetTextureHeight(float texHeight)
{
_textureHeight = texHeight;
}
float CMSprite::GetTextureWidht()
{
return _textureWidht;
}
void CMSprite::SetTextureWidht(float texWidht)
{
_textureWidht = texWidht;
}
}
|
Java
|
UTF-8
| 2,171
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
package cn.edu.cug.cs.gtl.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ArrayUtils {
public static byte[] createByteArray(byte[] ba) {
if (ba == null)
return null;
byte[] r = new byte[ba.length];
System.arraycopy(ba, 0, r, 0, r.length);
return r;
}
public static int compare(byte[] a, byte[] b) {
if (a.length > b.length) return 1;
if (a.length < b.length) return -1;
for (int i = 0; i < a.length; ++i) {
if (a[i] > b[i])
return 1;
else if (a[i] < b[i])
return -1;
else
continue;
}
return 0;
}
public static byte[] createByteArray(int size, byte defaultValue) {
byte[] r = new byte[size];
for (int i = 0; i < size; i++)
r[i] = defaultValue;
return r;
}
public static byte[][] createByteArray(byte[][] baa) {
byte[][] r = new byte[baa.length][];
for (int i = 0; i < baa.length; i++) {
r[i] = new byte[baa[i].length];
System.arraycopy(baa[i], 0, r[i], 0, baa[i].length);
}
return r;
}
public static <E> Collection<E> iterableToCollection(Iterable<E> i) {
if (i instanceof Collection) {
return (Collection<E>) i;
} else {
ArrayList<E> al = new ArrayList<>();
for (E e : i) {
al.add(e);
}
return al;
}
}
public static <E> List<E> iterableToList(Iterable<E> i) {
if (i instanceof List) {
return (List<E>) i;
} else {
ArrayList<E> al = new ArrayList<>();
for (E e : i) {
al.add(e);
}
return al;
}
}
public static <E> List<E> collectionToList(Collection<E> i) {
if (i instanceof List) {
return (List<E>) i;
} else {
ArrayList<E> al = new ArrayList<>();
for (E e : i) {
al.add(e);
}
return al;
}
}
}
|
Java
|
UTF-8
| 527
| 2.484375
| 2
|
[] |
no_license
|
package implementation;
import interpreter.PrintScriptInterpreter;
public class CustomImplementationFactory implements InterpreterFactory {
@Override
public PrintScriptInterpreter interpreter() {
// your PrintScript implementation should be returned here.
// make sure to ADAPT your implementation to PrintScriptInterpreter interface.
throw new NotImplementedException("Needs implementation"); // TODO: implement
// Dummy impl: return (src, version, emitter, handler) -> { };
}
}
|
Python
|
UTF-8
| 484
| 2.734375
| 3
|
[] |
no_license
|
import pygame
import sys
playScreen=pygame.image.load('data\GameForm\PlayScreen.png')
playScreen=pygame.transform.scale(playScreen, (1368,768))
class Game:
def start(self):
pygame.init()
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
screen.blit(playScreen, (0, 0))
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
pygame.display.flip()
|
TypeScript
|
UTF-8
| 5,061
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { TestBed } from '@angular/core/testing';
import type {
SkyIndicatorDescriptionType,
SkyLabelType,
} from '@skyux/indicators';
import { LabelHarnessTestComponent } from './fixtures/label-harness-test.component';
import { LabelHarnessTestModule } from './fixtures/label-harness-test.module';
import { SkyLabelHarness } from './label-harness';
async function setupTest(options: { dataSkyId: string }) {
await TestBed.configureTestingModule({
imports: [LabelHarnessTestModule],
}).compileComponents();
const fixture = TestBed.createComponent(LabelHarnessTestComponent);
const loader = TestbedHarnessEnvironment.loader(fixture);
const labelHarness = await loader.getHarness(
SkyLabelHarness.with({ dataSkyId: options.dataSkyId })
);
return { fixture, labelHarness };
}
function testGetLabelType(dataSkyId: string, labelType?: SkyLabelType) {
it('should return the label type', async () => {
const { fixture, labelHarness } = await setupTest({ dataSkyId });
if (labelType) {
fixture.componentInstance.labelType = labelType;
fixture.detectChanges();
}
const componentLabelType = await labelHarness.getLabelType();
if (labelType) {
expect(componentLabelType).toEqual(labelType);
} else {
expect(componentLabelType).toEqual('info');
}
});
}
function testGetDescriptionType(
dataSkyId: string,
descriptionType: SkyIndicatorDescriptionType,
customDescription?: string
) {
it('should return the description type', async () => {
const { fixture, labelHarness } = await setupTest({ dataSkyId });
fixture.componentInstance.descriptionType = descriptionType;
fixture.componentInstance.customDescription = customDescription;
fixture.detectChanges();
const componentDescriptionType = await labelHarness.getDescriptionType();
expect(componentDescriptionType).toEqual(descriptionType);
});
}
describe('Label harness', () => {
describe('getLabelType', () => {
describe('success label', () =>
testGetLabelType('label-with-label-type', 'success'));
describe('danger label', () =>
testGetLabelType('label-with-label-type', 'danger'));
describe('warning label', () =>
testGetLabelType('label-with-label-type', 'warning'));
describe('info label', () =>
testGetLabelType('label-with-label-type', 'info'));
describe('default label type', () =>
testGetLabelType('label-without-label-type'));
});
describe('getDescriptionType', () => {
describe('attention', () =>
testGetDescriptionType('label-with-label-type', 'attention'));
describe('caution', () =>
testGetDescriptionType('label-with-label-type', 'caution'));
describe('completed', () =>
testGetDescriptionType('label-with-label-type', 'completed'));
describe('danger', () =>
testGetDescriptionType('label-with-label-type', 'danger'));
describe('error', () =>
testGetDescriptionType('label-with-label-type', 'error'));
describe('important info', () =>
testGetDescriptionType('label-with-label-type', 'important-info'));
describe('important warning', () =>
testGetDescriptionType('label-with-label-type', 'important-warning'));
describe('success', () =>
testGetDescriptionType('label-with-label-type', 'success'));
describe('warning', () =>
testGetDescriptionType('label-with-label-type', 'warning'));
describe('none', () =>
testGetDescriptionType('label-with-label-type', 'none'));
describe('custom', () =>
testGetDescriptionType('label-with-label-type', 'custom', 'custom text'));
});
describe('getLabelText', () => {
it('should return the label text', async () => {
const { labelHarness } = await setupTest({
dataSkyId: 'label-with-label-type',
});
await expectAsync(labelHarness.getLabelText()).toBeResolvedTo(
'Test label'
);
});
});
describe('getCustomDescription', () => {
it('should return the custom description when `descriptionType` is custom', async () => {
const { fixture, labelHarness } = await setupTest({
dataSkyId: 'label-with-label-type',
});
const description = 'Custom description:';
fixture.componentInstance.descriptionType = 'custom';
fixture.componentInstance.customDescription = description;
fixture.detectChanges();
const componentDescription = await labelHarness.getCustomDescription();
expect(componentDescription).toEqual(description);
});
it('should return an empty string when `descriptionType` is not custom', async () => {
const { fixture, labelHarness } = await setupTest({
dataSkyId: 'label-with-label-type',
});
fixture.componentInstance.descriptionType = 'attention';
fixture.detectChanges();
const componentDescriptionType =
await labelHarness.getCustomDescription();
expect(componentDescriptionType).toEqual('');
});
});
});
|
Java
|
UTF-8
| 241
| 1.53125
| 2
|
[] |
no_license
|
package com.fastspring.pizza.api.data.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.fastspring.pizza.api.data.entity.Cart;
public interface ShoppingCartRepository extends JpaRepository<Cart, Integer> {
}
|
Python
|
UTF-8
| 317
| 3.015625
| 3
|
[] |
no_license
|
import sys
N = int(input().strip())
array = list(map(int, input().strip().split()))
fc = sys.maxsize
array.sort()
for i in range(N-2):
nums = array[i:i+3]
ave = sum(nums)/3
temp = ((nums[0] - ave) ** 2 + (nums[1] - ave) ** 2 + (nums[2] - ave) ** 2)/3
if temp < fc:
fc = temp
print("%.2f" % fc)
|
Ruby
|
UTF-8
| 1,080
| 3.984375
| 4
|
[] |
no_license
|
# easy_503.rb - After Midnight (Part 2)
MINUTES_IN_DAY = 1440
def after_midnight(time)
time_arr = time.split(':').map(&:to_i)
time_arr[0] = time_arr[0] * 60 % MINUTES_IN_DAY
time_arr.reduce(:+)
end
def before_midnight(time)
time_arr = time.split(':').map(&:to_i)
time_arr[0] *= 60
(MINUTES_IN_DAY - time_arr.reduce(:+)) % MINUTES_IN_DAY
end
p after_midnight('00:00') == 0
p before_midnight('00:00') == 0
p after_midnight('12:34') == 754
p before_midnight('12:34') == 686
p after_midnight('24:00') == 0
p before_midnight('24:00') == 0
=begin
utp:
- takes 24h format str, returns minutes in int before or after midnight
- 2 methods
ec:
- validation, etc
data:
- i: string
- o: integer
tc:
after_midnight('00:00') == 0
before_midnight('00:00') == 0
after_midnight('12:34') == 754
before_midnight('12:34') == 686
after_midnight('24:00') == 0
before_midnight('24:00') == 0
alg:
- use constants to get minutes in a day
- convert by spitting at ':'
- first * 60, add to second, perform - if before midnight
=end
|
Python
|
UTF-8
| 958
| 4.15625
| 4
|
[] |
no_license
|
# 返回一个可调用对象,该对象使用操作数的getItem方法从其操作数中提取项。如果指定了多个项,则返回查找值的元组
from operator import itemgetter
print(itemgetter(1)('ABCDEF'))
print(itemgetter(1,3,5)('ABCDEF'))
print(itemgetter(slice(2,None))('ABCDEF'))
d = {'name': 'Charles', 'age': 18, 'addr': 'Shanghai'}
print(itemgetter('name')(d))
# 获取类中字段的值
class User:
def __init__(self, seq=None, **kwargs):
self.d = {}
def __iter__(self):
pass
def __getitem__(self, item):
return self.d[item]
def __setitem__(self, key, value):
self.d[key] = value
user = User()
user['name'] = 'Zhangsan'
user['age'] = '18'
user['addr'] = 'shanghai'
print(itemgetter('name')(user))
# 排序
inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
getcount = itemgetter(1)
print(list(map(getcount, inventory)))
print(sorted(inventory, key=getcount))
|
Java
|
UTF-8
| 1,131
| 3.453125
| 3
|
[] |
no_license
|
public class Solution_53_Maximum_SubArray {
public int maxSubArray(int[] nums) {
int len = nums.length;
int ans = nums[0];
int maxSum = nums[0];
if (len == 1){return maxSum;}
for (int i = 1; i < len; i++) {
// 这个地方的意思是 每次确定是否结束前边的序列
// 只要前边的maxSum大于0,就说明前面没给后面拖后腿,就可以继续下去
maxSum = (maxSum + nums[i] > nums[i]) ? (maxSum + nums[i]) : nums[i];
// 但我们还没法保证加了后面一位会不会给前面的序列拖后腿,所以要记录每次增加之后的maxSum的最大值
ans = ans>maxSum?ans:maxSum;
}
return ans;
}
public static void main(String[] args) {
int[] nums = new int[]{-2,1,-3,4,-1,2,1,-5,4};
Solution_53_Maximum_SubArray sol = new Solution_53_Maximum_SubArray();
System.out.println(sol.maxSubArray(nums));
}
// 最终提交时间为 20190509
// 运行占用时间 1ms 超过 95.90% 用户
// 运行占用内存 38.9MB 超过 86.26% 用户
}
|
Java
|
UTF-8
| 6,523
| 1.875
| 2
|
[] |
no_license
|
package cc.landingzone.dreamweb.sso.sp;
import cc.landingzone.dreamweb.common.CommonConstants;
import cc.landingzone.dreamweb.sso.CertManager;
import cc.landingzone.dreamweb.sso.SamlGenerator;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.ram.model.v20150501.AttachPolicyToRoleRequest;
import com.aliyuncs.ram.model.v20150501.AttachPolicyToRoleResponse;
import com.aliyuncs.sts.model.v20150401.GetCallerIdentityRequest;
import com.aliyuncs.sts.model.v20150401.GetCallerIdentityResponse;
import org.opensaml.DefaultBootstrap;
public class SPHelper {
private static String LINE_BREAK = "<br>";
private static String LINE_SEPARATED = "<hr>";
public static void main(String[] args) throws Exception {
// for test
CertManager.initSigningCredential();
DefaultBootstrap.bootstrap();
String idpProviderName = "MyAzureAD";
String roleName = "charlesRole1";
DefaultProfile profile = DefaultProfile.getProfile(CommonConstants.Aliyun_REGION_HANGZHOU,
CommonConstants.Aliyun_AccessKeyId, CommonConstants.Aliyun_AccessKeySecret);
initSP(profile, idpProviderName, roleName);
}
/**
* init sp (alicloud)
*
* @param profile
* @param idpProviderName
* @param roleName
* @return
* @throws Exception
*/
public static String initSP(DefaultProfile profile, String idpProviderName, String roleName) throws Exception {
StringBuilder result = new StringBuilder();
String uid = getUid(profile);
result.append("UID:" + uid);
result.append(LINE_BREAK);
result.append("idpProvider: " + idpProviderName);
result.append(LINE_BREAK);
result.append("roleName: " + roleName);
result.append(LINE_BREAK);
String policyDocument = "{\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Condition\":{\"StringEquals\":{\"saml:recipient\":\"https://signin.aliyun.com/saml-role/sso\"}},\"Effect\":\"Allow\",\"Principal\":{\"Federated\":[\"acs:ram::"
+ uid + ":saml-provider/" + idpProviderName + "\"]}}],\"Version\":\"1\"}";
String policyName = "AdministratorAccess";
String policyType = "System";
result.append("policyDocument: " + policyDocument);
result.append(LINE_BREAK);
result.append("policyName: " + policyName);
result.append(LINE_BREAK);
result.append("policyType: " + policyType);
result.append(LINE_BREAK);
result.append(LINE_BREAK);
result.append(LINE_SEPARATED);
result.append("1. add saml provider");
result.append(LINE_BREAK);
// 1. add saml provider, this samlMetadata can download from IDP(for example: Azure AD)
String samlMetadata = SamlGenerator.generateMetaXML();
String addSAMLProviderResult = addSAMLProviders(profile, idpProviderName, samlMetadata);
result.append("result: " + addSAMLProviderResult);
result.append(LINE_BREAK);
result.append(LINE_BREAK);
result.append(LINE_SEPARATED);
result.append("2. create role");
result.append(LINE_BREAK);
// 2. create role
String createRoleResult = createRole(profile, roleName, policyDocument);
result.append("result: " + createRoleResult);
result.append(LINE_BREAK);
result.append(LINE_BREAK);
result.append(LINE_SEPARATED);
result.append("3. attach policy to role");
result.append(LINE_BREAK);
// 3. attach policy to role
String attachPolicyToRoleResult = attachPolicyToRole(profile, policyName, policyType, roleName);
result.append("result: " + attachPolicyToRoleResult);
result.append(LINE_BREAK);
result.append(LINE_BREAK);
result.append(LINE_SEPARATED);
String roleExpression = "acs:ram::" + uid + ":role/" + roleName + ",acs:ram::" + uid + ":saml-provider/"
+ idpProviderName;
result.append("roleExpression: " + roleExpression);
return result.toString();
}
public static String attachPolicyToRole(DefaultProfile profile, String policyName, String policyType,
String roleName) throws Exception {
AttachPolicyToRoleRequest request = new AttachPolicyToRoleRequest();
request.setPolicyName(policyName);
request.setPolicyType(policyType);
request.setRoleName(roleName);
IAcsClient client = new DefaultAcsClient(profile);
AttachPolicyToRoleResponse response = client.getAcsResponse(request);
return response.getRequestId();
}
public static String createRole(DefaultProfile profile, String roleName, String policyDocument) throws Exception {
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysDomain("ram.aliyuncs.com");
request.setSysVersion("2015-05-01");
request.setSysAction("CreateRole");
request.setSysProtocol(ProtocolType.HTTPS);
request.putQueryParameter("RoleName", roleName);
request.putQueryParameter("AssumeRolePolicyDocument", policyDocument);
CommonResponse response = client.getCommonResponse(request);
return response.getData();
}
public static String getUid(DefaultProfile profile) throws Exception {
GetCallerIdentityRequest request = new GetCallerIdentityRequest();
IAcsClient client = new DefaultAcsClient(profile);
GetCallerIdentityResponse response = client.getAcsResponse(request);
return response.getAccountId();
}
public static String addSAMLProviders(DefaultProfile profile, String providerName, String samlMetadata)
throws Exception {
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysDomain("ims.aliyuncs.com");
request.setSysVersion("2019-08-15");
request.setSysAction("CreateSAMLProvider");
request.setSysProtocol(ProtocolType.HTTPS);
request.putQueryParameter("SAMLProviderName", providerName);
request.putQueryParameter("SAMLMetadataDocument", samlMetadata);
CommonResponse response = client.getCommonResponse(request);
return response.getData();
}
}
|
Java
|
UTF-8
| 469
| 2.21875
| 2
|
[] |
no_license
|
package br.com.fiap.financas.vo;
public class MensagemBean {
private String from, message;
public MensagemBean(String from, String message) {
super();
this.from = from;
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
|
JavaScript
|
UTF-8
| 19,412
| 2.515625
| 3
|
[] |
no_license
|
const { parse } = require('path');
const CompleteFinancingContract = artifacts.require("CompleteFinancingContract");
require('chai')
.use(require('chai-as-promised'))
.should();
contract("CompleteFinancingContract", (accounts) => {
// defining the accounts of the GanacheCLI
let[supplier1,supplier2,buyer1, buyer2,bank1,bank2,insurance1,insurance2,investor1,investor2] = accounts;
let contractInstance;
beforeEach(async () => {
contractInstance = await CompleteFinancingContract.deployed();
})
describe("CORRECT DEPLOYMENT.", async () =>{
it("should return Contract Address", async() =>{
const contractAddress = await contractInstance.contractAddress();
assert.notEqual(contractAddress,"");
assert.notEqual(contractAddress,null);
assert.notEqual(contractAddress,undefined);
})
it("should return correct token names", async() => {
const REC = await contractInstance.REC();
const SEC = await contractInstance.SEC();
assert.equal(REC,"REC for Recievables");
assert.equal(SEC,"SEC for Securities");
})
})
describe("BASIC BUSINEE OPERATIONS MUST BE FLUID ", async() => {
describe("MUST ONBOARD ACTORS AND PRODUCTS CORRECTLY.", async() =>{
it("should onboard suppliers correctly ---> createCompany and GetCompany must work", async()=> {
result = await contractInstance.createCompany("supplier","supplier", "1",{from: supplier1});
result2 = await contractInstance.getCompany("1", {from:supplier1});
const event = result.logs[0].args;
assert.equal(event.companyId.toNumber(),1,"companyId is right and event can be read");
assert.equal(event.name,"supplier","Name is right and event can be read" );
assert.equal(result2.owner,supplier1,"owner is right and info can be fetched!");
assert.equal(result2.location, "supplier", "location is right! getCompany is working!!");
})
it(" should allow suppliers to register product and update inventory", async() => {
result = await contractInstance.registerProduct("1","product1","1000000000000000000",{from:supplier1});
result2 = await contractInstance.getProduct("1",{from:buyer1});
result3 = await contractInstance.manufactureProd("1","2",{from:supplier1});
await contractInstance.manufactureProd("1","2",{from:supplier2}).should.be.rejected;
result4 = await contractInstance.getInventory("1",{from:supplier1})
await contractInstance.getInventory("1",{from:supplier2}).should.be.rejected;
await contractInstance.removeProduct("1",{from:supplier2}).should.be.rejected;
result5 = await contractInstance.removeProduct("1",{from:supplier1});
result6 = await contractInstance.getProduct("1",{from:supplier2});
const event = result.logs[0].args;
assert.equal(event.productId.toNumber(),1,"productId is right and event can be read");
assert.equal(event.prodName,"product1","product name is right.");
assert.equal(result2.sellingPrice, "1000000000000000000","get Product is working");
assert.equal(result4,"2","manufactureProd is working.");
assert.equal(result6.productId,0,"removeProduct working.")
})
it("should onboard Bank and Insurance Company",async() => {
result = await contractInstance.registerBank("bank","bank",{from:bank1})
result2 = await contractInstance.getBank("1",{from:buyer1});
assert.equal(result2.bankName,"bank","correct bank Name");
assert.equal(result2.bankAddress,bank1,"correct Address");
result3 = await contractInstance.registerAsInsuranceCompany("Insurance","Insurance","4",{from:insurance1})
result4 = await contractInstance.getCompany("2", {from: supplier2});
assert.equal(result4.companyName, "Insurance", "correct name");
assert.equal(result4.isInsuranceCompany,true,"registered as an insurance company")
})
})
describe ( "MUST ENABLE ORDERING, ACCEPTING AND PAYMENT",async() => {
it("should be able to make order request and accept it", async() => {
await contractInstance.registerProduct("1","product1","1000000000000000000",{from:supplier1});
await contractInstance.manufactureProd("2","2",{from: supplier1});
await contractInstance.createCompany("buyer","buyer", "3",{from: buyer1});
await contractInstance.createCompany("carrier","carrier", "4",{from: buyer2});
await contractInstance.makePurchaseOrderRequest("2","2","3",{from:buyer1});
await contractInstance.getPurchaseOrderRequest("1",{from:supplier2}).should.be.rejected;
result = await contractInstance.getPurchaseOrderRequest("1",{from: supplier1})
assert.equal(result.productId,"2","correct product ID requested for purchase");
assert.equal(result.isAccepted,false,"PO not accepted yet");
await contractInstance.acceptOrder("1","4","30",true,{from:supplier2}).should.be.rejected;
await contractInstance.acceptOrder("1","4","30",false,{from:supplier1});
await contractInstance.getInvoice("1",{from:bank1}).should.be.rejected;
result2 = await contractInstance.getInvoice("1",{from:buyer1});
result3 = await contractInstance.getBillofLading("1",{from:buyer1});
assert.equal(result3.carrierId,"4","correct carrier is chosen");
assert.equal(result3.buyerCompanyId,"3","correct delivery address")
assert.equal(result.isAccepted,false,"PO not accepted yet");
assert.equal(result2.orderId.toNumber(),1,"correct order number");
assert.equal(result2.isPaymentDoneByBuyer, false, "Invoice is not yet accepted");
})
it("buyer should be able to make payment and seller should be able to accept the payment ", async() => {
await contractInstance.makePayment("1",{from:supplier2,value:2000000000000000000}).should.be.rejected;
await contractInstance.makePayment("1",{from:buyer1,value:2000000000000000000}).should.be.rejected;
await contractInstance.confirmShipment("1",{from:buyer1});
result = await contractInstance.getShipment("1",{from:supplier1});
assert.equal(result.isShipmentRecieved,true,"shipment correctly delivered")
assert.equal(result.deliveryAddress,"buyer","delivered at the correct address")
let paymentB = await contractInstance.makePayment("1",{from:buyer1,value:2000000000000000000});
const contractAddress = await contractInstance.contractAddress();
await contractInstance.getInvoice("1",{from:buyer1});
result1 = await contractInstance.getInvoice("1",{from:buyer1});
assert.equal(result1.isPaymentDoneByBuyer,true, "invoice payment successfuly done");
let sellerOldBalance;
sellerOldBalance = await web3.eth.getBalance(supplier1);
// sellerOlBalance = await new web3.utils.BN(sellerOldBalance);
sellerOldBalance = parseInt(sellerOldBalance);
let totalRecievables;
totalRecievables = await contractInstance.getRecBalance(buyer1, {from:supplier1});
totalRecievables = parseInt(totalRecievables);
// totalRecievables = new web3.utils.BN(totalRecievables);
await contractInstance.liquidateRecievables("1",{from: supplier2}).should.be.rejected;
liquidateRec = await contractInstance.liquidateRecievables("1",{from: supplier1}).should.not.be.rejected;
const gasUsed = liquidateRec.receipt.gasUsed;
let expectedBalance = totalRecievables + sellerOldBalance -gasUsed;
expectedBalance = expectedBalance.toString();
expectedBalance = await new web3.utils.BN(expectedBalance);
sellerNewBalance = await web3.eth.getBalance(supplier1);
sellerNewBalance = await new web3.utils.BN(sellerNewBalance);
const difference = expectedBalance - sellerNewBalance;
const contractBalance = await web3.eth.getBalance(contractAddress);
// console.log(difference);
// console.log(contractBalance1);
// console.log(contractBalance);
// console.log(totalRecievables);
// console.log(await contractInstance.getInvoice("1", {from:supplier1}));
})
})
})
describe("FINANCING SHOULD WORK", async()=>{
it("seller should be able to apply and bank should be able to accept POF", async()=>{
await contractInstance.registerBank("bank2","bank2",{from:bank2});
result = await contractInstance.getCompany("4",{from:supplier1});
await contractInstance.makePurchaseOrderRequest("2","2","3",{from:buyer1});
await contractInstance.applyPoFinance("2","2",{from:supplier2}).should.be.rejected;
await contractInstance.applyPoFinance("2","2",{from:supplier1});
await contractInstance.getPoFinance("1",{from:bank1}).should.be.rejected;
result = await contractInstance.getPoFinance("1",{from:bank2});
assert.equal(result.orderId, "2","orderID is right");
assert.equal(result.buyerCompanyId,"3","buyer company Id is right")
assert.equal(result.isApproved, false, "PO is correctly not approved")
assert.equal(parseInt(result.value,10),2000000000000000000);
let sellerOldBalance;
sellerOldBalance = await web3.eth.getBalance(supplier1);
// // sellerOlBalance = await new web3.utils.BN(sellerOldBalance);
sellerOldBalance = parseInt(sellerOldBalance);
await contractInstance.approvePOFinance("1",{from: bank1,value:2000000000000000000}).should.be.rejected;
await contractInstance.approvePOFinance("1",{from: bank2,value:2000000000000000000});
bankOldBalance = await web3.eth.getBalance(bank2);
bankOldBalance = parseInt(bankOldBalance);
let sellerNewBalance = await web3.eth.getBalance(supplier1);
sellerNewBalance = parseInt(sellerNewBalance);
let expectedBalance = sellerOldBalance + 1600000000000000000;
// console.log(expectedBalance);
// console.log(sellerNewBalance);
result1 = await contractInstance.getPoFinance("1",{from:bank2});
assert.equal(result1.isApproved, true, "PO finance is correctly approved.");
assert.equal(sellerNewBalance,expectedBalance);
await contractInstance.manufactureProd("2","2",{from: supplier1});
await contractInstance.acceptOrder("2","4","30",true,{from:supplier1});
await contractInstance.confirmShipment("2",{from:buyer1});
await contractInstance.makePayment("2",{from:buyer1,value:2000000000000000000});
liquidateRec = await contractInstance.liquidateRecievables("2",{from: bank2}).should.not.be.rejected;
////Ask Ali
// bankNewBalance = await web3.eth.getBalance(bank2);
// bankNewBalance = parseInt(bankNewBalance);
// console.log(2000000000000000000 - (bankNewBalance - bankOldBalance));
})
it("should allow buyer to apply invoiceFinance and bank to accept it",async() => {
// will reject Invoice Financing if seller specifies false
await contractInstance.makePurchaseOrderRequest("2","2","3",{from:buyer1});
await contractInstance.manufactureProd("2","2",{from: supplier1});
await contractInstance.acceptOrder("3","4","30",false,{from:supplier1});
await contractInstance.confirmShipment("3",{from:buyer1});
await contractInstance.applyApprovedPayableInvoiceFinance("3","1",{from:buyer2}).should.be.rejected;
await contractInstance.applyApprovedPayableInvoiceFinance("3","1",{from:buyer1}).should.be.rejected;
//buyer has to do normal payment
await contractInstance.makePayment("3",{from:buyer1,value:2000000000000000000});
await contractInstance.liquidateRecievables("3",{from: supplier1}).should.not.be.rejected;
await contractInstance.makePurchaseOrderRequest("2","2","3",{from:buyer1});
await contractInstance.manufactureProd("2","2",{from: supplier1});
await contractInstance.acceptOrder("4","4","30",true,{from:supplier1});
await contractInstance.confirmShipment("4",{from:buyer1});
await contractInstance.applyApprovedPayableInvoiceFinance("4","1",{from:buyer1});
result = await contractInstance.getInvoiceFinance("1",{from:bank1})
assert.equal(result.invoiceFinanceId,1, "InvoiceDinance ID is correct.");
assert.equal(result.isApproved,false, "Correctly not yet approved.");
let sellerOldBalance;
sellerOldBalance = await web3.eth.getBalance(supplier1);
// // sellerOlBalance = await new web3.utils.BN(sellerOldBalance);
sellerOldBalance = parseInt(sellerOldBalance);
// bankOldBalance = await web3.eth.getBalance(bank1);
// bankOldBalance = parseInt(bankOldBalance);
await contractInstance.approveInvoiceFinance("1",{from:bank2,value:2000000000000000000}).should.be.rejected;
await contractInstance.approveInvoiceFinance("1",{from:bank1,value:2000000000000000000});
result1 = await contractInstance.getInvoiceFinance("1",{from:bank1})
assert.equal(result1.isApproved,true, "correctly approved.");
let value = parseInt(result.value);
let expectedBalance = sellerOldBalance + value*90/100;
let sellerNewBalance = await web3.eth.getBalance(supplier1);
sellerNewBalance = parseInt(sellerNewBalance);
assert.equal(sellerNewBalance,expectedBalance, "seller sent money");
await contractInstance.makePayment("4",{from:buyer1,value:2000000000000000000});
liquidateRec = await contractInstance.liquidateRecievables("4",{from: bank1}).should.not.be.rejected;
// bankNewBalance = await web3.eth.getBalance(bank1);
// bankNewBalance = parseInt(bankNewBalance);
// console.log(value);
// console.log(bankOldBalance);
// console.log(200000000000000000 - (bankNewBalance - bankOldBalance))
// console.log(bankNewBalance)
})
it("should allow buyer to securitize the invoices and investors to buy the securities issued", async() => {
await contractInstance.makePurchaseOrderRequest("2","2","3",{from:buyer1});
await contractInstance.createCompany("supplier2","supplier2", "5",{from: supplier2});
await contractInstance.registerProduct("5","product1","2000000000000000000",{from:supplier2});
await contractInstance.makePurchaseOrderRequest("3","2","3",{from:buyer1});
await contractInstance.manufactureProd("2","2",{from: supplier1});
await contractInstance.manufactureProd("3","2",{from: supplier2});
await contractInstance.acceptOrder("5","4","30",true,{from:supplier1});
await contractInstance.acceptOrder("6","4","30",true,{from:supplier2});
await contractInstance.confirmShipment("5",{from:buyer1});
await contractInstance.confirmShipment("6",{from:buyer1});
await contractInstance.applyReverseSecuritization("3","2",{from:buyer2}).should.be.rejected;
await contractInstance.applyReverseSecuritization("3","2",{from:buyer1});
result = await contractInstance.getSecurity("1",{from:investor1});
assert.equal(result.sId, "1","correct security ID");
assert.equal(result.amount,"6000000000000000000","securities correctly issued");
assert.equal(result.spvId,"1","correct SPV")
await contractInstance.rateSpv("1","4",{from: insurance2}).should.be.rejected;
await contractInstance.rateSpv("1","4",{from: insurance1});
result1 = await contractInstance.getSpv("1",{from:investor1});
assert.equal(result1.rating,"4","correctly rated by insurance company.")
await contractInstance.buySecurities("1",{from:investor1,value:4000000000000000000});
await contractInstance.buySecurities("1",{from:investor2,value:4000000000000000000});
await contractInstance.liquidateRecievables("5",{from:supplier1}).should.not.be.rejected;
await contractInstance.liquidateRecievables("6",{from:supplier2}).should.not.be.rejected;
await contractInstance.getNoteInfo("1",{from:investor2}).should.be.rejected;
result3 = await contractInstance.getNoteInfo("1",{from:investor1});
result4 = await contractInstance.getNoteInfo("2",{from:investor2});
assert.equal(result3.owner,investor1,"owner is correct");
assert.equal(result4.noteId,"2","note ID is correct");
assert.equal(result3.isRedeemed,false,"correctly not redeemed");
assert.equal(result4.isRedeemed,false,"correctly not redeemed");
await contractInstance.makePayment("5",{from:buyer1,value:2000000000000000000});
await contractInstance.makePayment("6",{from:buyer1,value:4000000000000000000});
// let investor1OldBalance = await web3.eth.getBalance(investor1);
// let investor2OldBalance = await web3.eth.getBalance(investor2);
// investor1OldBalance = parseInt(investor1OldBalance);
// investor2OldBalance = parseInt(investor2OldBalance);
await contractInstance.liquidateNote("1",{from:investor2}).should.be.rejected;
await contractInstance.liquidateNote("1",{from:investor1}).should.not.be.rejected;
await contractInstance.liquidateNote("2",{from:investor2}).should.not.be.rejected;
// investor1Expected = investor1OldBalance + parseInt(result3.amount);
// investor2Expected = investor2OldBalance + parseInt(result4.amount);
// let investor1newBalance = await web3.eth.getBalance(investor1);
// let investor2newBalance = await web3.eth.getBalance(investor2);
// investor1newBalance = parseInt(investor1newBalance);
// investor2newBalance = parseInt(investor2newBalance);
// console.log(investor2OldBalance);
// console.log(parseInt(result4.amount));
// console.log(parseInt(result3.amount));
// console.log(investor2newBalance);
// console.log(parseInt(result4.amount)-(investor2newBalance-investor2OldBalance));
})
})
})
|
Java
|
UTF-8
| 2,165
| 2.515625
| 3
|
[] |
no_license
|
package com.uady.proyectofinal;
/**
* Created by Antonio Soto on 19/05/2017.
*/
public class Delivery {
private static Delivery delivery = new Delivery();
private String statusName;
private String shippingDescription;
private int shippingQuantity;
private int shippingSize;
private String clientFullname;
private double latClient;
private double lonClient;
private double latCompany;
private double lonCompany;
private Delivery(){
;
}
public static Delivery getDelivery(){
return delivery;
}
public String getStatusName() {
return statusName;
}
public void setStatusName(String statusName) {
this.statusName = statusName;
}
public String getShippingDescription() {
return shippingDescription;
}
public void setShippingDescription(String shippingDescription) {
this.shippingDescription = shippingDescription;
}
public int getShippingQuantity() {
return shippingQuantity;
}
public void setShippingQuantity(int shippingQuantity) {
this.shippingQuantity = shippingQuantity;
}
public int getShippingSize() {
return shippingSize;
}
public void setShippingSize(int shippingSize) {
this.shippingSize = shippingSize;
}
public String getClientFullname() {
return clientFullname;
}
public void setClientFullname(String clientFullname) {
this.clientFullname = clientFullname;
}
public double getLatClient() {
return latClient;
}
public void setLatClient(double latClient) {
this.latClient = latClient;
}
public double getLonClient() {
return lonClient;
}
public void setLonClient(double lonClient) {
this.lonClient = lonClient;
}
public double getLatCompany() {
return latCompany;
}
public void setLatCompany(double latCompany) {
this.latCompany = latCompany;
}
public double getLonCompany() {
return lonCompany;
}
public void setLonCompany(double lonCompany) {
this.lonCompany = lonCompany;
}
}
|
Java
|
UTF-8
| 1,866
| 1.882813
| 2
|
[] |
no_license
|
package com.pitatto.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Data
@Table(name = "t_company_recruit_site_page")
public class RecruitSiteEntity {
@Id
@GeneratedValue
private int rowid;
@Column(nullable = false)
private int company_id;
@Column
private int recruit_site_year_id;
@Column
private String company_recruit_site_name;
@Column(nullable = false)
private String recruit_site_company_id;
@Column
private String company_recruit_site_page_url;
@Column(columnDefinition = "int default 1")
private Integer main_recruit_site_page_flag;
@Column(columnDefinition = "int default 1")
private Integer publish_status;
@Column(columnDefinition = "int default 1")
private Integer entry_flag;
@Column(columnDefinition = "int default 1")
private Integer posting_flag;
@Column(columnDefinition = "int default 1")
private Integer seminar_open_flag;
@Column(columnDefinition = "int default 1")
private Integer new_arrivals;
@Column
private String recruit_site_update_date;
@Column
private String recruit_site_publish_date;
@Column
private String company_recruit_site_page_note;
@Column(columnDefinition = "int default 1")
private Integer sort_order;
@Column(nullable = false, columnDefinition = "int default 1")
private int enable_flag;
@Column(nullable = false, columnDefinition = "int default 1")
private int display_flag;
@Column(nullable = false, columnDefinition = "int default 1")
private int exist_flag;
@Column(nullable = false)
private String create_date;
@Column(nullable = false)
private String update_date;
}
|
Java
|
UTF-8
| 1,280
| 3.03125
| 3
|
[] |
no_license
|
package projet.vueGraphique;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import projet.cartes.Carte;
import projet.joueur.Partie;
public class CartePanel extends JPanel {
private static final long serialVersionUID = 1L;
/** Dimension large constante qui s'utilise quand la place est large */
protected static final Dimension DIMENSION_LARGE = new Dimension(130,185);
/** Dimension large constante qui s'utilise quand la place est petite. */
protected static final Dimension DIMENSION_PETITE = new Dimension(50,65);
/** Source d'image. */
protected String source;
private Carte carte;
/**
* Instantialiser un nouveau carteAllie panel.
*
* @param carte the carte
*/
public CartePanel(Carte carte) {
this.carte = carte;
}
/* (non-Javadoc)
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
/*
* methode pour afficher la carte
* */
public void paintComponent(Graphics g) {
Image background = new ImageIcon(source).getImage();
g.drawImage(background, 0, 0, getWidth(), getHeight(), this);
}
}
|
JavaScript
|
UTF-8
| 342
| 2.59375
| 3
|
[] |
no_license
|
var http = require('http');
onRequest = (request, response) => {
console.log('Ein User führt einen Request durch' + request.url);
response.writeHead(200, { 'Context-Type': 'text/plain' });
response.write('Ein bisschen Data');
response.end();
};
http.createServer(onRequest).listen(1337);
console.log('Server is running ....');
|
Java
|
UTF-8
| 1,021
| 2.03125
| 2
|
[] |
no_license
|
package com.eCommerce.lojaOnline.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eCommerce.lojaOnline.model.Loja;
import com.eCommerce.lojaOnline.model.Produto;
import com.eCommerce.lojaOnline.repository.LojaRepository;
import com.eCommerce.lojaOnline.repository.ProdutoRepository;
@Service
public class LojaService {
@Autowired
private ProdutoRepository produtoRepository;
@Autowired
private LojaRepository lojaRepository;
public Loja cadastroProdutoLoja(long idLoja, long idProduto) {
Optional<Produto> produtoExistente = produtoRepository.findById(idProduto);
Optional<Loja> lojaExistente = lojaRepository.findById(idLoja);
if(produtoExistente.isPresent()&&lojaExistente.isPresent()) {
lojaExistente.get().getProduto().add(produtoExistente.get());
lojaRepository.save(lojaExistente.get());
return lojaRepository.save(lojaExistente.get());
}
return null;
}
}
|
PHP
|
UTF-8
| 836
| 2.5625
| 3
|
[] |
no_license
|
<?php
class Tag extends AppModel {
public $hasAndBelongsToMany = array('Photo');
public $actsAs = array('Ordered' => array('foreign_key' => false));
public function get_tags($photo_count = true) {
if ($photo_count === true) {
$tag_query = "
SELECT Tag.id, Tag.weight, Tag.name, Tag.created, (SELECT count(*) FROM photos_tags WHERE tag_id = Tag.id) as photos_count
FROM tags AS Tag
";
$tags = $this->query($tag_query);
// convert tag ids to int so json will be int and sort correct in angular
foreach ($tags as &$tag) {
$tag['Tag']['id'] = (int) $tag['Tag']['id'];
$tag['Tag']['photos_count'] = (int) $tag[0]['photos_count'];
unset($tag[0]);
}
} else {
$tags = $this->find('all', array(
'contain' => false
));
}
return $tags;
}
}
|
Java
|
UTF-8
| 295
| 1.578125
| 2
|
[] |
no_license
|
package com.capgemini.capskills.configurations.security.dao;
import org.springframework.data.repository.CrudRepository;
import com.capgemini.capskills.configurations.security.models.SecurityRole;
public interface ISecurityRoleCrudRepository extends CrudRepository<SecurityRole, Integer> {
}
|
C++
|
UTF-8
| 937
| 2.921875
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <vector>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int n;
int t;
int x;
int y;
int w;
int sum;
scanf("%d", &t);
for (int cs = 1; cs <= t; cs++) {
vector <int> arr;
char names[200][1000];
char temp[1000];
scanf("%d", &n);
sum = 0;
for(int i = 0; i < n; i++) {
scanf("%s", temp);
strcpy(names[i], temp);
scanf("%d", &x);
scanf("%d", &y);
scanf("%d", &w);
sum += x * y * w;
arr.push_back(x * y * w);
}
int ans = 0;
int mini = arr[0];
int pie;
int ok = 0;
char who[1000];
char from[1000];
pie = sum / n;
for (int i = 0; i < n; i++) {
if(arr[i] > pie) {
strcpy(who, names[i]);
ok = 1;
}
if(arr[i] < pie) {
strcpy(from, names[i]);
ok = 1;
}
}
if(ok)
printf("Case %d: %s took chocolate from %s\n", cs, who, from);
else
printf("Case %d: no thief\n", cs);
}
}
|
Python
|
UTF-8
| 1,243
| 3.609375
| 4
|
[] |
no_license
|
import random
# Super Class
# The super() function lets us call a bit of code from the parent class
# inside our own class. This is really helpful when you need to override
# a method from the superclass, defining your own version, but keep the
# effects of the parent class's version of the code.
#
# For more about super() than you probably want to know at this point, check
# out this blog post from the excellent Raymond Hettinger.
# https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
class Character:
def __init__(self, name, **kwargs):
self.name = name
for key, value in kwargs.items():
setattr(self, key, value)
class Thief(Character):
def __init__(self, name, sneaky=True, **kwargs):
super().__init__(name, **kwargs)
self.sneaky = sneaky
def pickpocket(self):
return self.sneaky and bool(random.randint(0, 1))
def hide(self, light_level):
return self.sneaky and light_level < 10
class Inventory:
def __init__(self):
self.slots = []
def add_item(self, item):
self.slots.append(item)
class SortedInventory(Inventory):
def add_item(self, item):
super().add_item(item)
self.slots.sort()
|
Ruby
|
UTF-8
| 2,967
| 2.796875
| 3
|
[] |
no_license
|
require "test_help"
# Useful test helpers.
#
# Many have been looted from stellar test code seen in applications by technoweenie,
# zenspider, and topfunky.
class Fusionary::Test::TestCase < Test::Unit::TestCase
self.use_transactional_fixtures = true
self.use_instantiated_fixtures = false
# Work around a bug in test/unit caused by the default test being named
# as a symbol (:default_test), which causes regex test filters
# (like "ruby test.rb -n /foo/") to fail because =~ doesn't work on
# symbols.
def initialize(name) #:nodoc:
super(name.to_s)
end
# Work around test/unit's requirement that every subclass of TestCase have
# at least one test method. Note that this implementation extends to all
# subclasses, as well, so subclasses of IntegrationTest may also exist
# without any test methods.
def run(*args) #:nodoc:
return if @method_name == "default_test"
super
end
def assert_creates_file(path)
assert !File.exists?(path), "#{path} should not exist"
yield if block_given?
assert File.exists?(path), "#{path} should have been created"
end
def assert_deletes_file(path)
assert File.exists?(path), "#{path} should exist"
yield if block_given?
assert !File.exists?(path), "#{path} should have been deleted"
end
# http://project.ioni.st/post/217#post-217
# and http://blog.caboo.se/articles/2006/06/13/a-better-assert_difference
#
# def test_new_publication
# assert_changed_by 1, Publication, :count do
# post :create, :publication => {...}
# # ...
# end
# end
#
# Is the number of items different?
#
# Can be used for increment and decrement.
#
# You can also send an array of class contants to check against.
def assert_changed_by(difference, object, method)
initial_value = object.send(method)
yield
assert_equal initial_value + difference, object.send(method)
end
def assert_not_changed(object, method, &block)
assert_changed_by 0, object, method, &block
end
##
# The opposite of an assert.
#
# deny world.flat?, "A round world was expected, but it was found to be flat."
def deny(condition, msg = nil)
assert ! condition, msg
end
##
# Alias for assert_not_equal
def deny_equal(*args)
assert_not_equal(args)
end
##
# Asserts that +obj+ responds to #empty? and #empty? returns false.
def deny_empty(obj)
assert_respond_to obj, :empty?
assert_equal false, obj.empty?
end
##
# Asserts that +obj+ responds to #include? and that obj includes +item+.
def assert_includes(obj, item, message = nil)
assert_respond_to obj, :include?
assert_equal true, obj.include?(item), message
end
##
# Asserts that +obj+ responds to #include? and that obj does not include
# +item+.
def deny_includes(obj, item, message = nil)
assert_respond_to obj, :include?
assert_equal false, obj.include?(item), message
end
end
|
C#
|
UTF-8
| 1,078
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
using System.Net;
using System.Threading.Tasks;
namespace RHttpServer
{
/// <summary>
/// Http server where request are handled as tasks
/// <para />
/// Good for processing requests of varying size
/// </summary>
public sealed class TaskBasedHttpServer : BaseHttpServer
{
/// <summary>
/// </summary>
/// <param name="port">The port to listen on</param>
/// <param name="path">Path to use as public dir. Set to null or empty string if none wanted</param>
/// <param name="throwExceptions">Whether exceptions should be suppressed and logged, or thrown</param>
public TaskBasedHttpServer(int port, string path = "", bool throwExceptions = false)
: base(port, path, throwExceptions)
{
}
protected override void ProcessContext(HttpListenerContext context)
{
Task.Run(() =>
{
if (!SecurityOn || SecMan.HandleRequest(context.Request))
Process(context);
});
}
}
}
|
C#
|
UTF-8
| 1,449
| 2.75
| 3
|
[] |
no_license
|
namespace Git_Pack
{
public class CommandLineArguments : ICommandLineArguments
{
public string RepositoryPath
{
get;
set;
}
public string OutputDirectoryPath
{
get;
set;
}
public string OutputZipPath
{
get;
set;
}
public string BranchWithChanges
{
get;
set;
}
public string ComparableBranch
{
get;
set;
}
public bool Overwrite
{
get;
set;
}
public string BackupDirectory
{
get;
set;
}
public CommandLineArguments()
{
}
public CommandLineArguments(string repositoryDirectory, string outputPath, bool isOutputDirectory, string branchWithChanges, string comparableBranch, bool overwrite, string backupDirectory)
{
this.RepositoryPath = repositoryDirectory;
this.OutputDirectoryPath = isOutputDirectory ? outputPath : string.Empty;
this.OutputZipPath = !isOutputDirectory ? outputPath : string.Empty;
this.BranchWithChanges = branchWithChanges;
this.ComparableBranch = comparableBranch;
this.Overwrite = overwrite;
this.BackupDirectory = backupDirectory;
}
}
}
|
Python
|
UTF-8
| 1,764
| 3
| 3
|
[
"MIT"
] |
permissive
|
from bibliopixel.animation import BaseMatrixAnim
import bibliopixel.colors as colors
import math
class Pinwheel(BaseMatrixAnim):
def __init__(self, led, dir = True):
super(Pinwheel, self).__init__(led)
self._center = (self.width / 2, self.height / 2)
self._dir = dir
self._len = (self.width*2) + (self.height*2) - 2
def step(self, amt):
if self._dir:
s = 255 - self._step
else:
s = self._step
pos = 0
cX, cY = self._center
for x in range(self.width):
c = colors.hue_helper(pos, self._len, s)
self._led.drawLine(cX, cY, x, 0, c)
pos += 1
for y in range(self.height):
c = colors.hue_helper(pos, self._len, s)
self._led.drawLine(cX, cY, self.width-1, y, c)
pos += 1
for x in range(self.width-1, -1, -1):
c = colors.hue_helper(pos, self._len, s)
self._led.drawLine(cX, cY, x, self.height-1, c)
pos += 1
for y in range(self.height-1, -1, -1):
c = colors.hue_helper(pos, self._len, s)
self._led.drawLine(cX, cY, 0, y, c)
pos += 1
self._step += amt
if(self._step >= 255):
self._step = 0
MANIFEST = [
{
"class": Pinwheel,
"controller": "matrix",
"desc": "Rotating rainbow lines",
"display": "Pin-Wheel",
"id": "Pinwheel",
"params": [
{
"default": True,
"help": "On clockwise, Off for counter-clockwise.",
"id": "dir",
"label": "Direction",
"type": "bool"
}
],
"type": "animation"
}
]
|
Java
|
ISO-8859-1
| 998
| 2.9375
| 3
|
[] |
no_license
|
package com.cosmo.ui.controls;
import com.cosmo.Workspace;
/**
* Clase abstracta que deben implementar los controles de formulario.
*
* @author Gerard Llort
*/
public abstract class FormField
{
//==============================================
// Constructors
//==============================================
/**
* Constructor de la clase {@link FormField}.
*/
public FormField()
{
// Constructor vaco
}
//==============================================
// Abstract members
//==============================================
/**
* Obtiene el nombre (identificador único) del campo.
*/
public abstract String getName();
/**
* Establece el valor del campo.
*/
public abstract void setValue(Object value);
/**
* Convierte la instancia en una cadena XHTML que representa el elemento en una página web.
*/
public abstract String render(Workspace workspace);
}
|
Java
|
UTF-8
| 1,562
| 2.0625
| 2
|
[] |
no_license
|
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.package com.google.caja.parser.quasiliteral;
package com.google.caja.parser.quasiliteral;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.js.Operation;
import com.google.caja.parser.js.Operator;
public class SpecialOpFilter extends RuleFilter<Operator> {
public SpecialOpFilter (RuleChain ruleChain) {
super(ruleChain);
}
@Override
Operator getKey(ParseTreeNode node) {
return ((Operation) node).getOperator();
}
@Override
boolean canMatch(Rule rule, Operator op) {
return ruleOperator(rule) == op || rule.canMatch(Operation.class);
}
private Operator ruleOperator(Rule rule) {
QuasiNode qp = QuasiCache.parse(rule.getRuleDescription().matches());
if (qp != null && qp instanceof SimpleQuasiNode) {
SimpleQuasiNode sqp = (SimpleQuasiNode) qp;
if (Operation.class.isAssignableFrom(sqp.getMatchedClass())) {
return (Operator) sqp.getValue();
}
}
return null;
}
}
|
Markdown
|
UTF-8
| 729
| 2.546875
| 3
|
[] |
no_license
|
date: 2013-03-23
title: Long time no blog
已经很久没有写博客了,某次受小胖的[org-blog](https://github.com/crackcell/org-blog)的启发,突然想自己也捣鼓一个静态博客生成的工具,用markdown写博客内容,于是就有了现在这个东西。一来是确实有东西想写写了,二来练一练前端和Perl。还有很多没弄好的,比如样式还很丑(= =|||)。慢慢改进先……
想想上次写blog还是在差不多快1年半前了,那时候还在用Godaddy的空间,把wordpress跟REICN的空间放在一起搭的。后来自己脑残,糟蹋了REICN,也糟蹋了自己的博客。
不知道我脑残还有没有救,就看这个博客能写多久了。
|
C++
|
UTF-8
| 1,881
| 2.59375
| 3
|
[] |
no_license
|
#include "TinyGPS++.h"
const int LORA_RX = 16;
const int LORA_TX = 17;
const int GPS_RX = 26;
const int GPS_TX = 27;
void loraInit();
void clearBuffer();
void gpsInit();
TinyGPSPlus gps;
void setup() {
/*ES920とのシリアル通信の初期化*/
Serial2.begin(115200, SERIAL_8N1, LORA_RX, LORA_TX);
delay(1000);
loraInit();
Serial2.print("GPS SET UP\r\n");
delay(100);
/*GNSSモジュールとのシリアル通信の初期化*/
Serial1.begin(115200, SERIAL_8N1, GPS_RX, GPS_TX); //事前にボーレートを115200bpsに変更しておく
gpsInit();
Serial2.print("SET UP DONE...READY\r\n");
delay(100);
}
void loop() {
while (Serial1.available() > 0){
char c = Serial1.read();
gps.encode(c);
if (gps.location.isUpdated()){
Serial2.print(gps.time.value()); Serial2.print(",");
Serial2.print(gps.location.lat(), 6); Serial2.print(",");
Serial2.print(gps.location.lng(), 6); Serial2.print(",");
Serial2.print(gps.altitude.meters()); Serial2.print("\r\n");
}
}
}
void loraInit(){
Serial2.print("2\r\n"); //Proccesingモード
clearBuffer();
Serial2.print("node 2\r\n"); //子機に設定
clearBuffer();
Serial2.print("ownid 0001\r\n"); //自ノードIDを0001に設定
clearBuffer();
Serial2.print("dstid 0000\r\n"); //送信先のIDを0000(親機)に設定
clearBuffer();
Serial2.print("q 1\r\n"); //次回の起動時にconfigモードにする設定
clearBuffer();
Serial2.print("w\r\n"); //設定内容の保存
clearBuffer();
Serial2.print("z\r\n"); //通信の開始
clearBuffer();
}
void clearBuffer(){
}
void gpsInit(){
Serial1.print("$PMTK220,100*2F\r\n"); //サンプリングレートを1[Hz]に変更
delay(100);
Serial1.print("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n"); //GPRMCとGPGGAセンテンスのみ受信
delay(100);
}
|
Python
|
UTF-8
| 122
| 3.109375
| 3
|
[] |
no_license
|
with open("cat.jpg", "rb") as f:
byte = f.read(1)
while byte != b"":
print(byte)
byte = f.read(1)
|
Java
|
UTF-8
| 409
| 3.15625
| 3
|
[] |
no_license
|
package callmethod_demo;
import java.util.Scanner;
public class MethodDemo21 {
public static void findDayofWeek() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the day number");
int d = input.nextInt();
input.close();
switch (d) {
}
}
public static void main(String[] args) {
MethodDemo21 obj = new MethodDemo21();
MethodDemo21.findDayofWeek();
}
}
|
Java
|
UTF-8
| 5,340
| 2.09375
| 2
|
[] |
no_license
|
package com.tsh.vas.model;
import java.io.Serializable;
import java.util.List;
/**
* BillDetailInfo
*
* @author dengjd
* @date 2016/11/3
*/
public class BillDetailInfo implements Serializable {
public static class CommissionInfo {
/**
* 销售价格
*/
private String salePrice;
/**
* 成本价
*/
private String costingAmount;
/**
* 佣金比例
*/
private String commissionRatio;
/**
* 差价
*/
private String differential;
/**
* 平台提成比率
*/
private String platformRatio;
/**
* 平台分成
*/
private String platformCommission;
/**
* 县域比例
*/
private String countyRatio;
/**
* 县域分成比
*/
private String areaDividedRatio;
/**
* 县域佣金
*/
private String countyCommission;
/**
* 网点比例
*/
private String shopRatio;
/**
* 网点佣金
*/
private String shopCommission;
public String getCommissionRatio() {
return commissionRatio;
}
public String getCountyCommission() {
return countyCommission;
}
public String getCountyRatio() {
return countyRatio;
}
public String getDifferential() {
return differential;
}
public String getPlatformCommission() {
return platformCommission;
}
public String getPlatformRatio() {
return platformRatio;
}
public String getSalePrice() {
return salePrice;
}
public String getShopCommission() {
return shopCommission;
}
public String getShopRatio() {
return shopRatio;
}
public void setCommissionRatio(String commissionRatio) {
this.commissionRatio = commissionRatio;
}
public void setCountyCommission(String countyCommission) {
this.countyCommission = countyCommission;
}
public void setCountyRatio(String countyRatio) {
this.countyRatio = countyRatio;
}
public void setDifferential(String differential) {
this.differential = differential;
}
public void setPlatformCommission(String platformCommission) {
this.platformCommission = platformCommission;
}
public void setPlatformRatio(String platformRatio) {
this.platformRatio = platformRatio;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public void setShopCommission(String shopCommission) {
this.shopCommission = shopCommission;
}
public void setShopRatio(String shopRatio) {
this.shopRatio = shopRatio;
}
public String getCostingAmount() {
return costingAmount;
}
public void setCostingAmount(String costingAmount) {
this.costingAmount = costingAmount;
}
public String getAreaDividedRatio() {
return areaDividedRatio;
}
public void setAreaDividedRatio(String areaDividedRatio) {
this.areaDividedRatio = areaDividedRatio;
}
}
/**
* 缴费订单编号
*/
private String chargeCode;
/**
* 业务类型名
*/
private String businessCodeName;
/**
* 支付金额
*/
private String paymentAmount;
/**
* 供应商名称
*/
private String supplierName;
/**
* 销售县域
*/
private String saleCountyName;
/**
* 网点
*/
private String shopName;
/**
* 佣金信息
*/
private List<CommissionInfo> commissionInfoList;
public String getBusinessCodeName() {
return businessCodeName;
}
public String getChargeCode() {
return chargeCode;
}
public List<CommissionInfo> getCommissionInfoList() {
return commissionInfoList;
}
public String getPaymentAmount() {
return paymentAmount;
}
public String getSaleCountyName() {
return saleCountyName;
}
public String getShopName() {
return shopName;
}
public String getSupplierName() {
return supplierName;
}
public void setBusinessCodeName(String businessCodeName) {
this.businessCodeName = businessCodeName;
}
public void setChargeCode(String chargeCode) {
this.chargeCode = chargeCode;
}
public void setCommissionInfoList(List<CommissionInfo> commissionInfoList) {
this.commissionInfoList = commissionInfoList;
}
public void setPaymentAmount(String paymentAmount) {
this.paymentAmount = paymentAmount;
}
public void setSaleCountyName(String saleCountyName) {
this.saleCountyName = saleCountyName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
}
|
SQL
|
UTF-8
| 1,706
| 4.09375
| 4
|
[] |
no_license
|
CREATE TABLE ENEMIES(
ID INT PRIMARY KEY,
NAME VARCHAR(50) NOT NULL,
HP FLOAT NOT NULL,
DAMAGE FLOAT NOT NULL
);
CREATE TABLE HEROES(
ID INT PRIMARY KEY,
NAME VARCHAR(50) NOT NULL,
LEVEL INT NOT NULL,
CLASS VARCHAR(50) NOT NULL,
STATUS VARCHAR(50),
HP FLOAT NOT NULL
);
CREATE TABLE SKILLS(
ID INT PRIMARY KEY,
TYPE VARCHAR(50) NOT NULL,
NAME VARCHAR(50) NOT NULL,
RANGE FLOAT NOT NULL
);
CREATE TABLE ENEMIES_SKILLS(
ENEMY_ID INT NOT NULL,
SKILL_ID INT NOT NULL,
LEVEL INT NOT NULL,
DAMAGE_HEAL FLOAT NOT NULL,
PRIMARY KEY (ENEMY_ID, SKILL_ID),
FOREIGN KEY (ENEMY_ID) REFERENCES ENEMIES(ID),
FOREIGN KEY (SKILL_ID) REFERENCES SKILLS(ID)
);
CREATE TABLE HEROES_SKILLS(
HEROES_ID INT NOT NULL,
SKILL_ID INT NOT NULL,
LEVEL INT NOT NULL,
DAMAGE_HEAL FLOAT NOT NULL,
PRIMARY KEY (HEROES_ID, SKILL_ID),
FOREIGN KEY (HEROES_ID) REFERENCES HEROES(ID),
FOREIGN KEY (SKILL_ID) REFERENCES SKILLS(ID)
);
INSERT INTO ENEMIES VALUES(
11, 'WORLD SERPENT', 9999.99, 700
);
INSERT INTO HEROES (LEVEL, NAME, STATUS, HP, ID, CLASS) VALUES(
10, 'SOLIDER', NULL, 100, 1, 'KNIGHT'
);
INSERT INTO HEROES VALUES (
1,'ARAGON',123,'KNIGHT','NORMAL',200.50
);
DELETE FROM ENEMIES WHERE LEVEL > 2 AND NAME='WORLD SERPENT';
UPDATE HEROES
SET LEVEL = 4, HP=100
WHERE ID = 1;
SELECT LEVEL, NAME FROM HEROES
WHERE ID = 2;
SELECT H.NAME, H.LEVEL, S.NAME, HS.LEVEL
FROM HEROES H, SKILLS S, HEROES_SKILLS HS
WHERE HEROES_ID = H.ID AND SKILL_ID = S.ID
AND H.NAME LIKE '%A%';
SELECT COUNT(*) FROM HEROES;
SELECT SUM(H.LEVEL), AVG(H.LEVEL) FROM HEROES H;
SELECT * FROM ENEMIES;
SELECT NAME FROM HEROES WHERE DAMAGE = 100;
|
Java
|
UTF-8
| 1,098
| 2.4375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.sql.Timestamp;
public class QuizObj {
private int quizId;
private Timestamp dateChange;
private int money;
private int userId;
public QuizObj() {
}
public QuizObj(int quizId, Timestamp dateChange, int money, int userId) {
this.quizId = quizId;
this.dateChange = dateChange;
this.money = money;
this.userId = userId;
}
public Timestamp getDateChange() {
return dateChange;
}
public void setDateChange(Timestamp dateChange) {
this.dateChange = dateChange;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getQuizId() {
return quizId;
}
public void setQuizId(int quizId) {
this.quizId = quizId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
Java
|
UTF-8
| 4,240
| 2.59375
| 3
|
[] |
no_license
|
package shapeshooser;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.MouseEvent;
public class Controller {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Button drawRect;
@FXML
public ColorPicker colorpicker;
@FXML
public RadioButton rbCircle;
@FXML
public RadioButton rbOval;
@FXML
public RadioButton rbRectangle;
@FXML
public RadioButton rbSquare;
@FXML
public RadioButton rbTriangle;
@FXML
public RadioButton rbLine;
@FXML
public ToggleGroup tgShapes;
@FXML
public Canvas canvas;
public void draw(){
Double[] coordArray = new Double[4];
GraphicsContext gc = canvas.getGraphicsContext2D();
canvas.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
coordArray[0] = mouseEvent.getSceneX();
coordArray[1] = mouseEvent.getSceneY()-235;
}
});
canvas.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
coordArray[2] = mouseEvent.getSceneX();
coordArray[3] = mouseEvent.getSceneY() - 235;
gc.setFill(colorpicker.getValue()) ;
gc.setStroke(colorpicker.getValue());
gc.setLineWidth(5);
ShapeArrayList<Shape> shapes = new ShapeArrayList<>();
rbCircle.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
Circle circle = new Circle(coordArray[2]-coordArray[0],coordArray[0],coordArray[1]);
Main.drawShapes(gc,circle);
}
});
rbLine.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
LineDirect line = new LineDirect(coordArray[2],coordArray[3],coordArray[0],coordArray[1]);
Main.drawShapes(gc,line);
}
});
rbSquare.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
Square square = new Square(coordArray[2]-coordArray[0],coordArray[0],coordArray[1]);
Main.drawShapes(gc,square);
}
});
rbRectangle.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
Rectangle_shaped rect = new Rectangle_shaped(coordArray[2]-coordArray[0],coordArray[3]-coordArray[1],coordArray[0],coordArray[1]);
Main.drawShapes(gc,rect);
}
});
rbOval.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
Oval oval = new Oval(coordArray[2]-coordArray[0],coordArray[3]-coordArray[1],coordArray[0],coordArray[1]);
Main.drawShapes(gc,oval);
}
});
rbTriangle.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
Triangle triangle = new Triangle(coordArray[2]-coordArray[0],coordArray[3]-coordArray[1],coordArray[0],coordArray[1]);
Main.drawShapes(gc,triangle);
}
});
}
});
}
@FXML
void initialize() {
draw();
}
}
|
SQL
|
UTF-8
| 18,725
| 3.015625
| 3
|
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : local
Source Server Version : 50636
Source Host : localhost:3306
Source Database : admin4
Target Server Type : MYSQL
Target Server Version : 50636
File Encoding : 65001
Date: 2018-09-28 13:44:48
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for deploy
-- ----------------------------
DROP TABLE IF EXISTS `deploy`;
CREATE TABLE `deploy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL COMMENT '名称',
`host` varchar(30) DEFAULT NULL COMMENT '主机',
`port` int(11) DEFAULT NULL COMMENT '端口',
`user` varchar(50) DEFAULT NULL COMMENT '用户',
`pwd` varchar(100) DEFAULT NULL COMMENT '密码',
`path` varchar(100) DEFAULT NULL COMMENT '路径',
`create_time` timestamp NULL DEFAULT NULL COMMENT '文件',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='程序部署';
-- ----------------------------
-- Records of deploy
-- ----------------------------
INSERT INTO `deploy` VALUES ('6', '聊天室', '192.168.1.181', '22', 'root', '123456', '/opt/java/chat/chat-server.jar', '2018-09-27 16:09:45');
-- ----------------------------
-- Table structure for guide_site
-- ----------------------------
DROP TABLE IF EXISTS `guide_site`;
CREATE TABLE `guide_site` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) DEFAULT NULL,
`URL` varchar(200) DEFAULT NULL,
`IMAGE` varchar(200) DEFAULT NULL,
`TYPE` int(11) DEFAULT NULL,
`COMMENT` varchar(100) DEFAULT NULL,
`SORT` int(11) DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=137 DEFAULT CHARSET=utf8 COMMENT='网站地址';
-- ----------------------------
-- Records of guide_site
-- ----------------------------
INSERT INTO `guide_site` VALUES ('98', '网易课堂', 'study.163.com', 'icon6913048374137169941.png', '4', '网易在线课程', '1', '2018-05-16 22:10:35');
INSERT INTO `guide_site` VALUES ('101', '网络电子课程', 'yeybk.xzkfq.cn', 'unknown.png', '34', '在线备课(宋老师)', '1', '2018-05-16 22:42:43');
INSERT INTO `guide_site` VALUES ('102', '百度', 'www.baidu.com', 'icon4847216020769285621.png', '29', '百度一下', '1', '2018-05-17 20:47:31');
INSERT INTO `guide_site` VALUES ('103', '淘宝', 'www.taobao.com', 'icon6961302624607474104.png', '30', '淘宝购物', '1', '2018-05-17 20:48:31');
INSERT INTO `guide_site` VALUES ('104', '京东', 'www.jd.com', 'icon2478977191638425815.png', '30', '京东商城', '2', '2018-05-18 15:42:47');
INSERT INTO `guide_site` VALUES ('105', '开源中国', 'www.oschina.net', 'icon1277877172443504134.png', '33', '开源中国社区', '1', '2018-05-19 22:19:59');
INSERT INTO `guide_site` VALUES ('108', 'GitHub', 'github.com', 'icon1980162427419300092.png', '33', '代码托管中心', '2', '2018-05-19 23:53:56');
INSERT INTO `guide_site` VALUES ('109', 'Collect UI', 'www.collectui.com', 'icon8758936578823090736.png', '31', 'Collect UI', '4', '2018-05-19 23:54:32');
INSERT INTO `guide_site` VALUES ('110', '优设', 'www.uisdc.com', 'unknown.png', '31', '优设', '2', '2018-05-19 23:55:54');
INSERT INTO `guide_site` VALUES ('112', '追波', 'dribbble.com', 'icon4758864900014274635.png', '31', '设计师创意作品', '3', '2018-05-19 23:57:38');
INSERT INTO `guide_site` VALUES ('113', '站酷', 'www.zcool.com.cn', 'icon2335670426781082746.png', '31', '设计师互动平台', '1', '2018-05-21 09:01:50');
INSERT INTO `guide_site` VALUES ('114', '用友OA', '218.94.153.148:8888/seeyon/index.jsp', 'unknown.png', '34', '天泽OA', '2', '2018-05-21 10:52:31');
INSERT INTO `guide_site` VALUES ('115', 'MVN仓库', 'mvnrepository.com', 'unknown.png', '35', 'Maven Repository', '1', '2018-05-23 14:05:17');
INSERT INTO `guide_site` VALUES ('116', 'html模板', 'templated.co', 'icon4937138979905354104.png', '36', '', '3', '2018-05-28 23:33:45');
INSERT INTO `guide_site` VALUES ('117', 'one page', 'onepagelove.com', 'unknown.png', '36', '单页模版', '2', '2018-05-28 23:34:14');
INSERT INTO `guide_site` VALUES ('118', '禅道', '192.168.1.52:9999/zentao', 'unknown.png', '34', '内网项目管理', '3', '2018-05-30 15:29:15');
INSERT INTO `guide_site` VALUES ('119', '用友NC', '218.94.153.148:666/hrss/login.jsp', 'unknown.png', '34', '薪资管理', '4', '2018-06-04 09:09:32');
INSERT INTO `guide_site` VALUES ('120', 'Colorlib', 'colorlib.com', 'unknown.png', '36', '免费网站模板', '1', '2018-06-13 10:02:54');
INSERT INTO `guide_site` VALUES ('121', '悬笔e绝', 'www.xuanbiyijue.com', 'icon6470490984486409721.png', '37', '悬笔e绝 个人博客', '1', '2018-06-14 15:51:35');
INSERT INTO `guide_site` VALUES ('122', '绩效', '218.94.153.148:100', 'unknown.png', '34', '天泽绩效', '5', '2018-06-20 16:35:43');
INSERT INTO `guide_site` VALUES ('123', '基站定位接口', 'www.cellocation.com/interfac', 'unknown.png', '35', 'LBS数据仓库', '2', '2018-07-06 16:57:43');
INSERT INTO `guide_site` VALUES ('124', 'thinkrace', 'www.thinkrace.com', 'unknown.png', '35', '智能设备', '3', '2018-07-09 23:12:50');
INSERT INTO `guide_site` VALUES ('125', '哈哈max', 'www.haha.mx', 'icon3924112112093172094.png', '33', '搞笑那点儿事', '4', '2018-07-11 08:58:49');
INSERT INTO `guide_site` VALUES ('126', '经纬度查询', 'www.gpsspg.com/maps.htm', 'icon7781571856844894725.png', '35', '经纬度地图', '5', '2018-07-16 17:04:55');
INSERT INTO `guide_site` VALUES ('127', 'icons8', 'icons8.com', 'unknown.png', '31', 'Free Flat Icons免费图标', '5', '2018-07-21 21:48:39');
INSERT INTO `guide_site` VALUES ('129', ' SVG icons', 'www.iconfinder.com', 'icon5566927916572449782.png', '31', '图标库', '6', '2018-07-21 21:50:58');
INSERT INTO `guide_site` VALUES ('130', 'html5', 'html5up.net', 'unknown.png', '36', 'html5响应式模版', '5', '2018-07-24 14:51:02');
INSERT INTO `guide_site` VALUES ('131', 'CSDN', 'www.csdn.net', 'icon1538902782487695558.png', '33', 'IT技术社区', '3', '2018-07-25 14:27:29');
INSERT INTO `guide_site` VALUES ('132', 'CSS Winner', 'www.csswinner.com', 'icon3704146882469737955.png', '36', '样板网站', '6', '2018-07-25 15:47:19');
INSERT INTO `guide_site` VALUES ('134', 'WrapPixel', 'wrappixel.com', 'unknown.png', '36', 'Bootstrap Admin ', '4', '2018-08-22 09:19:54');
INSERT INTO `guide_site` VALUES ('135', '格式转换', 'cn.office-converter.com', 'unknown.png', '35', '在线格式转换', '4', '2018-09-26 16:06:46');
-- ----------------------------
-- Table structure for guide_type
-- ----------------------------
DROP TABLE IF EXISTS `guide_type`;
CREATE TABLE `guide_type` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`CODE` varchar(5) DEFAULT NULL,
`NAME` varchar(20) DEFAULT NULL,
`SORT` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 COMMENT='网址类型';
-- ----------------------------
-- Records of guide_type
-- ----------------------------
INSERT INTO `guide_type` VALUES ('4', null, '教程', '6');
INSERT INTO `guide_type` VALUES ('29', null, '综合', '1');
INSERT INTO `guide_type` VALUES ('30', null, '购物', '8');
INSERT INTO `guide_type` VALUES ('31', null, '设计', '5');
INSERT INTO `guide_type` VALUES ('33', null, '社区', '2');
INSERT INTO `guide_type` VALUES ('34', null, '办公', '9');
INSERT INTO `guide_type` VALUES ('35', null, 'IT', '3');
INSERT INTO `guide_type` VALUES ('36', null, 'HTML', '4');
INSERT INTO `guide_type` VALUES ('37', null, '博客', '7');
-- ----------------------------
-- Table structure for manifest
-- ----------------------------
DROP TABLE IF EXISTS `manifest`;
CREATE TABLE `manifest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`os` varchar(20) DEFAULT NULL COMMENT '操作系统',
`host` varchar(50) DEFAULT NULL COMMENT '主机',
`net_no` varchar(5) DEFAULT NULL COMMENT '编号',
`user` varchar(50) DEFAULT NULL,
`pwd` varchar(100) DEFAULT NULL,
`tag` varchar(200) DEFAULT NULL COMMENT '标签',
`note` varchar(200) DEFAULT NULL COMMENT '备注',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COMMENT='清单';
-- ----------------------------
-- Records of manifest
-- ----------------------------
INSERT INTO `manifest` VALUES ('9', 'Linux', null, '24', null, null, 'XCMG-GW', '重型网关', '2018-09-16 13:39:17');
-- ----------------------------
-- Table structure for mem_body
-- ----------------------------
DROP TABLE IF EXISTS `mem_body`;
CREATE TABLE `mem_body` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` int(11) DEFAULT NULL COMMENT '类型',
`day` date DEFAULT NULL COMMENT '时间',
`subject` varchar(300) DEFAULT NULL COMMENT '主题',
`content` varchar(1000) DEFAULT NULL COMMENT '内容',
`photos` varchar(1000) DEFAULT NULL COMMENT '照片',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`create_user` varchar(50) DEFAULT NULL COMMENT '创建人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=utf8 COMMENT='概要';
-- ----------------------------
-- Records of mem_body
-- ----------------------------
-- ----------------------------
-- Table structure for mem_photo
-- ----------------------------
DROP TABLE IF EXISTS `mem_photo`;
CREATE TABLE `mem_photo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) DEFAULT NULL COMMENT '标题',
`note` varchar(200) DEFAULT NULL COMMENT '备注',
`path` varchar(100) DEFAULT NULL COMMENT '路径',
`thumb` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8 COMMENT='照片';
-- ----------------------------
-- Records of mem_photo
-- ----------------------------
-- ----------------------------
-- Table structure for mem_type
-- ----------------------------
DROP TABLE IF EXISTS `mem_type`;
CREATE TABLE `mem_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '名称',
`note` varchar(100) DEFAULT NULL COMMENT '备注',
`sort` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='类型';
-- ----------------------------
-- Records of mem_type
-- ----------------------------
INSERT INTO `mem_type` VALUES ('1', '亲子', '', '1');
INSERT INTO `mem_type` VALUES ('2', '旅行', '', '2');
INSERT INTO `mem_type` VALUES ('3', '公开', '', '3');
-- ----------------------------
-- Table structure for rel_user_role
-- ----------------------------
DROP TABLE IF EXISTS `rel_user_role`;
CREATE TABLE `rel_user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`role_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of rel_user_role
-- ----------------------------
INSERT INTO `rel_user_role` VALUES ('35', '1', '1');
INSERT INTO `rel_user_role` VALUES ('42', '27', '17');
INSERT INTO `rel_user_role` VALUES ('39', '27', '16');
INSERT INTO `rel_user_role` VALUES ('27', '25', '15');
-- ----------------------------
-- Table structure for sys_asset
-- ----------------------------
DROP TABLE IF EXISTS `sys_asset`;
CREATE TABLE `sys_asset` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL COMMENT '资源名称',
`code` varchar(50) DEFAULT NULL COMMENT '资源代码',
`pid` int(11) DEFAULT NULL COMMENT '父ID',
`pids` varchar(80) DEFAULT NULL COMMENT '父节组ID',
`type` varchar(50) DEFAULT NULL COMMENT '类型',
`controller` varchar(100) DEFAULT NULL COMMENT '控制器',
`view` varchar(100) DEFAULT NULL COMMENT '视图',
`icon_css` varchar(100) DEFAULT NULL COMMENT '图标css',
`is_menu` int(11) DEFAULT NULL COMMENT '是否菜单',
`sort` int(11) DEFAULT NULL COMMENT '排序',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=43 DEFAULT CHARSET=utf8 COMMENT='系统资源';
-- ----------------------------
-- Records of sys_asset
-- ----------------------------
INSERT INTO `sys_asset` VALUES ('1', '首页', 'index', '0', '0', 'menu', '', '', 'mdi-home', '1', '1');
INSERT INTO `sys_asset` VALUES ('34', '程序清单', 'manifest', '39', '0/39', 'menu', 'home/mf', 'devops/manifest', '', '1', '30');
INSERT INTO `sys_asset` VALUES ('33', '部署管理', 'deploy', '39', '0/39', 'menu', 'home/dpl', 'devops/deploy', '', '1', '20');
INSERT INTO `sys_asset` VALUES ('5', '系统管理', 'sys', '0', '0', 'node', '', '', 'mdi-settings', '1', '100');
INSERT INTO `sys_asset` VALUES ('6', '用户管理', 'user', '5', '0/5', 'menu', 'home/user', 'sys/user', null, '1', '5');
INSERT INTO `sys_asset` VALUES ('7', '角色管理', 'role', '5', '0/5', 'menu', 'home/role', 'sys/role', null, '1', '10');
INSERT INTO `sys_asset` VALUES ('8', '菜单管理', 'menu', '5', '0/5', 'menu', 'home/menu', 'sys/menu', null, '1', '15');
INSERT INTO `sys_asset` VALUES ('36', '相册管理', 'photo', '0', '0', 'node', '', '', 'mdi-panorama', '1', '40');
INSERT INTO `sys_asset` VALUES ('37', '图片上传', 'upload', '36', '0/36', 'menu', 'home/upload', 'photo/upload', '', '1', '5');
INSERT INTO `sys_asset` VALUES ('38', '图库预览', 'preview', '36', '0/36', 'menu', 'home/preview', 'photo/preview', '', '1', '10');
INSERT INTO `sys_asset` VALUES ('39', '运维管理', 'devops', '0', '0', 'node', '', '', 'mdi-lan-connect', '1', '30');
INSERT INTO `sys_asset` VALUES ('40', '导航管理', 'guide', '0', '0', 'node', '', '', 'mdi-internet-explorer', '1', '80');
INSERT INTO `sys_asset` VALUES ('41', '网址排序', 'sort', '40', '0/40', 'menu', 'home/guide.2', 'guide/sort', '', '1', '30');
INSERT INTO `sys_asset` VALUES ('42', '网址导航', 'site', '40', '0/40', 'menu', 'home/guide.1', 'guide/site', '', '1', '5');
-- ----------------------------
-- Table structure for sys_privilege
-- ----------------------------
DROP TABLE IF EXISTS `sys_privilege`;
CREATE TABLE `sys_privilege` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`master` varchar(50) DEFAULT NULL,
`master_value` varchar(100) DEFAULT NULL,
`access` varchar(50) DEFAULT NULL,
`access_value` varchar(200) DEFAULT NULL,
`permission` varchar(50) DEFAULT NULL,
`comment` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=288 DEFAULT CHARSET=utf8 COMMENT='权限';
-- ----------------------------
-- Records of sys_privilege
-- ----------------------------
INSERT INTO `sys_privilege` VALUES ('287', 'role', '1', 'menu', '42', 'guide:site', null);
INSERT INTO `sys_privilege` VALUES ('252', 'role', '17', 'menu', '33', 'home:deploy', null);
INSERT INTO `sys_privilege` VALUES ('250', 'role', '14', 'menu', '34', 'home:manifest', null);
INSERT INTO `sys_privilege` VALUES ('253', 'role', '17', 'menu', '34', 'home:manifest', null);
INSERT INTO `sys_privilege` VALUES ('285', 'role', '1', 'menu', '34', 'devops:manifest', null);
INSERT INTO `sys_privilege` VALUES ('286', 'role', '1', 'menu', '41', 'guide:sort', null);
INSERT INTO `sys_privilege` VALUES ('284', 'role', '1', 'menu', '33', 'devops:deploy', null);
INSERT INTO `sys_privilege` VALUES ('283', 'role', '1', 'menu', '38', 'photo:preview', null);
INSERT INTO `sys_privilege` VALUES ('282', 'role', '1', 'menu', '37', 'photo:upload', null);
INSERT INTO `sys_privilege` VALUES ('281', 'role', '1', 'menu', '8', 'sys:menu', null);
INSERT INTO `sys_privilege` VALUES ('280', 'role', '1', 'menu', '7', 'sys:role', null);
INSERT INTO `sys_privilege` VALUES ('279', 'role', '1', 'menu', '6', 'sys:user', null);
INSERT INTO `sys_privilege` VALUES ('278', 'role', '1', 'menu', '1', 'home:index', null);
INSERT INTO `sys_privilege` VALUES ('251', 'role', '17', 'menu', '1', 'home:index', null);
INSERT INTO `sys_privilege` VALUES ('249', 'role', '14', 'menu', '33', 'home:deploy', null);
INSERT INTO `sys_privilege` VALUES ('248', 'role', '14', 'menu', '1', 'home:index', null);
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pid` int(11) DEFAULT NULL COMMENT '父ID',
`name` varchar(50) DEFAULT NULL COMMENT '角色名称',
`code` varchar(30) DEFAULT NULL COMMENT '角色代码',
`comment` varchar(100) DEFAULT NULL COMMENT '角色描述',
`create_user` varchar(50) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', null, '管理员角色', 'admin', '管理员角色', 'admin', '2018-09-16 00:24:55');
INSERT INTO `sys_role` VALUES ('17', null, '测试角色', 'test1', '测试角色', 'admin', '2018-09-16 13:39:58');
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL COMMENT '用户名',
`password` varchar(80) DEFAULT NULL COMMENT '登录密码',
`salt` varchar(50) DEFAULT NULL COMMENT '盐',
`name` varchar(20) DEFAULT NULL COMMENT '真实姓名',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
`tel` varchar(15) DEFAULT NULL COMMENT '联系电话',
`org_id` int(11) DEFAULT NULL COMMENT '用户所属机构',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`create_user` varchar(50) DEFAULT NULL COMMENT '创建人',
`status` int(11) DEFAULT NULL COMMENT '用户状态',
`user_icon` varchar(100) DEFAULT NULL,
`note` varchar(255) DEFAULT NULL,
`expire_time` datetime DEFAULT NULL COMMENT '过期时间',
`login_count` int(11) DEFAULT NULL COMMENT '登陆次数',
`last_login_ip` varchar(20) DEFAULT NULL COMMENT '最后登陆IP',
`last_login_time` datetime DEFAULT NULL COMMENT '最后登陆时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', 'admin', 'b722097ee08ea4c20eae7958639c839e', 'b9f1d5d2b65231cd016e6d84979f7078', '管理员', '87166669@dyl.com', '18086776731', null, null, null, null, 'icon190779368587970139.JPG', '积极进取,持之以恒。', '2020-05-20 00:00:00', '934', '0:0:0:0:0:0:0:1', '2018-09-28 13:34:26');
INSERT INTO `sys_user` VALUES ('27', 'test', '8d1e533914f577ec50f478973fcd7245', 'dd06bb22476ddb60057daf36ba5ffe58', '测试', '88776699@qq.com', '88776699', null, '2018-09-13 14:11:29', 'admin', '1', null, null, '2019-09-12 14:11:19', '2', '0:0:0:0:0:0:0:1', '2018-09-16 00:27:06');
|
Java
|
UTF-8
| 4,534
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package wuzm.android.kframe.widget;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import wuzm.android.kframe.R;
/***
*
* @author wuzm
* @version 0.1beta
* @since 2015/1/18
*/
public class DefaultRefreshHeadView extends AbstractRefreshHeadView {
private Context mContext;
private float headTextSize = DEFAULT_HEAD_TEXTSIZE;
private static final float DEFAULT_HEAD_TEXTSIZE = 20f;
private ImageView headArrowIv;
private ImageView headRefreshIv;
private TextView headContentTv;
/*head arrow animations*/
private RotateAnimation rotateAnimation;
private RotateAnimation rotateResetAnimation;
/*head refresh animation*/
private RotateAnimation recycleRotateAnimation;
public DefaultRefreshHeadView(Context context) {
super(context);
}
public DefaultRefreshHeadView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DefaultRefreshHeadView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void init(Context context) {
mContext = context;
initAnim();
initView();
}
private void initView() {
RelativeLayout container = new RelativeLayout(mContext);
headArrowIv = new ImageView(mContext);
headArrowIv.setImageResource(R.drawable.down_arrow);
LayoutParams rlp = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlp.addRule(RelativeLayout.CENTER_VERTICAL);
container.addView(headArrowIv, rlp);
headRefreshIv = new ImageView(mContext);
headRefreshIv.setImageResource(R.drawable.refresh);
headRefreshIv.setVisibility(View.INVISIBLE);
container.addView(headRefreshIv, rlp);
headContentTv = new TextView(mContext);
headContentTv.setGravity(Gravity.CENTER);
headContentTv.setTextColor(Color.BLACK);
headContentTv.setTextSize(DEFAULT_HEAD_TEXTSIZE);
headContentTv.setText("下拉刷新");
rlp = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.CENTER_IN_PARENT);
container.addView(headContentTv, rlp);
container.setPadding(50, 50, 50, 50);
RelativeLayout.LayoutParams containerRLP = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
containerRLP.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
addView(container, containerRLP);
this.setBackgroundColor(Color.WHITE);
}
private void initAnim() {
rotateAnimation = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF,
0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(150);
rotateAnimation.setFillAfter(true);
rotateResetAnimation = new RotateAnimation(180, 0, RotateAnimation.RELATIVE_TO_SELF,
0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotateResetAnimation.setDuration(150);
rotateResetAnimation.setFillAfter(true);
recycleRotateAnimation =new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF,
0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
recycleRotateAnimation.setDuration(1200);
recycleRotateAnimation.setRepeatCount(RotateAnimation.INFINITE);
recycleRotateAnimation.setRepeatMode(RotateAnimation.RESTART);
}
@Override
public void setTextSize(float size) {
headTextSize = size;
headContentTv.setTextSize(size);
}
@Override
public void setTextSize(int resId) {
headTextSize = mContext.getResources().getDimension(resId);
headContentTv.setTextSize(headTextSize);
}
@Override
public void noneRefresh() {
headRefreshIv.clearAnimation();
headRefreshIv.setVisibility(View.INVISIBLE);
headArrowIv.setVisibility(View.VISIBLE);
headContentTv.setText("下拉刷新");
}
@Override
public void prepareRefresh() {
headArrowIv.startAnimation(rotateResetAnimation);
headContentTv.setText("下拉刷新");
}
@Override
public void relaseToRefresh() {
headArrowIv.startAnimation(rotateAnimation);
headContentTv.setText("释放刷新");
}
@Override
public void refreshing() {
headContentTv.setText("刷新中...");
headArrowIv.clearAnimation();
headArrowIv.setVisibility(View.INVISIBLE);
headRefreshIv.setVisibility(View.VISIBLE);
headRefreshIv.startAnimation(recycleRotateAnimation);
}
}
|
Java
|
UTF-8
| 508
| 1.742188
| 2
|
[] |
no_license
|
package com.pqsoft.leaseDate.service;
import java.util.Map;
import com.pqsoft.skyeye.api.Page;
import com.pqsoft.util.BaseUtil;
import com.pqsoft.util.PageUtil;
public class LeaseDateService {
private String basePath = "leaseDate.";
public Page queryPage(Map<String,Object> param){
param.put("TYPE_", "还款计划状态");
param.put("TYPE1_", "业务类型");
BaseUtil.getDataAllAuth(param);
return PageUtil.getPage(param, basePath+"getAllPayTask", basePath+"getAllPayTask_count");
}
}
|
Markdown
|
UTF-8
| 1,015
| 3.234375
| 3
|
[] |
no_license
|
#1 第1次实验
# 第一次实验
## 1.实验目标
(1)学习和搭建开发环境(Android Studio);
(2)了解GitHub网站的功能及提交的基本的要求;
## 2.实验步骤
(1)搭建开发环境(Android Studio 3.1正式版),运行(截图);
(2)加入Git项目(Fork),将项目克隆(Clone)到自己帐号下;
(3)$ git clone https://github.com/BeamGod/android-labs-2018/
(4)创建以学号命名的个人实验目录:com1614080901113。
其中,com开头表示计算机班,soft开头表示软件班,数字为个人学号。
(5)创建一个Java类:edu.hzuapps.androidlabs.com1614080901113.Com1614080901113Activity.java。
(6)提交代码并发Pull Request。
## 3.实验结果

## 4.实验体会
这是我的第一次实验,使用了编译器创建了我的第一个类,同时使用了git,使用了markdown语言,很有意思
|
SQL
|
UTF-8
| 2,474
| 4.03125
| 4
|
[] |
no_license
|
-- name: get-all-campaigns
-- gets all sms campaigns
SELECT *
FROM `sms-gateway`.sms_campaign
ORDER BY id DESC
LIMIT :offset, :limit;
-- name: fetch-one-campaign
-- gets one sms campaign
SELECT *
FROM `sms-gateway`.sms_campaign
WHERE id = :id;
-- name: fetch-active-campaigns
-- fetches all the active campaigns
SELECT *
FROM `sms-gateway`.sms_campaign
WHERE campaign_status = 0 AND
CURDATE() BETWEEN start_date AND end_date
ORDER BY date_created ASC;
-- name: fetch-campaign-messages
-- fetches campaign messages
SELECT *
FROM `sms-gateway`.sms_campaign_message
WHERE sms_campaign_id = :campaign_id
ORDER BY id DESC
LIMIT :offset, :limit;
-- name: create-campaign<!
-- creates a campaign
INSERT INTO `sms-gateway`.sms_campaign (campaign_type, start_date, end_date, cron_expression,
created_by, tenant_id, campaign_name, message_template,
schedule_once, campaign_criteria)
VALUES
(cast(:campaign_type AS UNSIGNED), :start_date, :end_date, :cron_expression,
:created_by, :tenant_id, :campaign_name, :message_template, :schedule_once, :campaign_criteria);
-- name: create-sms-log<!
-- create a new sms log
INSERT INTO `sms-gateway`.sms_logs (campaign_id, sms_to, sms_from, message) VALUES
(:campaign_id, :sms_to, :sms_from, :message);
-- name: update-message-after-sending!
-- updates the message after sending
UPDATE `sms-gateway`.sms_logs
SET bulk_id = :bulk_id, message_id = :message_id, request_status = 1,
status_message = :status, sent_log = :log
WHERE id = :id;
-- name: get-dirty-messages
-- gets the messages whose status hasn't changes
SELECT DISTINCT (bulk_id) AS bulk_id
FROM `sms-gateway`.sms_logs
WHERE status_changed = 0 AND bulk_id IS NOT NULL
ORDER BY id DESC
LIMIT 20;
-- name: clean-dirty-messages!
-- updates the dirty messages
UPDATE `sms-gateway`.sms_logs
SET status_changed = 1, request_status = 2, status_message = :status, sent_log = :log
WHERE message_id = :message_id;
-- name: delete-campaign!
-- deletes a campaign
DELETE FROM `sms-gateway`.sms_campaign
WHERE id = :id;
-- name: delete-campaign-messages!
-- deletes campaign messages
DELETE FROM `sms-gateway`.sms_campaign_message
WHERE sms_campaign_id = :id;
-- name: create-campaign-message<!
-- creates a campaign message
INSERT INTO `sms-gateway`.sms_campaign_message (sms_campaign_id, destination, message, sender)
VALUES
(:sms_campaign_id, :stination, :message, :sender);
|
Markdown
|
UTF-8
| 3,125
| 3.703125
| 4
|
[] |
no_license
|
## Gauss' Law
- **Gauss' law** = a mathematical model that relates **net flux($\phi$)** and enclosed charge
- Mathematically it looks like this
$$ \epsilon_0 \Sigma \phi = \Sigma q $$
- Or, substituting the definition of net flux, we get
$$ \epsilon_0 \oint \bigg( \vec{E} \cdot d\vec{A} \bigg) = \Sigma q $$
- The charge of $\Sigma q$ determines whether the flux is *inwards* or *outwards*
* If $\Sigma q$ is *positive*, $\Sigma \phi$ points outward
* If $\Sigma q$ is *negative*, $\Sigma \phi$ points inward
* If $\Sigma q$ is zero, $\Sigma \phi$ is a zero
- The interesting thing about Gauss' law is that charges external to the enclosed volume do not affect the net flux
* Think about that: *if you put a charged particle right up against the barrier, the field lines would change but the net flux wouldn't*
### Deriving Coulomb's Law with Gauss' Law
- Recall **Coulomb's law**
$$ \vec{E} = \frac{1}{4 \pi \epsilon_0} \frac{q}{r^2} $$
- This can actually be proven using Gauss' law
- Imagine we had a particle of point q
* Now superimpose a gaussian sphere that envelops that particle
+ We can use the integral form of Gauss' law to set up an equation
$$ \epsilon_0 \oint \bigg( \vec{E} \cdot d\vec{A} \bigg) = \Sigma q $$
- A property of dot products is that
$$ \vec{a} \cdot \vec{b} = |\vec{a}| |\vec{b}| cos(\theta) $$
- where $\theta$ is the angle between $\vec{a}$ and $\vec{b}$
- Using that fact, we can rewrite our equation as
$$ \epsilon_0 \oint \bigg( |\vec{E}| |d\vec{A}| cos(\theta) \bigg) = \Sigma q $$
- Since our problem is basically a one-particle problem, we know that $\vec{E}$ will radiate outwards perpendicular to concecntric spheres
* As such, $\vec{E}$ and $d\vec{A}$ actually point in the same direction
+ So, $\theta$ is zero
$$ \epsilon_0 \oint \bigg( |\vec{E}| |d\vec{A}| cos(0) \bigg) = \Sigma q $$
$$ \epsilon_0 \oint \bigg( |\vec{E}| |d\vec{A}| (1) \bigg) = \Sigma q $$
$$ \epsilon_0 \oint \bigg( |\vec{E}| |d\vec{A}| \bigg) = \Sigma q $$
- At this point, we can rewrite $\Sigma q$ as just $q$, since our gaussian sphere only contains that one particle
$$ \epsilon_0 \oint \bigg( |\vec{E}| |d\vec{A}| \bigg) = q $$
- Now, the direction of $\vec{E}$ clearly changes from point to point on the gaussian sphere
* However, the *magnitude* does not change
+ So, we can pull it out of the integral
$$ \epsilon_0 |\vec{E}| \oint |d\vec{A}| = q $$
- Now, surface integrals, which is what that $\oint$ symbol denotes, aren't in the scope of this course
* Really, all you need to know is that they integrate a function over every point on a surface(in this case, the surface area of the sphere)
* If the function your surface integrates is just $1$, then the surface integral returns the surface area
+ So, really, our surface integral just returns the surface area of our sphere
- Which, if you remember from geometry is
$$ SA = 4 \pi r^2 $$
- Substituting that, we get
$$ \epsilon_0 |\vec{E}| \big( 4 \pi r^2 \big)= q $$
- Then, some simple algebra gets us to
$$ |\vec{E}| = \frac{1}{4 \pi \epsilon_0} \frac{q}{r^2} $$
|
Java
|
UTF-8
| 7,927
| 3.3125
| 3
|
[] |
no_license
|
public class Logic {
int score = 0;
int yahztees = 0;
Gameplay GameplayObject = new Gameplay();
private int[] dice;
public Logic(int[] dice){
this.dice = dice;
}
private int ones(){
int score = 0;
for (int i = 0; i < 5; i++){
if (dice[i] == 1){
score = score+1;
}
}
return score;
}
private int twos(){
int score = 0;
for (int i = 0; i < 5; i++){
if (dice[i] == 2){
score = score + 2;
}
}
return score;
}
private int threes(){
int score = 0;
for (int i = 0; i < 5; i++){
if (dice[i] == 3){
score = score + 3;
}
}
return score;
}
private int fours(){
int score = 0;
for (int i = 0; i < 5; i++){
if (dice[i] == 4){
score = score + 4;
}
}
return score;
}
private int fives(){
int score = 0;
for (int i = 0; i < 5; i++){
if (dice[i] == 5){
score = score + 5;
}
}
return score;
}
private int sixes(){
int score = 0;
for (int i = 0; i < 5; i++){
if (dice[i] == 6){
score = score + 6;
}
}
return score;
}
private void bonus(){
if (score>62)
//add 25 to the actual score
score = score + 25;
}
private int threeOfaKind(){
int score = 0;
/*int counter;
for (int a = 6; a >= 0; a--) {
counter = 0;
for (int i = 0; i < 5; i++) {
if (dice[i] == a){
score = score + dice[i];
counter++;
}
}
if (counter == 3) {
return score;
}
else score = 0;
}*/
int [] numOfEachNum = new int[6];
for (int i = 1; i < 7; i++) {
for (int die : dice) {
if (die == i){
++numOfEachNum[i-1];
}
}
}
for (int i = 0; i < numOfEachNum.length; i++) {
if (numOfEachNum[i] >= 3){
score = (i+1)*numOfEachNum[i];
}
}
return score;
}
private int fourOfaKind(){
int score = 0;
//int counter;
int [] numOfEachNum = new int[6];
for (int i = 1; i < 7; i++) {
for (int die : dice
) {
if (die == i){
++numOfEachNum[i-1];
}
}
}
for (int i = 0; i < numOfEachNum.length; i++) {
if (numOfEachNum[i] >= 4){
score = (i+1)*numOfEachNum[i];
}
}
return score;
}
private int fullHouse(){
int score = 0;
/*int gg = 0;
int counter = 0;
int c = 0;
int skip;
for (int a = 6; a >= 0; a--) {
counter = 0;
for (int i = 0; i < 5; i++) {
if (dice[i] == a){
score = score + dice[i];
counter++;
}
if (counter==3) {
skip = a;
for (int b = 6; b >= 0; b--) {
if (b == skip)
b = skip + 1;
else{
c = 0;
for (int f = 0; f < 5; f++) {
if (dice[f] == b){
gg = gg + dice[f];
c++;
}
else gg = 0;
}
}
}
}
else score = 0;
}
}
if(counter == 3 && c == 2){
return score + gg;
}*/
int [] numOfEachNum = new int[6];
boolean[] fullHouse = new boolean[]{
false, false
};
for (int i = 1; i < 7; i++) {
for (int die : dice
) {
if (die == i){
++numOfEachNum[i-1];
}
}
}
for (int num:numOfEachNum) {
if(num == 2){
fullHouse[0] = true;
}
if (num == 3){
fullHouse[1] = true;
}
}
if (fullHouse[0] && fullHouse[1]){
score = 25;
}
System.out.println("Fullhouse 3 of kind: " + fullHouse[1]);
System.out.println("Fullhouse 2 of kind: " + fullHouse[0]);
return score;
//return 0;
}
private int yahtzee(){
score = 0;
int [] numOfEachNum = new int[6];
for (int i = 1; i < 7; i++) {
for (int die : dice
) {
if (die == i){
++numOfEachNum[i-1];
}
}
}
for (int num:numOfEachNum) {
if (num == 5){
score = 50;
break;
}
}
return score;
//return 0;
}
/*private int chance(){
int score = 0;
for (int i = 0; i < 6; i++){
score = score + dice[i];
}
return score;
}*/
private int smStraight(){
//int[] dice = dice;
int lowestDie = 7;
for (int die: dice) {
if (die < lowestDie){
lowestDie = die;
}
}
int counter = 0;
for (int die: dice) {
if (die == (lowestDie+1)){
++ counter;
++ lowestDie;
}
}
if (counter >= 3){
return 30;
}
else{
return 0;
}
}
private int lgStraight(){
//int[] dice = dice;
int lowestDie = 7;
for (int die: dice) {
if (die < lowestDie){
lowestDie = die;
}
}
int counter = 0;
for (int die: dice) {
if (die == (lowestDie+1)){
++ counter;
++ lowestDie;
}
}
if (counter == 4){
return 40;
}
else{
return 0;
}
}
public int[] getPossibilities(boolean[] excludes){
int[] possibleScores = new int[]{
0,0,0,0,
0,0,0,0,
0,0,0,0
};
if (!excludes[0]){
possibleScores[0] = ones();
}
if (!excludes[1]){
possibleScores[1] = twos();
}
if (!excludes[2]){
possibleScores[2] = threes();
}
if (!excludes[3]){
possibleScores[3] = fours();
}
if (!excludes[4]){
possibleScores[4] = fives();
}
if (!excludes[5]){
possibleScores[5] = sixes();
}
if (!excludes[6]){
possibleScores[6] = threeOfaKind();
}
if (!excludes[7]){
possibleScores[7] = fourOfaKind();
}
if (!excludes[8]){
possibleScores[8] = fullHouse();
}
if (!excludes[9]){
possibleScores[9] = smStraight();
}
if (!excludes[10]){
possibleScores[10] = lgStraight();
}
possibleScores[11] = yahtzee();
for (int num: possibleScores
) {
System.out.println("Score: " + num);
}
for (int num: dice) {
System.out.println("Die: " + num);
}
return possibleScores;
}
public void yahtzeeCounter(){
yahztees++;
}
}
|
C++
|
UTF-8
| 12,395
| 2.6875
| 3
|
[] |
no_license
|
#include "Supervisorio.h"
#include "ui_Supervisorio.h"
Supervisorio::Supervisorio(QWidget *parent) : QMainWindow(parent), ui(new Ui::Supervisorio) {
// Seta a User Interface
ui->setupUi(this);
// Busca as portas seriais disponíveis e mostra no combo box
serial = new Serial();
// Alimenta a lista de portas Seriais
portasDisponiveis = serial->listaPortas();
// Adiciona um valor em branco nesta lista, pois como a seleção da porta é pela alteração de índice do combo box
// se tiver apenas 1 porta disponível não é possível mudar de índice, impedindo que o lógica de seleção de porta funcione
portasDisponiveis.push_front("");
// Para cada ítem da lista adiciona uma opção no combo box
for(int i = 0 ; i < portasDisponiveis.size(); i++) {
ui->comboBoxPortasSeriais->addItem(portasDisponiveis.at(i)); // Adiciona uma opção no combo box
}
// Define informações de tempo de aquisição e amostragem
leituraDaSerial = new QTimer();
atualizaTela = new QTimer();
// Define a quantidade de amostras no gráfico e inicializa os vetores dos eixos x e y
qtdPontosGrafico = 2000;
for (int i=0; i < qtdPontosGrafico; i++) {
xAxis << 0;
yAxis << 0;
}
//
customPlot = new QCustomPlot();
customPlot->addGraph();
ui->verticalLayout->addWidget(customPlot);
// Inicializa Variáveis globais de controle
fatorDeConversao = (float) (5.0/1023.0); // Fator de conversão para multiplicar pelo valor enviado pelo arduino
isPortaSelecionada = false; // Inicializa como falso a variável que define que a porta serial está configurada corretamente
indiceGrafico = 0; // Variável que controla onde inserir os valores lidos no gráfico
stringArquivo.clear(); // Limpa o Vetor utilizado para gravar em arquivo
connect(ui->comboBoxPortasSeriais, SIGNAL(currentIndexChanged(int)), this, SLOT(selecionaPortaSerial(int))); // Selecionar a porta serial escolhida no combo box
connect(leituraDaSerial, SIGNAL(timeout()), this, SLOT(leDadosDaPortaSerial())); // Aquisição do sinal
connect(atualizaTela, SIGNAL(timeout()), this, SLOT(atualizaDados())); // Amostragem
connect(ui->pushButtonSalvar, SIGNAL(clicked()), this, SLOT(salvarEmArquivo())); // Salvar em Arquivo
connect(ui->pushButtonIniciar, SIGNAL(clicked()), this, SLOT(iniciaLeitura())); // Inicia Leitura
connect(ui->pushButtonParar, SIGNAL(clicked()), this, SLOT(paraLeitura())); // Para Leitura
}
Supervisorio::~Supervisorio() {
delete ui;
portaSelecionada.close();
}
void Supervisorio::selecionaPortaSerial(int porta) {
// Conforme o indice que for passado por parâmetro, irá configurar a porta serial com os dados da porta selecionada no combo box
portaSelecionada.setPortName(serial->selecionaPorta(porta).portName());
portaSelecionada.setBaudRate(QSerialPort::Baud115200); // Velocidade da comunicação deve ser alta para evitar perda de dados
portaSelecionada.setDataBits(QSerialPort::Data8);
portaSelecionada.setParity(QSerialPort::NoParity);
portaSelecionada.setStopBits(QSerialPort::OneStop);
// Valida se com os dados configurados anteriormente consegue abrir a porta serial configurada
// Se abrir seta a variável global que define que a porta serial está configurada corretamente
// Se não abrir, informa o usuário
if (portaSelecionada.open(QIODevice::ReadWrite)) {
isPortaSelecionada = portaSelecionada.setBaudRate(QSerialPort::Baud115200) &
portaSelecionada.setStopBits(QSerialPort::OneStop) &
portaSelecionada.setDataBits(QSerialPort::Data8) &
portaSelecionada.setParity(QSerialPort::NoParity) &
portaSelecionada.setFlowControl(QSerialPort::NoFlowControl);
} else {
std::cout << "Não foi possível abrir a porta serial selecionada" << std::endl;
}
}
void Supervisorio::leDadosDaPortaSerial() {
// Se a porta serial estiver configurada corretamente lê os dados e alimenta o buffer
// Se não avisa o usuário que nenhuma porta está configurada corretamente
if (isPortaSelecionada) {
stringLida += portaSelecionada.readAll();
} else {
std::cout << "Não há porta Serial Selecionada!" << std::endl;
}
}
void Supervisorio::plotaGrafico(float x, float y) {
// Cria um gráfico com base nos vetores X e Y
// Incrementa variável de controle para que o valor repassado seja inserido na próxima posição do vetor
indiceGrafico++;
// Se a variável de controle for maior ou igual que a quantidade de amostras da tela, zera para substituir os valores desde o começo
if (indiceGrafico >= qtdPontosGrafico) {
indiceGrafico = 0;
}
// Substitui o valor anterior do vetor pelo valor atual no indice da veriável de controle
yAxis.replace(indiceGrafico,y);
xAxis.replace(indiceGrafico,indiceGrafico);
/*****************************************************************
// Forma para plotar o gráfico igual ao osciloscópio
if ((indiceGrafico += x) <= qtdPontosGrafico+1) { // Se a variável de controle mais 1 é menor que a quantidade de amostras
if(yAxis.isEmpty() || xAxis.isEmpty()) { // Verifica se os vetores estão vazios
yAxis << y; // Se estiver insere o valor do y passado por parâmetro
xAxis << 0; // Insere o valor 0 para o eixo x
} else { // Se os vetores não forem vazios
yAxis.push_back(y); // Insere o valor passado por parâmetro depois da ultima posição
xAxis.push_back(x+(xAxis.last())); // Insere o valor da ultima posição + 1 depois da ultima posição
}
} else { // Se a variálvel de controle mais 1 não for menor que a quantidade de amostras
yAxis.remove(0); // Remove o primeiro valor do eixo y
xAxis.remove(0); // Remove o primeiro valor do eixo x
yAxis.push_back(y); // Insere na ultima posicao do vetor o valor para y passado por parâmetro
for (int i=0; i<xAxis.size(); i++) { // Para o valor do eixo x é necessário realizar um deslocamento para a esquerda dos valores anteriores
xAxis.replace(i,(xAxis.at(i)-1)); // Move o valor da posição atual - 1 para a posição anterior
}
xAxis.push_back(x+(xAxis.last())); // Insere o valor da ultima posição mais 1
}
*****************************************************************/
customPlot->graph(0)->setData(xAxis,yAxis); // Seta os eixos x e y com os vetores alimentados anteriormente
customPlot->xAxis->setLabel("Tempo (ms)"); // Seta o nome do eixo x
customPlot->xAxis->setRange(0, qtdPontosGrafico); // Seta o tamanho do gráfico no eixo x
customPlot->yAxis->setLabel("Variação da Tensão"); // Seta o nome do eixo y
customPlot->yAxis->setRange(0,5); // Seta tamanho do gráfico no eixo y
customPlot->replot(); // Pinta o gráfico
}
void Supervisorio::atualizaDados() {
// Se a Porta serial foi configurada corretamente processa 1 valor
if (isPortaSelecionada) {
// Se o buffer com os valores lidos pela porta serial for maior que 0 processa 1 valor
if (stringLida.size() > 0) {
QString valorLido; // variável temporária que vai armazenar 1 valor do buffer
int primeiroRegistro = stringLida.indexOf('['); // busca a primeira posição do [, identificador de início de um valor
int ultimoRegistro = stringLida.indexOf(']'); // busca a primeira posição do ], identificador de fim de um valor
// Se encontrou o identificador [ e encontrou o identificador ] e a posição o identificador ] é maior que a posição do identificador [
if ((primeiroRegistro != -1) && (ultimoRegistro != -1) && (ultimoRegistro > primeiroRegistro)) {
int j=0; // Variável que controla a posição na string temporária que o caractere atual será inserido
// Percorre os caracteres entre os delimitadores [ e ] armazenando na variável temporária
for (int i= primeiroRegistro+1; i<ultimoRegistro; i++) {
valorLido.insert(j,stringLida.at(i)); // Insere na variável temporária o caractere lido entre os delimitadores [] do buffer
j++;
}
// Converte o valor armazenado na variável temporária para float
float valorConvertido = valorLido.toFloat();
// Multiplica o valor convertido com o fator de conversão para gerar o valor entre 0 e 5
valorConvertido *= fatorDeConversao;
// Imprime o gráfico
plotaGrafico(1,valorConvertido);
// Armazena no buffer de gravação em arquivo o valor lido e convertido
if (valorLido.size() > 0 && valorConvertido > 0) {
QString valorParaArquivo; // Variável temporária para converter o valor
valorParaArquivo.setNum(valorConvertido); // Converte de Float para String
stringArquivo += valorParaArquivo.toLatin1()+";\n"; // Incrementa o buffer com o a string convertida
}
}
// Limpa as variáveis temporárias e remove do buffer o que já foi lido e convertido
valorLido.clear(); // Limpa variável temporária usada para montar o valor
// Tratamento de exceções para limpeza do buffer de leitura
if (primeiroRegistro = -1) // Se não encontrou o identificado [
stringLida.remove(0,ultimoRegistro+1); // Exclui do buffer tudo que tem antes do delimitador ] pois houve alguma falha na comunicação
else if (primeiroRegistro != -1 && ultimoRegistro != -1) // Senão verifica se os dois delimitadores foram encontrados
stringLida.remove(0,ultimoRegistro+1); // Se foram, exclui tudo que estava entre os delimitadores, incluindo os delimitadores
} // Se não entrar em nenhuma das opções é por que achou apenas o delimitador de inicio [
// com isso o processamento acabou passando a leitura, então não limpa o buffer
// e espera a próxima execução para ter ambos os delimitadores
}
}
void Supervisorio::salvarEmArquivo() {
// Solicita um diretório e um nome de arquivo para gravar o buffer com os valores convertidos
diretorio = QFileDialog::getSaveFileName(this, tr("Abrir Arquivo"), QDir::currentPath(), tr("Files (*.txt)"));
// Verifica se foi informado um diretório, se não foi, informa o usuário
if (diretorio.size() > 0) {
// Cria um arquivo no diretório
arquivo = new QFile(diretorio);
// Tenta abrir o arquivo, se conseguir grava o buffer com os valores convertidos, se não conseguir informa o usuário
if (!arquivo->open(QIODevice::ReadWrite | QIODevice::Text)) {
std::cout << "Não foi possível abrir o arquivo: " << diretorio.toStdString() << std::endl;
} else {
arquivo->write(stringArquivo); // Grava o buffer com os valores convertidos no arquivo
arquivo->close(); // Fecha o arquivo
}
} else {
std::cout << "Não foi possível localizar o diretório: "<< diretorio.toStdString() << std::endl;
}
}
void Supervisorio::iniciaLeitura() {
// Inicia os contadores para ler e processar os dados da porta serial
stringLida.clear(); // Limpa o buffer de leitura
atualizaTela->start(5); // Tempo de Amostragem
leituraDaSerial->start(5); // Tempo de Leitura
}
void Supervisorio::paraLeitura() {
// Para os contadores de leitura e processamento
atualizaTela->stop();
leituraDaSerial->stop();
stringLida.clear(); // Limpa buffer de leitura
}
|
C#
|
UTF-8
| 1,269
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
//
// The default behavior is to discard the overridden method, but this doesn't work for constructors.
// So, instead of picking a default, the code has to explain what to do.
//
//
// With this attribute, the system will try to automatically merge the code for the constructors, based on different cases:
//
// 1) There's no matching constructor
// a) Default constructor is missing => Fail, it's not clear what should happen.
// b) Default constructor is present => Merge the initialization of the overridden object with the current one.
//
// 2) There's a matching constructor => Merge the initialization of the overridden object with the current one.
//
//
// Use paired with 'AliasForMethod' to guide how to merge,
// so you can name otherwise unnameable entities, like constructors.
//
[TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_MergeWithTargetImplementationAttribute" )]
[AttributeUsage(AttributeTargets.Constructor)]
public sealed class MergeWithTargetImplementationAttribute : Attribute
{
}
}
|
Java
|
UTF-8
| 2,320
| 2.796875
| 3
|
[] |
no_license
|
package infovis.scatterplot;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class MouseController implements MouseListener, MouseMotionListener {
private Model model = null;
private View view = null;
private int x = 0, y = 0;
private int w = 0, h = 0;
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
x = arg0.getX();
y = arg0.getY();
}
public void mouseReleased(MouseEvent arg0) {
int anzahl_rect = model.getRanges().size();
int width_rect = 0;
if(view.getWidth()<view.getHeight()) {
width_rect = (int)Math.floor((view.getWidth()-view.getPadding())/anzahl_rect);
}
else {
width_rect = (int)Math.floor((view.getHeight()-view.getPadding())/anzahl_rect);
}
int rectX = (int) ((x-view.getPadding())/width_rect);
int rectY = (int) ((y-view.getPadding())/width_rect);
for (Data d : model.getList()) {
double minX = model.getRanges().get(rectX).getMin()-1.0;
double maxX = model.getRanges().get(rectX).getMax()+1.0;
double absX = maxX-minX;
double valX = d.getValue(rectX);
double prozX = (100.0/absX)*(valX-minX);
double posX = width_rect/100.0*prozX;
double minY = model.getRanges().get(rectY).getMin()-1.0;
double maxY = model.getRanges().get(rectY).getMax()+1.0;
double absY = maxY-minY;
double valY = d.getValue(rectY);
double prozY = (100.0/absY)*(valY-minY);
double posY = width_rect/100.0*prozY;
boolean inBox =
x <= view.getPadding()+width_rect*rectX+posX &&
(x+w) >= view.getPadding()+width_rect*rectX+posX+2 &&
y <= view.getPadding()+width_rect*rectY+posY &&
(y+h) >= view.getPadding()+width_rect*rectY+posY+2;
if(inBox) {
d.setColor(Color.red);
} else {
d.setColor(Color.black);
}
view.repaint();
}
}
public void mouseDragged(MouseEvent arg0) {
w = arg0.getX()-x;
h = arg0.getY()-y;
view.getMarkerRectangle().setRect(x,y,w,h);
view.repaint();
}
public void mouseMoved(MouseEvent arg0) {
}
public void setModel(Model model) {
this.model = model;
}
public void setView(View view) {
this.view = view;
}
}
|
Python
|
UTF-8
| 2,700
| 3.625
| 4
|
[] |
no_license
|
"""
Задание 3.
Приведен код, формирующий из введенного числа
обратное по порядку входящих в него
цифр и вывести на экран.
Сделайте профилировку каждого алгоритма через cProfile и через timeit
Сделайте вывод, какая из трех реализаций эффективнее и почему
"""
import timeit
import cProfile
def revers(enter_num, revers_num=0):
if enter_num == 0:
return ''
else:
num = enter_num % 10
revers_num = (revers_num + num / 10) * 10
enter_num //= 10
return str(num) + revers(enter_num, revers_num)
def revers_2(enter_num, revers_num=0):
while enter_num != 0:
num = enter_num % 10
revers_num = (revers_num + num / 10) * 10
enter_num //= 10
return revers_num
def revers_3(enter_num):
enter_num = str(enter_num)
revers_num = enter_num[::-1]
return revers_num
print(revers(12345))
print(revers_2(12345))
print(revers_3(12345))
print(timeit.timeit(f"revers({12345})", setup="from __main__ import revers", number=1000))
print(timeit.timeit(f"revers_2({12345})", setup="from __main__ import revers_2", number=1000))
print(timeit.timeit(f"revers_3({12345})", setup="from __main__ import revers_3", number=1000))
cProfile.run(f'revers({1234567891234567891234566666666666666666666665555555555555555555555})')
cProfile.run(f'revers_2({1234567891234567891234566666666666666666666665555555555555555555555})')
cProfile.run(f'revers_3({1234567891234567891234566666666666666666666665555555555555555555555})')
"""
1. Исправил ошибку в 1 функции иначе она не возвращала данные
2. Профилирование для второй и третьей функцией показывает одинаковый результат так как они очень простые
и быстро выполняются, однако если замерять время то видно что функция 3 выполянется намногобыстрее,
это связано с тем, что вместо цикла и выполнения операций выполется только переконвертация в строку
и вывод в обратном порядке
4. Самая медленная это функция с рекурсией это видно как по таймеру так и по проилированию где видно, что функция
выполняется по разу за каждую цифру в числе.
"""
|
C#
|
UTF-8
| 652
| 2.859375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EX_three
{
class Du_lieu
{
public void ShowDL()
{
Console.Write("Nhap n=");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n+1];
arr[0] = 1;
string gep = "";
Console.WriteLine(arr[0]);
for (int i = 1; i < n;i++ )
{
gep = string.Concat(arr[0], "-", arr[n-1]);
}
Console.WriteLine(gep);
Console.ReadLine();
}
}
}
|
Java
|
UTF-8
| 380
| 2.4375
| 2
|
[] |
no_license
|
public class SampleMain{
public static void main(String[] args){
PartsStore partsStore = new PartsStore();
partsStore.FindPartsWithBrand("Hard Drive", "Lenovo");
partsStore.FindCheapestMemory(32);
partsStore.UpdateStock();
partsStore.FindCheapestMemory(16);
partsStore.TotalPrice("GPU", "Asus", "GeForce RTX 2080");
partsStore.FindFastestCPU();
}
}
|
JavaScript
|
UTF-8
| 9,101
| 2.90625
| 3
|
[] |
no_license
|
Chart.defaults.global.defaultFontFamily = 'Roboto';
Chart.defaults.global.defaultFontColor = '#333';
Chart.Legend.prototype.afterFit = function() {
this.height = this.height + 5;
};
Chart.pluginService.register({
beforeDraw: function(chart) {
if (chart.config.options.elements.center) {
// Get ctx from string
var ctx = chart.chart.ctx;
// Get options from the center object in options
var centerConfig = chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var maxFontSize = centerConfig.maxFontSize || 75;
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
// Start with a base font of 30px
ctx.font = "35px " + fontStyle;
// Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
var minFontSize = centerConfig.minFontSize;
var lineHeight = centerConfig.lineHeight || 25;
var wrapText = false;
if (minFontSize === undefined) {
minFontSize = 20;
}
if (minFontSize && fontSizeToUse < minFontSize) {
fontSizeToUse = minFontSize;
wrapText = true;
}
// Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px " + fontStyle;
ctx.fillStyle = color;
if (!wrapText) {
ctx.fillText(txt, centerX, centerY);
return;
}
var words = txt.split(' ');
var line = '';
var lines = [];
// Break words up into multiple lines if necessary
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > elementWidth && n > 0) {
lines.push(line);
line = words[n] + ' ';
} else {
line = testLine;
}
}
// Move the center up depending on line height and number of lines
centerY -= (lines.length / 2) * lineHeight;
for (var n = 0; n < lines.length; n++) {
ctx.fillText(lines[n], centerX, centerY);
centerY += lineHeight;
}
//Draw text in center
ctx.fillText(line, centerX, centerY);
}
}
});
function resetCanvas(){
$('.container-fluid').remove();
$('body').append('<div class="container-fluid"></div>')
for (let i=1; i<9; i+=2) {
$('.container-fluid').append(`
<div class="row">
<div class="col-6">
<canvas id="chart${i}"></canvas>
</div>
<div class="col-6">
<canvas id="chart${i+1}"></canvas>
</div>
</div>`)
}
}
function changeTitle(title){
var origin = document.querySelector("#title");
if (title=="Sex"){
title="Sex"
}
origin.innerHTML = `Number of Students per ${title} per Year`;
}
function testChartPie(students, year, attr, chartid) {
students = students.filter(function(d){ return d.Academic_Year == year });
var terms = d3.group(students, d => d[attr]);
terms_data = []
terms_labels = []
terms_colors = []
var keyValues = []
for (key of terms.keys()) {
keyValues.push([ key, terms.get(key).length ])
}
keyValues.sort(function compare(kv1, kv2) {
return kv2[0].localeCompare(kv1[0])
})
for (val of keyValues) {
terms_labels.push(val[0]);
terms_data.push(val[1]);
}
var myColor = d3.scaleOrdinal().domain(terms_labels)
.range(d3.schemeSet2)
for (val of keyValues) {
terms_colors.push(myColor(val[0]))
}
var chart = new Chart(chartid, {
type: 'doughnut',
options: {
elements: {
center: {
text: year,
color: '#FF6384', // Default is #000000
fontStyle: 'Arial', // Default is Arial
sidePadding: 20, // Default is 20 (as a percentage)
minFontSize: 25, // Default is 20 (in px), set to false and text will not wrap.
lineHeight: 25 // Default is 25 (in px), used for when text wraps
}
},
maintainAspectRatio: true,
responsive: true,
legend: {
display: true
},
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 50,
borderWidth: 5,
color: 'white',
anchor:'end',
},
},
},
data: {
labels: terms_labels,
datasets: [
{
data: terms_data,
backgroundColor: terms_colors
}
],
}
})
}
function testChartBar(students, year, attr, chartid) {
students = students.filter(function(d){ return d.Academic_Year == year });
var terms = d3.group(students, d => d[attr]);
terms_data = []
terms_labels = []
terms_colors = []
var keyValues = []
for (key of terms.keys()) {
keyValues.push([ key, terms.get(key).length ])
}
keyValues.sort(function compare(kv1, kv2) {
return kv2[0].localeCompare(kv1[0])
})
for (val of keyValues) {
terms_labels.push(val[0]);
terms_data.push(val[1]);
}
var myColor = d3.scaleOrdinal().domain(terms_labels)
.range(d3.schemeSet2)
for (val of keyValues) {
terms_colors.push(myColor(val[0]))
}
var chart = new Chart(chartid, {
type: 'bar',
options: {
maintainAspectRatio: true,
responsive: true,
legend: {
display: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2)+"%";
return percentage;
},
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 50,
borderWidth: 5,
color: 'white',
anchor:'end',
},
},
scales: {
xAxes: [
{
scaleLabel: {
display: true,
labelString: attr,
fontSize: 16
}
}
]
}
},
data: {
labels: terms_labels,
datasets: [
{
data: terms_data,
backgroundColor: terms_colors
}
],
}
})
}
function draw(attr){
resetCanvas();
d3.select('canvas').selectAll('*').remove();
d3.csv('https://vohi0311.pythonanywhere.com/allData').then(function(result) {
testChartPie(result, "2015-16", attr, 'chart1');
testChartPie(result, "2016-17", attr, 'chart3');
testChartPie(result, "2017-18", attr, 'chart5');
testChartPie(result, "2018-19", attr, 'chart7');
changeTitle(attr)
});
d3.csv('https://vohi0311.pythonanywhere.com/allData').then(function(result) {
testChartBar(result, "2015-16", attr, 'chart2');
testChartBar(result, "2016-17", attr, 'chart4');
testChartBar(result, "2017-18", attr, 'chart6');
testChartBar(result, "2018-19", attr, 'chart8');
});
}
// d3.csv('http://127.0.0.1:5000/all_data.csv').then(function(result) {
// testChartPie(result, "2015-16", 'chart1');
// testChartPie(result, "2016-17", 'chart3');
// });
// d3.csv('http://127.0.0.1:5000/all_data.csv').then(function(result) {
// testChartBar(result, "2015-16", 'chart2');
// testChartBar(result, "2016-17", 'chart4');
// });
|
JavaScript
|
UTF-8
| 1,638
| 4.375
| 4
|
[] |
no_license
|
// 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
//
// 注意:
// 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
//
// 示例 1:
// 输入:x = 123
// 输出:321
// 示例 2:
// 输入:x = -123
// 输出:-321
// 示例 3:
// 输入:x = 120
// 输出:21
// 示例 4:
// 输入:x = 0
// 输出:0
//方法一:使用字符串变换的方法。缺点:用了很多基本库,影响性能的其实。
function reverse(num) {
var intMax = Math.pow(2, 31);
var symbol = num > 0 ? '' : '-';
var str = Math.abs(num) + '';
var arr = [];
for (let i = 0; i < str.length; i++) {
arr.unshift(str[i]);
}
var res = (symbol + arr.join('')) - 0;
if (res > intMax - 1 || res < -intMax) {
return 0;
} else {
return res
}
}
// console.log(reverse(123456));
// console.log(reverse(123400));
// console.log(reverse(-123400));
//方法二:使用数学方法.因为是十进制的数,所以可以根据这个规则去进行数字的获取。
function reverse2(num) {
var intMax = Math.pow(2, 31);
var res = 0;
var pop = 0;
while (num != 0) {
pop = num % 10;
num = parseInt(num / 10);
res = res * 10 + pop;
if (res > intMax - 1 || res < -intMax) {
return 0
}
}
return res;
}
// console.log(reverse2(123456));
// console.log(reverse2(123400));
// console.log(reverse2(-123400));
|
Java
|
UTF-8
| 1,542
| 2.421875
| 2
|
[] |
no_license
|
package com.sivalabs.springboot;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Controller
class MySampleController
{
@Autowired
PersonService personService;
@RequestMapping({"/"})
public String welcome(Model model) {
return "welcome.html";
}
@RequestMapping(value="/users/{id}",
method=RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Person findPersonById(@PathVariable("id") int id)
{
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(null,"abcd"));
persons.add(new Person(null,"xyz"));
persons.add(new Person(null,"xxx"));
persons.add(new Person(null,"pqr"));
personService.save(persons);
Person person = new Person();
person.setId(id);
person.setName("PersonName "+id);
return person;
}
}
|
Markdown
|
UTF-8
| 42,065
| 3.09375
| 3
|
[] |
no_license
|
* 1 為促進性別地位之實質平等,消除性別歧視,維護人格尊嚴,厚植並建立性別平等之教育資源與環境,特制定本法。本法未規定者,適用其他法律之規定。
> 釋:按憲法第七條規定:「中華民國人民,無分男女、宗教、種族、階級、黨派,在法律上一律平等。」,次按憲法增修條文第十條第六項規定:「國家應維護婦女之人格尊嚴、保障婦女之人身安全、消除性別歧視、促進兩性地位之實質平等。」,為落實上開憲法規定意旨,並厚植性別平等教育之資源與環境,提昇教育本質與內涵,建設性別平等之公民社會,爰制定本法。
* 2 本法用詞定義如下:一、性別平等教育:指以教育方式教導尊重多元性別差異,消除性別歧視,促進性別地位之實質平等。二、學校:指公私立各級學校。三、性侵害:指性侵害犯罪防治法所稱性侵害犯罪之行為。四、性騷擾:指符合下列情形之一,且未達性侵害之程度者:(一)以明示或暗示之方式,從事不受歡迎且具有性意味或性別歧視之言詞或行為,致影響他人之人格尊嚴、學習、或工作之機會或表現者。(二)以性或性別有關之行為,作為自己或他人獲得、喪失或減損其學習或工作有關權益之條件者。五、性霸凌:指透過語言、肢體或其他暴力,對於他人之性別特徵、性別特質、性傾向或性別認同進行貶抑、攻擊或威脅之行為且非屬性騷擾者。六、性別認同:指個人對自我歸屬性別的自我認知與接受。七、校園性侵害、性騷擾或性霸凌事件:指性侵害、性騷擾或性霸凌事件之一方為學校校長、教師、職員、工友或學生,他方為學生者。
> 釋:一、在兒少性/性別意識觀念形成或偏差時即給予正確的養成與矯治,才能建立健全的性別關係互動。性別平等教育之內涵不只是男女性別的平等對待,更是多元性別觀點的包容,對人的尊重不應因其外表性別而有不同。爰修正第一款之定義。二、鑑於校園性霸凌事件有增多與嚴重趨勢,原法律對性霸凌尚未有明確定義,僅能適用其他相關法律,或視為性騷擾事件處理。爰參照相關論述,增訂第五款定義性霸凌,以發揮教育輔導之作用。三、配合性霸凌之定義,「性別認同」之概念有進一步釐清之必要,爰增訂第六款。四、原第五款移列為第七款,並酌作文字修正。
* 3 本法所稱主管機關:在中央為教育部;在直轄市為直轄市政府;在縣(市)為縣(市)政府。
> 釋:一、明定本法之主管機關。本法所規定者為性別平等教育事項,故主管機關由中央及地方教育行政機關任之。二、縣市政府,雖然教育局是實際負責性別平等教育事項的單位,但鑑於對外行文單位是縣市政府而非教育局,故以縣市政府為地方主管機關。三、參考性侵害防治法,以直轄市政府為主管機關,為因應地方自治之規定,不再以局處為主管機關。
* 4 中央主管機關應設性別平等教育委員會,其任務如下:一、研擬全國性之性別平等教育相關法規、政策及年度實施計畫。二、協調及整合相關資源,協助並補助地方主管機關及所主管學校、社教機構落實性別平等教育之實施與發展。三、督導考核地方主管機關及所主管學校、社教機構性別平等教育相關工作之實施。四、推動性別平等教育之課程、教學、評量與相關問題之研究與發展。五、規劃及辦理性別平等教育人員之培訓。六、提供性別平等教育相關事項之諮詢服務及調查、處理與本法有關之案件。七、推動全國性有關性別平等之家庭教育及社會教育。八、其他關於全國性之性別平等教育事務。
> 釋:明定中央主管機關應設性別平等教育委員會,並參考目前教育部兩性平等教育委員會推動之工作項目,定其任務。
* 5 直轄市、縣(市)主管機關應設性別平等教育委員會,其任務如下:一、研擬地方之性別平等教育相關法規、政策及年度實施計畫。二、協調及整合相關資源,並協助所主管學校、社教機構落實性別平等教育之實施與發展。三、督導考核所主管學校、社教機構性別平等教育相關工作之實施。四、推動性別平等教育之課程、教學、評量及相關問題之研究發展。五、提供所主管學校、社教機構性別平等教育相關事項之諮詢服務及調查、處理與本法有關之案件。六、辦理所主管學校教育人員及相關人員之在職進修。七、推動地方有關性別平等之家庭教育及社會教育。八、其他關於地方之性別平等教育事務。
> 釋:明定直轄市、縣(市)主管機關應設性別平等教育委員會及其任務。
* 6 學校應設性別平等教育委員會,其任務如下:一、統整學校各單位相關資源,擬訂性別平等教育實施計畫,落實並檢視其實施成果。二、規劃或辦理學生、教職員工及家長性別平等教育相關活動。三、研發並推廣性別平等教育之課程、教學及評量。四、研擬性別平等教育實施與校園性侵害及性騷擾之防治規定,建立機制,並協調及整合相關資源。五、調查及處理與本法有關之案件。六、規劃及建立性別平等之安全校園空間。七、推動社區有關性別平等之家庭教育與社會教育。八、其他關於學校或社區之性別平等教育事務。
> 釋:一、明定學校應設性別平等教育委員會及其任務,以落實性別平等教育之具體成效。二、目前部分學校校園性侵害或性騷擾事件,係交由獨立之委員會或小組處理,鑑於獨立之委員會或小組之委員,與學校另設之兩性平等教育委員會之委員多有重複,為避免資源之浪費及提高效率,且性侵害或性騷擾事件並不經常發生,該處理性侵害或性騷擾事件獨立之委員會或小組與學校另設之兩性平等教育委員會允有合併之必要,爰明定學校性別平等教育委員會之任務,包括規劃或辦理性別平等教育及調查、處理與本法有關之案件。
* 7 中央主管機關之性別平等教育委員會,置委員十七人至二十三人,採任期制,以教育部部長為主任委員,其中女性委員應占委員總數二分之一以上;性別平等教育相關領域之專家學者、民間團體代表及實務工作者之委員合計,應占委員總數三分之二以上。前項性別平等教育委員會每三個月應至少開會一次,並應由專人處理有關業務;其組織、會議及其他相關事項,由中央主管機關定之。
> 釋:一、第一項明定中央主管機關性別平等教育委員會委員人數、比例及採任期制,其中為促進性別地位之實質平等,並明定女性委員應占委員總數二分之一以上,理由如下:(一)目前中央機關所有各式委員會成員之性別比例,仍未臻平衡,欲變更現狀,以女性、兩性或性別為主之委員會,更須提升女性之參與率,以落實性別平等。(二)在長久性別失衡及不平等之社會及文化環境中,兩性之成長經驗顯有差異,相較之下,女性較常遭受限制及差別待遇,鑑於女性之性別經驗較易受召喚,且亦較能體察前述文化需要改進之處,爰期藉量化帶動質化之改變。二、為具體推動性別平等委員會之決議事項,於第二項明定應由專人處理有關業務。
* 8 直轄市、縣(市)主管機關之性別平等教育委員會,置委員九人至二十三人,採任期制,以直轄市、縣(市)首長為主任委員,其中女性委員應占委員總數二分之一以上;性別平等教育相關領域之專家學者、民間團體代表及實務工作者之委員合計,應占委員總數三分之一以上。前項性別平等教育委員會每三個月應至少開會一次,並應由專人處理有關業務;其組織、會議及其他相關事項,由直轄市、縣(市)主管機關定之。
> 釋:一、第一項明定直轄市、縣(市)主管機關性別平等教育委員會委員人數、比例及採任期制。二、專家學者、民間團體代表及實務工作者之委員合計,應占委員總數三分之一以上之規定,乃期地方層級之委員會得善用專家學者、民間代表及實務工作者之知識及經驗,以利其任務之遂行,且兼具地方特色及專業性。三、為具體推動性別平等委員會之決議事項,於第二項明定應由專人處理有關業務。
* 9 學校之性別平等教育委員會,置委員五人至二十一人,採任期制,以校長為主任委員,其中女性委員應占委員總數二分之一以上,並得聘具性別平等意識之教師代表、職工代表、家長代表、學生代表及性別平等教育相關領域之專家學者為委員。前項性別平等教育委員會每學期應至少開會一次,並應由專人處理有關業務;其組織、會議及其他相關事項,由學校定之。
> 釋:一、第一項明定學校性別平等教育委員會委員人數、比例及採任期制。二、基於女性較常遭受差別待遇考量,學校性別平等教育委員會女性委員應占委員總數二分之一以上。如有學校女性人員不足之情況,得聘具性別平等意識之教師代表、職工代表、家長代表、學生代表及性別平等教育相關領域之專家學者擔任委員。三、為避免學校之性別平等教育委員會委員於處理校內相關事務時,相互袒護或利益糾結,以致造成偏頗,或資源不足(例如,缺少法律或心理專業人員),爰規定得聘校外委員。四、為具體推動性別平等委員會之決議事項,於第二項明定應由專人處理有關業務。
* 10 中央、直轄市、縣(市)主管機關及學校每年應參考所設之性別平等教育委員會所擬各項實施方案編列經費預算。
> 釋:為落實性別平等教育之工作、執行性別平等教育委員會所研訂之計畫,並保障長期推動、穩定性別平等教育之發展,各級主管機關每年應編列經費預算,預算之執行效果列入督導考核。
* 11 主管機關應督導考核所主管學校、社教機構或下級機關辦理性別平等教育相關工作,並提供必要之協助;其績效優良者,應給予獎勵,績效不良者,應予糾正並輔導改進。
> 釋:明定主管機關對於所主管學校、社教機構或下級主管機關辦理性別平等教育相關工作者,除應給予督導及協助外,並因其績效之優劣,而給予獎勵或糾正。
* 12 學校應提供性別平等之學習環境,尊重及考量學生與教職員工之不同性別、性別特質、性別認同或性傾向,並建立安全之校園空間。學校應訂定性別平等教育實施規定,並公告周知。
> 釋:目前性別平等觀念一般還停留在「生理性別」的階段,即男女二元對立。至於性傾向、性別特質或性別認同與主流觀念不同者,或因「心理性別」與生理有異不易被重視,或由於外顯的氣質與一般性別刻板印象不一致,容易遭致歧視,這也是校園性霸凌事件發生的深層因素。破除性別刻板印象走出二元對立的藩籬,才能達到尊重性別多元差異、促進性別地位之實質平等,實現性別平等教育之目標。學校作為性別教育的重要場域,應提供性別平等之基本學習環境,更應體現在對不同性別、性別特質、性別認同及性傾向者需求的尊重與考量上。不能只關照某一類型而忽略不同性別特質的需求,否則可能造成其學習發展受到限制而形成不公平現象。是以修正並合併原條文第一項與第二項。
* 13 學校之招生及就學許可不得有性別、性別特質、性別認同或性傾向之差別待遇。但基於歷史傳統、特定教育目標或其他非因性別因素之正當理由,經該管主管機關核准而設置之學校、班級、課程者,不在此限。
> 釋:本法內容缺失不足包括侷限於各級公私立學校場域,未能涵括家庭教育、親職教育、社會教育等;集中於校園性騷擾或性侵害事件之處理機制,有關多元性別的條文比重過少;對不同一般性別認知的「性傾向」、「性別特質」、「性別認同」未進一步界定,並加以保障。相較於事件發生後的處理與輔導,制度上建立一個安全健康的學習環境,保障學生受教權與資源不因多元性別差異而有不同待遇,才是正本清源之道。
* 14 學校不得因學生之性別、性別特質、性別認同或性傾向而給予教學、活動、評量、獎懲、福利及服務上之差別待遇。但性質僅適合特定性別、性別特質、性別認同或性傾向者,不在此限。學校應對因性別、性別特質、性別認同或性傾向而處於不利處境之學生積極提供協助,以改善其處境。
> 釋:一、本法內容缺失不足包括侷限於各級公私立學校場域,未能涵括家庭教育、親職教育、社會教育等;集中於校園性騷擾或性侵害事件之處理機制,有關多元性別的條文比重過少;對不同一般性別認知的「性傾向」、「性別特質」、「性別認同」未進一步界定,並加以保障。相較於事件發生後的處理與輔導,制度上建立一個安全健康的學習環境,保障學生受教權與資源不因多元性別差異而有不同待遇,才是正本清源之道。二、對於因性別、性別特質、性別認同或性傾向而處於不利處境之學生,應積極提供協助,以改善其處境。三、第三項關於懷孕學生受教權維護及協助之規定,與其他項對於性別、性別特質、性別認同或性傾向處境之規範內涵有異,基於一文一條主義,爰建議另立一條,第三項予以刪除。
* 14.1 學校應積極維護懷孕學生之受教權,並提供必要之協助。
> 釋:一、本條新增。二、原條文第十四條第三項移列。
* 15 教職員工之職前教育、新進人員培訓、在職進修及教育行政主管人員之儲訓課程,應納入性別平等教育之內容;其中師資培育之大學之教育專業課程,應有性別平等教育相關課程。
> 釋:一、性別相關議題雖然過去皆已有之,直至近年來方受到應有之重視。傳統師資培育課程中缺乏對於性別教育之探討,以至於教師教學及對待學生時受限於性別盲點而不自知,甚至造成性別偏見、性別歧視之反教育效果。爰所有教師皆應接受性別平等教育之職前與在職訓練。於教師職前養成教育中,有必要納入性別教育諸多議題之探討,以協助所有準教師激發性別意識、培養對自己經驗之反省能力,增加對學校體制中之性別預設及運作機制之敏感度及洞察力,協助學生於日常生活實踐及面對相關議題時,得覺知自己所處社會位置及立場,增加對不同經驗及價值之理解、尊重與關懷,並發展性別平等教育識能。二、師資培育法第十條規定:「師資培育課程……應著重道德品格之陶冶、民主法治之涵泳、專業精神及教學知能之培養。」性侵害犯罪防治法第八條規定:「各級中小學每學年應至少有四小時以上之性侵害防治教育課程。」於九十學年度開始實施之九年一貫課程,已將性別平等教育納入課程綱要之中,成為所有中小學教師所需具備專業知能之一部分。爰師資培育課程中應納入兩性平等教育之內涵。其中師資培育職前教育之性別平等課程實施方式有三:(一)將性別平等教育觀念融入所有職前教育科目中;(二)開設性別平等教育之專門課程;(三)以上二者並行。至一般教師之性別平等教育識能可包含至少三階段:(一)初階:開發與培養性別敏感度,覺察自我之性別知覺;(二)進階:培養將性別觀點融入教學之能力;(三)高階:培養規劃性別平等教育活動、設計或編寫相關教材之能力及處理校園性侵害或性騷擾事件之能力。三、教育行政主管人員為所有教育活動之推動者,尤須具備正確之性別平等教育觀念,故其儲備訓練課程中應加入性別教育課程。
* 16 學校之考績委員會、申訴評議委員會、教師評審委員會及中央與直轄市、縣(市)主管機關之教師申訴評議委員會之組成,任一性別委員應占委員總數三分之一以上。但學校之考績委員會及教師評審委員會因該校任一性別教師人數少於委員總數三分之一者,不在此限。學校或主管機關相關組織未符合前項規定者,應自本法施行之日起一年內完成改組。
> 釋:一、考績委員會、各級各類申訴評議委員會、教師評審委員會皆為影響學生及教職員工權益之最關鍵單位。為落實性別平等教育,上開處理人事委員會之組成,應符合性別平等原則。惟考慮某些學校或科系之性別比例懸殊,為避免委員會窒礙難行,爰於第一項規定任一性別應占委員總數三分之一以上,並增列但書,以符實際。二、前項所定各委員會所遴聘之委員均為任期制,如依本法第三十八條規定,該些未合前項規定者,均應自施行之日起隨即改組,恐造成委員會工作之中斷或混亂,經衡酌此些攸關學生及教職員工權益組織之業務推動及前項修正意旨,爰於第二項明定其應自本法施行之日起一年內完成改組,以為緩衝。
* 17 學校之課程設置及活動設計,應鼓勵學生發揮潛能,不得因性別而有差別待遇。國民中小學除應將性別平等教育融入課程外,每學期應實施性別平等教育相關課程或活動至少四小時。高級中等學校及專科學校五年制前三年應將性別平等教育融入課程。大專校院應廣開性別研究相關課程。學校應發展符合性別平等之課程規劃與評量方式。
> 釋:一、第一項學校之課程設置及活動設計,應鼓勵學生多方發揮潛能與興趣,不應以性別做為區隔,避免因循過去國中男生習工藝,女生學家政及高中職及大學男生學軍訓,女生學護理之例子。除課程之設置外,課程內涵是否具有平等之性別意識,亦須加以檢視。另外各項校園及學生社團等活動,亦不應因性別而有差別待遇。二、九年一貫新課程實施後,國民中小學除了必須將性別平等教育適切融入各學習領域之外,並應善用百分之二十之空白課程,爰於第二項明定每學期實施至少四個小時之性別平等教育。三、配合高級中等學校及專科學校五年制前三年之課程設計,於第三項明定應將性別平等教育融入課程,以培養學生具性別平等意識。四、第四項明定大學在通識課程、教育學程以及各系所一般課程內應廣開性別研究(含婦女研究、性別平等教育、同志研究等)相關課程,提供學生修習之機會。五、第五項明定學校應發展無性別偏見之測驗工具及評量方式,以取代傳統之紙筆測驗及評量方式。如根據女性主義教學法,以口語、討論或文字敘述等方式,鼓勵學生多方表達,建立自我主體,並尊重他人之差異性。
* 18 學校教材之編寫、審查及選用,應符合性別平等教育原則;教材內容應平衡反映不同性別之歷史貢獻及生活經驗,並呈現多元之性別觀點。
> 釋:教材為學校教育最重要之教學素材,其內容是否符合性別平等原則,於形塑學生之自我認知、性別意識及相互尊重、多元包容等能力上,扮演關鍵角色。爰明定所有教材,自編寫、審查到選用,均應符合性別平等之原則。又所有教材,無論是係人物出現之次數、樣態、文選作者、內容、意識形態及插圖,均應破除性別偏見、性別刻板印象及男尊女卑之觀念,避免使用男性專屬語言,應平衡呈現兩性及多元之性別觀點。
* 19 教師使用教材及從事教育活動時,應具備性別平等意識,破除性別刻板印象,避免性別偏見及性別歧視。教師應鼓勵學生修習非傳統性別之學科領域。
> 釋:一、教師除必須時時從事性別意識之自我檢視之外,更須具備活用教材教法之能力,以有效之教學法克服教材中仍未達完善之部分。教師或可採先讓學生產生認知衝突,輔以合作反省及批判思考之教學法,協助學生認知自身之性別意識,培養性別平等之觀念及實踐能力。鑑於教師之教育活動包括正式、非正式與潛在三個面向:正式係指班級之教學;非正式如班級經營、社團等;潛在活動如師生互動、對話、教師間之互動、學校人事結構等,爰教師乃將性別平等教育落實於課堂及所有教育情境之關鍵人物。無論是在正式、非正式或潛在課程之教學中,教師均應具有性別平權觀念,並將之具體展現,爰明定於第一項。至於教師建構此種觀念之作法如下:(一)避免性別角色刻板化之工作分派,提供所有學生參與各項學習活動之機會。(二)教師以身示教,教學行為必須具有性別平等之楷模。(三)於班級教學之討論中,將有關性別與族群等之迷思概念提出來以為反思活動。(四)於班級經營方面,應避免有性別隔離或歧視之現象。(五)提供學生對各種不同多元角色進行試探,勿灌輸男女學生生涯選擇植基於傳統性別分工觀念。(六)全面檢視所採用之各科教材及補充教材是否有性別偏見或失衡現象。(七)學校之空間、體育用品及學校設備、校規之訂定必須確保性別之公平性。(八)提供男女學生合作學習、尊重差異之團體互動經驗。二、教師於教導或輔導學生時,無論是其所修習之課程、選擇之科系、未來之生涯或親密關係之探索,均不應以性別作區隔或有差別待遇,爰於第一項明定學生如表示對非傳統性別之學科領域有興趣,教師應加以鼓勵,並協助了解之意旨。
* 20 為預防與處理校園性侵害、性騷擾或性霸凌事件,中央主管機關應訂定校園性侵害、性騷擾或性霸凌之防治準則;其內容應包括學校安全規劃、校內外教學與人際互動注意事項、校園性侵害、性騷擾或性霸凌之處理機制、程序及救濟方法。學校應依前項準則訂定防治規定,並公告周知。
> 釋:納入性霸凌之定義與防治後,相關條文亦應依其性質加以適用。期以建立周密的性霸凌事件處理程序及相關機制,在實務上於性霸凌事件發生之初即妥善加以處置,導正偏差扭曲之性別觀念,並保障行為人及被害者在內當事人的權益,重建未來常態化的健全性別互動關係。
* 21 學校校長、教師、職員或工友知悉服務學校發生疑似校園性侵害、性騷擾或性霸凌事件者,除應立即依學校防治規定所定權責,依性侵害犯罪防治法、兒童及少年福利法、身心障礙者權益保障法及其他相關法律規定通報外,並應向學校及當地直轄市、縣(市)主管機關通報,至遲不得超過二十四小時。學校校長、教師、職員或工友不得偽造、變造、湮滅或隱匿他人所犯校園性侵害、性騷擾或性霸凌事件之證據。學校或主管機關處理校園性侵害、性騷擾或性霸凌事件,應將該事件交由所設之性別平等教育委員會調查處理。
> 釋:一、依原法規,學校校長、教師、職員或工友於執行職務,知悉服務學校發生疑似校園性侵害、性騷擾或性霸凌事件時,應視事件及受害者不同,依性侵害犯罪防治法第八條、兒童及少年福利法第三十四條或身心障礙者權益保障法第七十六條及其授權法規等規定,立即向當地直轄市、縣(市)主管機關通報。為使學校及主管機關得迅速知悉,俾得立即採行相關因應措施,爰於第一項增訂學校校長、教師、職員或工友並應依學校防治規定所定權責,在二十四小時內,向學校及當地直轄市、縣(市)主管機關通報。二、因校園性侵害、性騷擾或性霸凌事件除須由性別平等教育委員會依本法相關規定調查處理外,亦可能進入司法程序,其相關證據之保全自屬重要,鑑於刑法第一百六十五條湮滅證據罪之規定,限於刑事被告案件方有適用,爰增訂第二項,明定學校校長、教師、職員或工友不得偽造、變造、湮滅或隱匿他人所犯校園性侵害、性騷擾或性霸凌事件之證據,並於修正條文第三十六條增訂違反上開義務之處罰,期杜絕教育人員隱匿校園性侵害、性騷擾或性霸凌事件之發生。三、原條文移列為第三項,並酌作修正。
* 22 學校或主管機關調查處理校園性侵害、性騷擾或性霸凌事件時,應秉持客觀、公正、專業之原則,給予雙方當事人充分陳述意見及答辯之機會。但應避免重複詢問。當事人及檢舉人之姓名或其他足以辨識身分之資料,除有調查之必要或基於公共安全之考量者外,應予保密。
> 釋:配合第二十條條文修正,規範性霸凌事件之原則。
* 23 學校或主管機關於調查處理校園性侵害、性騷擾或性霸凌事件期間,得採取必要之處置,以保障當事人之受教權或工作權。
> 釋:配合第二十條條文修正,規範學校處置性霸凌事件,應保障當事人之受教權或工作權。
* 24 學校或主管機關處理校園性侵害、性騷擾或性霸凌事件,應告知當事人或其法定代理人其得主張之權益及各種救濟途徑,或轉介至相關機構處理,必要時,應提供心理輔導、保護措施或其他協助;對檢舉人有受侵害之虞者,並應提供必要之保護措施或其他協助。前項心理輔導、保護措施或其他協助,學校或主管機關得委請醫師、心理師、社會工作師或律師等專業人員為之。
> 釋:一、納入性霸凌之定義與防治後,相關條文亦應依其性質加以適用。期以建立周密的性霸凌事件處理程序及相關機制,在實務上於性霸凌事件發生之初即妥善加以處置,導正偏差扭曲之性別觀念,並保障行為人及被害者在內當事人的權益,重建未來常態化的健全性別互動關係。二、考量行為人及被害人雙方皆應有被告知其得主張之權益及各種救濟途徑之權力,將「被害人」修正為「當事人」外;另增訂保護檢舉人、引進專業人士協助等規定,以求周延。三、校園性侵擾或霸凌事件是教育或學生問題的呈現,其千頭萬緒,涉及教育、心理、法律、醫學、社工等諸多議題。若以目前清一色是教育體系出身的老師擔任輔導工作,必有難以應付之缺失,發生事件後再處分老師其實並不公平。心理輔導乃至保護措施及其他協助涉及多項專業,應委請醫師、心理師、社會工作師與律師等共同為之,才會見其成效,使輔導工作發揮其功能。爰增訂第二項。
* 25 校園性侵害、性騷擾或性霸凌事件經學校或主管機關調查屬實後,應依相關法律或法規規定自行或將加害人移送其他權責機關懲處。學校、主管機關或其他權責機關為性騷擾或性霸凌事件之懲處時,應命加害人接受心理輔導之處置,並得命其為下列一款或數款之處置:一、經被害人或其法定代理人之同意,向被害人道歉。二、接受八小時之性別平等教育相關課程。三、其他符合教育目的之措施。校園性騷擾或性霸凌事件情節輕微者,學校、主管機關或其他權責機關得僅依前項規定為必要之處置。第一項懲處涉及加害人身分之改變時,應給予其書面陳述意見之機會。第二項之處置,應由該懲處之學校或主管機關執行,執行時並應採取必要之措施,以確保加害人之配合遵守。
> 釋:一、納入性霸凌之定義與防治後,相關條文亦應依其性質加以適用。期以建立周密的性霸凌事件處理程序及相關機制,在實務上於性霸凌事件發生之初即妥善加以處置,導正偏差扭曲之性別觀念,並保障行為人及被害者在內當事人的權益,重建未來常態化的健全性別互動關係。二、性霸凌多屬存於學生間的性別觀念偏差行為,其性別意識與價值觀仍未定型,處罰威嚇可能造成性別觀念之持續扭曲,反不利未來之性別關係發展。從保護學生與性別平等教育立場應從寬處理,強調宜教不宜罰原則,並強化心理輔導的重要性與必要性。爰修正本條第二項為應命加害人接受心理輔導,使其成為強制性義務。三、現行「校園性侵害或性騷擾事件防治準則」第二十四條相關規定亦建議提升至母法加以規範,增訂第三項明定情節輕微者,得僅依第二項規定為必要之處置,而不依相關法律或法規加以懲處。四、對包括心理輔導、道歉、接受性別平等教育課程及其他符合教育目的措施等相關處置之執行,亦應採取必要措施,以確保行為人配合遵守方能落實。爰增訂第五項。
* 26 學校或主管機關調查校園性侵害、性騷擾或性霸凌事件過程中,得視情況就相關事項、處理方式及原則予以說明,並得於事件處理完成後,經被害人或其法定代理人之同意,將事件之有無、樣態及處理方式予以公布。但不得揭露當事人之姓名或其他足以識別其身分之資料。
> 釋:配合第二十條條文修正,規範性霸凌事件之當事人身分資訊保護。
* 27 學校或主管機關應建立校園性侵害、性騷擾或性霸凌事件及加害人之檔案資料。前項加害人轉至其他學校就讀或服務時,主管機關及原就讀或服務之學校應於知悉後一個月內,通報加害人現就讀或服務之學校。接獲前項通報之學校,應對加害人實施必要之追蹤輔導,非有正當理由,並不得公布加害人之姓名或其他足以識別其身分之資料。學校任用教育人員或進用其他專職、兼職人員前,應依性侵害犯罪防治法之規定,查閱其有無性侵害之犯罪紀錄,或曾經主管機關或學校性別平等教育委員會調查有性侵害、性騷擾或性霸凌行為屬實並經該管主管機關核准解聘或不續聘者。
> 釋:一、規範性霸凌事件之檔案資料通報機制。二、第一項酌作文字修正。三、第二項、第三項未修正。四、增訂第四項,以確認應徵者是否有相關性侵害犯罪事實或有不適任教師情事,俾有效監控並杜絕有相關性侵害、性騷擾或性霸凌之教職員進入校園。
* 28 學校違反本法規定時,被害人或其法定代理人得向學校所屬主管機關申請調查。校園性侵害、性騷擾或性霸凌事件之被害人或其法定代理人得以書面向行為人所屬學校申請調查。但學校之首長為加害人時,應向學校所屬主管機關申請調查。任何人知悉前二項之事件時,得依其規定程序向學校或主管機關檢舉之。
> 釋:配合第二十條條文修正,規範保障性霸凌事件之被害人檢舉機制。
* 29 學校或主管機關於接獲調查申請或檢舉時,應於二十日內以書面通知申請人或檢舉人是否受理。學校或主管機關於接獲調查申請或檢舉時,有下列情形之一者,應不予受理:一、非屬本法所規定之事項者。二、申請人或檢舉人未具真實姓名。三、同一事件已處理完畢者。前項不受理之書面通知,應敘明理由。申請人或檢舉人於第一項之期限內未收到通知或接獲不受理通知之次日起二十日內,得以書面具明理由,向學校或主管機關申復。
> 釋:一、第一項明定學校或主管機關應於規定期間內通知申請人或檢舉人是否受理。二、第二項明定不予受理之情形。三、為確保程序正義原則,於第三項明定接受申請調查之單位因故不予受理或未於規定時間內回覆申請人是否受理時,申請人或檢舉人得提起申復。
* 30 學校或主管機關接獲前條第一項之申請或檢舉後,除有前條第二項所定事由外,應於三日內交由所設之性別平等教育委員會調查處理。學校或主管機關之性別平等教育委員會處理前項事件時,得成立調查小組調查之。前項小組成員應具性別平等意識,女性人數比例,應占成員總數二分之一以上,必要時,部分小組成員得外聘。處理校園性侵害、性騷擾或性霸凌事件所成立之調查小組,其成員中具性侵害、性騷擾或性霸凌事件調查專業素養之專家學者之人數比例於學校應占成員總數三分之一以上,於主管機關應占成員總數二分之一以上;雙方當事人分屬不同學校時,並應有申請人學校代表。性別平等教育委員會或調查小組依本法規定進行調查時,行為人、申請人及受邀協助調查之人或單位,應予配合,並提供相關資料。行政程序法有關管轄、移送、迴避、送達、補正等相關規定,於本法適用或準用之。性別平等教育委員會之調查處理,不受該事件司法程序進行之影響。性別平等教育委員會為調查處理時,應衡酌雙方當事人之權力差距。
> 釋:配合第二十條條文修正,規範霸凌事件之被害人檢舉後,後續調查機制。
* 31 學校或主管機關性別平等教育委員會應於受理申請或檢舉後二個月內完成調查。必要時,得延長之,延長以二次為限,每次不得逾一個月,並應通知申請人、檢舉人及行為人。性別平等教育委員會調查完成後,應將調查報告及處理建議,以書面向其所屬學校或主管機關提出報告。學校或主管機關應於接獲前項調查報告後二個月內,自行或移送相關權責機關依本法或相關法律或法規規定議處,並將處理之結果,以書面載明事實及理由通知申請人、檢舉人及行為人。學校或主管機關為前項議處前,得要求性別平等教育委員會之代表列席說明。
> 釋:一、為符合調查過程之專業原則,於第一項及第二項明定學校或主管機關性別平等教育委員會應於兩個月完成調查,並向學校或主管機關提出書面報告。調查時程以兩個月為原則,必要時得延長之。延長以二次為限,每次不得逾一個月。二、第三項明定學校或主管機關於接獲調查報告之處理及應將處理結果以書面載明事實及理由通知申請人、檢舉人及行為人,以示審慎。三、為提升調查結果之信服度,以確保其懲處決議之適當性,於第四項明定學校或主管機關得要求性別平等教育委員會之代表列席說明。
* 32 申請人及行為人對於前條第三項處理之結果有不服者,得於收到書面通知次日起二十日內,以書面具明理由向學校或主管機關申復。前項申復以一次為限。學校或主管機關發現調查程序有重大瑕疵或有足以影響原調查認定之新事實、新證據時,得要求性別平等教育委員會重新調查。
> 釋:一、為避免不當之調查結果及提供申請人及行為人合理之救濟機會,爰於第一項明定對於調查結果不服者,得提起申復之規定。二、第二項明定申復以一次為限。三、為確認性別平等教育委員會調查結果之正確性,第三項明定賦予學校或主管機關行政審查權限,於發現調查程序有重大瑕疵時,得要求性別平等教育委員會重新調查。此外,為提供當事雙方救濟機會,亦明定學校或主管機關於有足以影響原調查認定之新事實、新證據時,得要求性別平等教育委員會重新調查。
* 33 性別平等教育委員會於接獲前條學校或主管機關重新調查之要求時,應另組調查小組;其調查處理程序,依本法之相關規定。
> 釋:為確保調查結果之公正性,明定性別平等教育委員會因前條所列原因被學校或主管機關要求重新調查時,應另組調查小組,其調查處理程序仍應依循本法之相關規定。
* 34 申請人或行為人對學校或主管機關之申復結果不服,得於接獲書面通知書之次日起三十日內,依下列規定提起救濟:一、公私立學校校長、教師:依教師法之規定。二、公立學校依公務人員任用法任用之職員及中華民國七十四年五月三日教育人員任用條例施行前未納入銓敘之職員:依公務人員保障法之規定。三、私立學校職員:依性別工作平等法之規定。四、公私立學校工友:依性別工作平等法之規定。五、公私立學校學生:依規定向所屬學校提起申訴。
> 釋:將本條第一項第三款及第四款中之「兩性」工作平等法修正為「性別」工作平等法。
* 35 學校及主管機關對於與本法事件有關之事實認定,應依據其所設性別平等教育委員會之調查報告。法院對於前項事實之認定,應審酌各級性別平等教育委員會之調查報告。
> 釋:一、第一項明定學校及主管機關對於與本法事件有關之事實認定,應依據其所設之性別平等教育委員會之調查報告。二、鑑於調查處理違反本法規定或校園性侵害或性騷擾事件之性別平等教育委員會或調查小組,依本法規定均應具有性別平等意識及相關專業能力,故其調查報告應符合專業,公正及中立之要求,爰於第二項明定法院對於前項事實之認定,應審酌各級性別平等教育委員會之調查報告。
* 36 學校違反第十三條、第十四條、第十四條之一、第十六條、第二十條第二項、第二十二條第二項或第二十七條第三項規定者,應處新臺幣一萬元以上十萬元以下罰鍰。行為人違反第三十條第四項規定而無正當理由者,由學校報請主管機關處新臺幣一萬元以上五萬元以下罰鍰,並得連續處罰至其配合或提供相關資料為止。學校校長、教師、職員或工友有下列情形之一者,處新臺幣三萬元以上十五萬元以下罰鍰:一、違反第二十一條第一項規定,未於二十四小時內,向學校及當地直轄市、縣(市)主管機關通報。二、違反第二十一條第二項規定,偽造、變造、湮滅或隱匿他人所犯校園性騷擾或性霸凌事件之證據。
> 釋:一、配合新增第十四條之一條文,爰於第一項中增列「第十四條之一」。二、第二項未修正。三、依兒童及少年福利法第六十一條規定,負有通報義務人員(含教育人員)未通報且無正當理由者,處新臺幣六千元以上三萬元以下罰鍰。因學校校長、教師、職員或工友負有維護校園安全,保障學生權益之責任,應對其課以更高之要求,爰增訂第三項,提高學校教育人員違反本法通報規定之罰鍰額度,並將偽造、變造、湮滅或隱匿他人所犯校園性騷擾事件證據者,一併納入處罰對象。
* 36.1 學校校長、教師、職員或工友違反第二十一條第一項所定疑似校園性侵害事件之通報規定,致再度發生校園性侵害事件;或偽造、變造、湮滅或隱匿他人所犯校園性侵害事件之證據者,應依法予以解聘或免職。學校或主管機關對違反前項規定之人員,應依法告發。
> 釋:一、本條新增。二、學校校長、教師、職員或工友若因違反第二十一條第一項所定疑似校園性侵害事件之通報規定,致使受害學生增加或被害者遭受第二次甚至更多傷害等結果,其已不適合繼續在教育現場服務;而偽造、變造、湮滅或隱匿他人所犯校園性侵害事件之證據者,更不具備擔任教育人員之資格,爰增訂本條,使渠等得依法(如:教育人員任用條例、教師法等相關法律)予以解聘或免職,終身不得再為教育人員,以回應社會要求及使學校教育人員得以拒絕人情關說或壓力,杜絕校園性侵害事件發生。
* 37 本法施行細則,由中央主管機關定之。
> 釋:明定本法施行細則由中央主管機關定之。
* 38 本法施行日期,除中華民國一百年六月七日修正之條文,由行政院定之外,自公布日施行。
> 釋:本次修正條文之施行日期,為與教師法及教育人員任用條例相關修正條文之施行日期相配合,爰授權由行政院定之。
|
C#
|
UTF-8
| 1,836
| 3.34375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace BasicSingleton
{
public class Highlander
{
private static Highlander instance;
private static int instanceCount = 0;
private static object syncRoot = new object();
/*private Highlander()
{
// use to yield to simulate race condition
// remove this for production
Thread.Sleep(0);
}*/
private static Highlander GetInstance()
{
if (instance == null)
{
CreateInstance();
}
return instance;
}
public static Highlander Default
{
get { return GetInstance(); }
}
private static void CreateInstance()
{
// Comment out the lock and if ( instance == null ) lines
// to see that a race condition can happen if two threads
// attempt to create an instance. With the lock and if (instance==null) code in place
// this should not happen
if (instance == null)
{
var success = Monitor.TryEnter(syncRoot, 2000);
if (!success)
throw new Exception("couldn't get lock");
try
{
if (instance == null)
{
instance = new Highlander();
Debug.Assert(Interlocked.Increment(ref instanceCount) == 1, "Multiple Creations");
}
}
finally
{
Monitor.Exit(syncRoot);
}
}
}
}
}
|
Java
|
UTF-8
| 350
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
package me.heacewalker.microkernel.core;
import java.util.List;
public class TradeStream {
List<TradeProcessor> tradeProcessors;
public TradeStream(List<TradeProcessor> tradeProcessors) {
this.tradeProcessors = tradeProcessors;
}
public List<TradeProcessor> getTradeProcessors() {
return tradeProcessors;
}
}
|
Python
|
UTF-8
| 759
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
# encoding: utf-8
"""
two-sum.py
Created by Shuailong on 2016-03-10.
https://leetcode.com/problems/two-sum/.
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {num: 0 for num in nums}
for i in range(len(nums)):
diff = target - nums[i]
if diff not in d:
continue
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
def main():
solution = Solution()
nums = [2,7,11,15]
target = 13
print solution.twoSum(nums, target)
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 1,020
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
"""这个例子将展示如何使用BP神经网络构建多分类的神经网络"""
import sys
import numpy as np
import pandas as pd
import classicML as cml
DATASET_PATH = './datasets/iris_dataset.csv'
CALLBACKS = [cml.callbacks.History(loss_name='categorical_crossentropy',
metric_name='accuracy')]
# 读取数据
dataframe = pd.read_csv(DATASET_PATH, index_col=0, header=0)
x = dataframe.iloc[:, :-1]
x = (x - np.mean(x, axis=0)) / np.var(x, axis=0)
y = dataframe.iloc[:, -1]
y = pd.get_dummies(y)
# 生成神经网络
model = cml.BPNN(seed=2020)
model.compile(network_structure=[4, 2, 3],
optimizer='sgd',
loss='categorical_crossentropy',
metric='accuracy')
# 训练神经网络
model.fit(x.values, y.values, epochs=1000, verbose=True, callbacks=CALLBACKS)
# 可视化历史记录(如果您使用的是MacOS, 请注释掉此句, 这句是为了在CI上测试用的.)
if sys.platform != 'darwin':
cml.plots.plot_history(CALLBACKS[0])
|
Markdown
|
UTF-8
| 4,198
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
---
path: /growth-hackers/
title: Growth Hackers Conference Notes
date: 2013-05-10 22:50:00 Z
---
## Growth vs Growth Hacking
[Keith Rabois](https://twitter.com/rabois)
Value => Growth => Growth Hacking
### Lessons
1. First grow based on real value
2. Growth hacking is an observational science
3. Feature design is the new marketing
### Hacks on hacks
* LinkedIn submitting personal profiles to Google
* Pay me with Paypal buttons on eBay
* YouTube embeddable player
* Facebook will proactively send you a new password when you fail to login a few times
* Yammer would get users to sign up and then call their IT department with "Your data is insecure…" once a few users from a company started using the product
> At Square, the brand is more important than any short-term gain.
Organic growth loop at Square was the transaction itself, which was a branded experience. You could actually treat the interaction like an ad impression, and it converted accordingly.
> My job is to add zeroes to the dashboard.
## Understanding the stages of growth
[Sean Ellis](https://twitter.com/seanellis)
1. Product / market fit
2. Transition to growth
3. Growth
### How do you know you're at PM/fit?
> 40%+ users must be disappointed without it
### Transition activities
* Implement user analytics
* Identify **must have** benefit
* Map benefit to effective hooks
* Optimize business model
* Optimize conversions
* Hire growth team
1. Conversion rate = desire - friction
2. Optimize funnel on delivering must-have benefit
Ask freeform "What is the primary benefit from this product?", after you see patterns emerge, switch to multiple choice.
Free products create demand over-time for premium features.
## How to make your first dollar
[Noah Kagan](https://twitter.com/noahkagan)
Put a tweet on it, no one still wants to get their shoes tied.
### Hustle today
> Coffee challenge: Go to Starbucks and ask for 10% off.
Try it and see what happens. Most people can't even do it. This is step one for aspiring entrepreneurs.
### Validate
1. Do they want it?
2. Will they pay you?
You can validate any product within 48 hours, you don't need code, a business degree, or a co-founder. Just get a yes to those two questions and move onto the next step. Quit wasting months of your time to validate radically simple ideas.
## Habits from inception to adoption
[Josh Elman](https://twitter.com/joshelman)
* Purpose: What need do you solve?
* Inception: How can you make users *aware*?
* Adoption: How can you *teach* users to use it?
* Habits: How can we *keep* them using it?
> SMS is the most underutilized communication medium.
When using invitation emails hint at the solution and benefit to hint at how potential users should use the platform.
## Building the growth machine
[Elliot Shmukler](https://www.linkedin.com/in/eshmu)
1. Set growth goal
2. Understand drivers
3. Optimize
### Goals
* must be measurable
* be measurable quickly (Facebook's 10 friends in **13** days)
* align goal with product / business
* make it a single number
### Understand drivers
Draw a diagram of all the possible flows of getting to the purpose
* work backwards from the goal
* understand the steps to get there
### Optimize
1. Reduce friction, make it simpler
2. Increase incentive, give me a better reason
3. Increase exposure, more often, more prominently, or in more places
Micro-questions, reduce friction by breaking out forms. You need all the data, but not all at once. Chip away at the problem.
## Email: unglamorous, difficult, effective
[Mike Greenfield](https://numeratechoir.com/)
Fix your email funnel and optimize in the order of magnitude of holes in your funnel. For example, only 20% of our emails got to Yahoo Mail users, by switching service providers we were able to get that number to 100%.
1. **Inbox delivery**, *make sure everyone is getting your email*
2. **One item focus**, *have one main hero piece of content*
3. **Quality**, *highly curated content > user generated*
4. **Subject optimization**, *test many lines and send the best one*
5. **Winners and losers**, *quit sending loser emails*
6. **Personalization**, *use relevant segmenting*
7. **Frequency**, *send more than you think*
|
PHP
|
UTF-8
| 408
| 2.78125
| 3
|
[] |
no_license
|
<?php
/**
* Tells whether user is logged in or not
* @return boolean
* @package MIS
* @name LoggedIn
* @author Harsh Vardhan Ladha & Yogesh Chauhan
* @copyright Computer Science & Engineering Department, NIT Silchar
* @link http://mis.nits.ac.in
* @license NIT Silchar
*/
function loggedIn(){
if(Session::exists('loggedIn') && Session::get('loggedIn')==1){
return TRUE;
}
else
return FALSE;
}
?>
|
Markdown
|
UTF-8
| 2,311
| 4.03125
| 4
|
[] |
no_license
|
# [Jumping in the hills](https://www.codechef.com/problems/HILLS)
Problem Code: **HILLS**
There are **N** hills in a row numbered 1 through **N** from left to right. Each hill has a height; for each valid **i**, the height of the **i**-th hill is **H_i**. Chef is initially on the leftmost hill (hill number 1). He can make an arbitrary number of jumps (including zero) as long as the following conditions are satisfied:
- Chef can only jump from each hill to the next hill, i.e. from the **i**-th hill, he can jump to the **i+1**-th hill (if it exists).
- It's always possible to jump to a hill with the same height as the current hill.
- It's possible to jump to a taller hill if it's higher than the current hill by no more than **U**.
- It's possible to jump to a lower hill if it's lower than the current hill by no more than **D**.
- Chef can use a parachute and jump to a **lower** hill regardless of its height (as long as it's lower than the current hill). This jump can only be performed at most once.
Chef would like to move as far right as possible. Determine the index of the rightmost hill Chef can reach.
## Input
- The first line of the input contains a single integer **T** denoting the number of test cases. The description of **T** test cases follows.
- The first line of each test case contains three space-separated integers **N**, **U** and **D**.
- The second line contains N space-separated integers **H_1**, **H_2**, ..., **H_N**.
## Output
For each test case, print a single line containing one integer — the index of the rightmost reachable hill.
## Usage
```sh
node .
```
## Example
### Input:
```
3
5 3 2
2 5 2 6 3
5 2 3
4 4 4 4 4
5 2 7
1 4 3 2 1
```
### Output:
```
3
5
1
```
## Explanation
**Example case 1:**
Chef can jump to second hill because it's higher by no more than **U**=3 than first hill, to jump to third hill Chef has to use parachute because it's lower than second hill by 3 which is more than **D**=2, Chef can't jump to fourth hill because it's higher than third hill by 4 which is more than **U**=3
**Example case 2:**
All hills are of the same height, so chef can reach the last hill with no problems.
**Example case 3:**
Chef can't jump to second hill because it's too high for him
## Coder
* **Tejas Rathod** - [@tejas77](https://github.com/tejas77)
|
PHP
|
UTF-8
| 3,349
| 3.234375
| 3
|
[] |
no_license
|
<?php
require "ErrorCode.php";
header("Content-Type:text/html;charset=UTF-8");
class User
{
/**
* 数据库连接句柄
*/
private $_db;
public function __construct($_db) //构造方法传入,而不是require进来
{
$this ->_db = $_db;
}
/**
* 用户登录
*/
public function login($username,$password)
{
if(empty($username)){
throw new Exception("用户名不能为空",ErrorCode::USERNAME_CANNNOT_EMPTY);
}
if(empty($password)){
throw new Exception('密码不能为空',ErrorCode::PASSWORD_CANNOT_EMPTY);
}
$sql = 'SELECT * FROM `zhuche` WHERE `username` =:username AND `password` =:password';
$stmt = $this -> _db ->prepare($sql);
$password = $this->_md5($password);
$stmt -> bindParam(':username',$username);
$stmt -> bindParam(':password',$password);
$stmt -> execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if(empty($user)){
throw new Exception('用户名或密码错误',ErrorCode::USERNAME_OR_PASSWORD_INVALID);
}
unset($user['password']); //删除这个数组中的value=password的key
return $user;
}
/**
* 注册
*/
public function register($username,$password,$email,$name,$intro,$sex)
{
if(empty($username)){
throw new Exception("用户名不能为空",ErrorCode::USERNAME_CANNNOT_EMPTY);
}
if($this -> _isUsernameExists($username)){
throw new Exception("用户名已存在",ErrorCode::USERNAME_EXISTS);
}
if(empty($password)){
throw new Exception('密码不能为空',ErrorCode::PASSWORD_CANNOT_EMPTY);
}
$sql = 'INSERT INTO `zhuche`(`username`,`password`,`name`,`email`,`intro`,`sex`) VALUES (:username,:password,:name,:email,:intro,:sex)';
$stmt = $this->_db->prepare($sql); //要有全部的变量
$password = $this->_md5($password);
$stmt -> bindParam(':username',$username);//该函数绑定了 SQL 的参数,且告诉数据库参数的值
$stmt -> bindParam(':password',$password);
$stmt -> bindParam(':name',$name);
$stmt -> bindParam(':email',$email);
$stmt -> bindParam(':intro',$intro);
$stmt -> bindParam(':sex',$sex);
if(!$stmt->execute()){
throw new Exception('注册失败',ErrorCode::REGISTER_FAIL);
}
return [
'userId' => $this -> _db->lastInsertId(), //这句话可以少调用一次数据库而直接获得上次操作的数据
'username' => $username,
'name' => $name
];
}
/**
* md5加密
*/
public function _md5($string , $key ='XDU'){ //把md5加密改一改
return md5($string.$key);
}
/**
* 检测用户名是否存在
*/
private function _isUsernameExists($username)
{
$sql = 'SELECT * FROM `zhuche` WHERE `username` = :username'; //这里:是占位符
$stmt = $this->_db->prepare($sql); //调用自己变量直接不用$
$stmt->bindParam(':username',$username);
$stmt->execute();
$result = $stmt -> fetch(PDO::FETCH_ASSOC);
return !empty($result);
}
}
|
Markdown
|
UTF-8
| 2,640
| 4.125
| 4
|
[] |
no_license
|
##### 类
```dart
//声明类
class Person{
// le==类的属性
String name = '张三';
//类的方法
void getInfo(){
print('我是'+name+'');
}
}
void main(){
//实例化类,然后得到一个对象
Person p = new Person();
print(p.name);
//访问类中的属性
p.getInfo();
// Dart 所有的内容都是对象
Map m = new Map();
//属性为扳手
// 方法为方块
print(m.length);
m.addAll({'name':'李四','age':20});
print(m.length);
}
```
##### 类与对象
```dart
class Point{
// num x;
// num y;
num x=1,y=1;
// 声明普通构造函数
Point(){
print('我是默认构造函数,实例化时,我是第一个被调用');
//this访问外部
num x=2,y=2;
//当命名指向有歧义时,this不能省略
print(x+y);
print(this.x+this.y);
}
}
void main(){
Point();
}
```
##### 构造函数
```dart
class Point{
num x,y;
Point(this.x,this.y);
//命名构造函数
Point.origin(){
x=0;
y=0;
}
//命名构造函数
Point.fromJson({x:0,y:0}){
this.x=x;
this.y=y;
}
}
void main(){
// 自动设置
Point p1 = new Point.origin();
print(p1.x);
// 手动设置
Point p2 = new Point.fromJson(x:6,y:6);
print(p2.x);
}
```
常量构造函数
```dart
class Point{
num x;
num y;
Point(this.x,this.y);
}
class ImmutablePoint{
// 属性必须通过final声明
final num x;
final num y;
//常量构造函数,必须通过const 声明
const ImmutablePoint(this.x, this.y);
}
void main(){
var p1 = new Point(1,2);
var p2 = new Point(1,2);
print(p1 == p2);//false 内存比较
print(p1);//ture
//常量构造函数可以当作普通构造函数使用
// new之后即被初始化, 可以省略
var p3 =ImmutablePoint(1, 2);
var p4 = ImmutablePoint(1, 2);
print(p3==p4);//false
//声明不可变对象,必须通过 const 关键字
var p5 = const ImmutablePoint(1, 2);
var p6 = const ImmutablePoint(1, 2);
print(p5==p6);
}
```
##### 工厂构造函数
```dart
class Person {
String name;
static Person instance;
//工厂构造函数
factory Person([String name = '刘备']) {
// 工厂构造函数不能使用this
// print(this.name);
// 工厂不能实例化
if (Person.instance == null) {
// 第一次实例化
Person.instance = new Person.newSelf(name);
}
//非第一次实例化
return Person.instance;
}
//命名构造函数
Person.newSelf(this.name);
}
void main() {
// 实例化操作
Person p1 = new Person('关羽');
print(p1.name);
Person p2 = new Person('张飞');
print(p2.name);
print(p1 == p2);
}
```
|
JavaScript
|
UTF-8
| 3,203
| 2.796875
| 3
|
[] |
no_license
|
document.addEventListener("DOMContentLoaded", function () {
// see more-less 1
const seeMoreLessBtn1 = document.querySelector(".see-more-less-btn1");
const additionalPictures1 = document.querySelector(".additional-pictures1");
seeMoreLessBtn1.addEventListener("click", function() {
if (additionalPictures1.style.display === "none" || additionalPictures1.style.display === "") {
additionalPictures1.style.display = "block";
seeMoreLessBtn1.textContent = "Zobacz mniej";
} else {
additionalPictures1.style.display = "none";
seeMoreLessBtn1.textContent = "Zobacz więcej";
}
});
// see more-less 2
const seeMoreLessBtn2 = document.querySelector(".see-more-less-btn2");
const additionalPictures2 = document.querySelector(".additional-pictures2");
seeMoreLessBtn2.addEventListener("click", function() {
if (additionalPictures2.style.display === "none" || additionalPictures2.style.display === "") {
additionalPictures2.style.display = "block";
seeMoreLessBtn2.textContent = "Zobacz mniej";
} else {
additionalPictures2.style.display = "none";
seeMoreLessBtn2.textContent = "Zobacz więcej";
}
});
// see more-less 3
const seeMoreLessBtn3 = document.querySelector(".see-more-less-btn3");
const additionalPictures3 = document.querySelector(".additional-pictures3");
seeMoreLessBtn3.addEventListener("click", function() {
if (additionalPictures3.style.display === "none" || additionalPictures3.style.display === "") {
additionalPictures3.style.display = "block";
seeMoreLessBtn3.textContent = "Zobacz mniej";
} else {
additionalPictures3.style.display = "none";
seeMoreLessBtn3.textContent = "Zobacz więcej";
}
});
// see more-less 4
const seeMoreLessBtn4 = document.querySelector(".see-more-less-btn4");
const additionalPictures4 = document.querySelector(".additional-pictures4");
seeMoreLessBtn4.addEventListener("click", function() {
if (additionalPictures4.style.display === "none" || additionalPictures4.style.display === "") {
additionalPictures4.style.display = "block";
seeMoreLessBtn4.textContent = "Zobacz mniej";
} else {
additionalPictures4.style.display = "none";
seeMoreLessBtn4.textContent = "Zobacz więcej";
}
});
// see more-less 5
const seeMoreLessBtn5 = document.querySelector(".see-more-less-btn5");
const additionalPictures5 = document.querySelector(".additional-pictures5");
seeMoreLessBtn5.addEventListener("click", function() {
if (additionalPictures5.style.display === "none" || additionalPictures5.style.display === "") {
additionalPictures5.style.display = "block";
seeMoreLessBtn5.textContent = "Zobacz mniej";
} else {
additionalPictures5.style.display = "none";
seeMoreLessBtn5.textContent = "Zobacz więcej";
}
});
// go-up button //
const goUpBtn = document.querySelector(".go-up");
goUpBtn.addEventListener("click", function () {
window.scroll({
top: 0,
left: 0,
behavior: "smooth"
});
});
});
|
C#
|
UTF-8
| 669
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ParticleSystem
{
public class ChaoticParticle : Particle
{
public ChaoticParticle(MatrixCoords position, MatrixCoords speed)
: base(position, speed)
{ }
private Random rnd = new Random();
protected override void Move()
{
base.Move();
this.Accelerate(new MatrixCoords(rnd.Next(-1, 2), rnd.Next(-1, 2)));
}
public override char[,] GetImage()
{
return new char[,] { { '#' } };
}
}
}
|
C++
|
UTF-8
| 800
| 3.109375
| 3
|
[] |
no_license
|
//
// Complex.cpp
// Ex10_08
//
// Created by MacBook Pro on 2019/11/21.
// Copyright © 2019 MacBook Pro. All rights reserved.
//
#include <complex>
#include "Complex.hpp"
Complex::Complex(double x,double y){
real=x;
imaginary=y;
}
bool Complex::operator==(const Complex & c)const{
if(real==c.real&&imaginary==c.imaginary)return true;
else
return false;
}
bool Complex::operator!=(const Complex &c)const{
return !(*this==c);
}
Complex Complex::operator*(const Complex & c){
return Complex(real*c.real-imaginary*c.imaginary,real*c.imaginary+c.real*imaginary);
}
istream &operator>>(istream&in,Complex &c){
in>>c.real;
in>>c.imaginary;
return in;
}
ostream &operator<<(ostream&out,Complex &c){
out<<"("<<c.real<<","<<c.imaginary<<")";
return out;
}
|
PHP
|
UTF-8
| 873
| 3.078125
| 3
|
[] |
no_license
|
<?php
class CourseDAO extends DAO{
protected $table;
public function __construct($flag=true) {
parent::__construct();
$this->flag = $flag;
$this->table = "course";
}
public function getById($id) {
$data = $this->get($id);
return $this->createObject($data);
}
public function getByIds($ids) {
$courses = array();
foreach($ids as $id) {
array_push($courses, $this->getById($id));
}
return $courses;
}
public function createObject($data){
$points = null;
if ($this->flag == true) {
$pointDAO = new PointDAO();
$points = $pointDAO->getAllByFkCourse($data['pk']);
}
$obj = new Course(
$data['pk'],
$points,
$data['name']
);
return $obj;
}
}
|
Python
|
UTF-8
| 755
| 3.078125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
from nose.tools import *
from vector3d import Vector3d
class TestVector3d:
def __init__(self):
self.a = Vector3d(1,2,3)
self.b = Vector3d(2,3,4)
def test_init(self):
eq_(self.a, [1,2,3])
def test_addition(self):
eq_(self.a + self.b, [3,5,7])
@raises(AttributeError)
def test_bad_addition(self):
eq_(self.a+1, [1,2,3])
def test_subtraction(self):
eq_(self.b - self.a, [1,1,1])
def test_scalar_mul(self):
assert_equal(self.a*2, [2,4,6])
def test_dot_product(self):
assert_equal(self.a.dot(self.b), [2,6,12])
def test_cross_product(self):
assert_equal(self.a.cross(self.b), [-1,2,-1])
if __name__ == '__main__':
print("Use nosetests to run this script")
|
SQL
|
UTF-8
| 1,338
| 3.703125
| 4
|
[
"MIT",
"BSD-4-Clause-UC",
"BSD-3-Clause",
"ISC",
"bzip2-1.0.6",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause",
"Artistic-2.0",
"PostgreSQL",
"LicenseRef-scancode-unknown"
] |
permissive
|
drop table if exists r;
create table r(a int, b int);
SELECT attnum::information_schema.cardinal_number
from pg_attribute
where attnum > 0 and attrelid = 'r'::regclass;
-- this one should fail
SELECT attnum::information_schema.cardinal_number
from pg_attribute
where attrelid = 'r'::regclass;
SELECT *
from (SELECT attnum::information_schema.cardinal_number
from pg_attribute
where attnum > 0 and attrelid = 'r'::regclass) q
where attnum=2;
select table_schema, table_name,column_name,ordinal_position
from information_schema.columns
where table_name ='r';
select table_schema, table_name,column_name,ordinal_position
from information_schema.columns
where table_name ='r'
and ordinal_position =1;
select table_schema, table_name,column_name,ordinal_position
from information_schema.columns
where ordinal_position = 20;
-- MPP-25724
select a.column_name
from information_schema.columns a
where a.table_name
in
(select b.table_name from information_schema.tables b where
a.column_name like 'b') and a.table_name = 'r';
select c.relname
from pg_class c
where c.relname
in
(select b.table_name from information_schema.tables b where
c.relname like 'r');
select a.table_name
from information_schema.tables a
where a.table_name
in
(select b.relname from pg_class b where
a.table_name like 'r');
drop table r;
|
TypeScript
|
UTF-8
| 2,336
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import { MongoConnectionSettingsBuilder } from '../src/lib/mongo-connection-settings';
const testConnectionString = `mongodb+srv://abc:pWd1!@internal-ohjxv.gcp.mongodb.net/accounts?retryWrites=true&w=majority`;
describe('MongoConnectionSettings', () => {
it('Parse proto with +srv', () => {
const connString1 = `mongodb+srv://test.mongodb.net`;
const builder1 = new MongoConnectionSettingsBuilder(connString1);
expect(builder1.isDnsSeedlist).toBeTruthy();
const connString2 = `mongodb://test.mongodb.net`;
const builder2 = new MongoConnectionSettingsBuilder(connString2);
expect(builder2.isDnsSeedlist).toBeFalsy();
});
it('Parse domain', () => {
const connString1 = `mongodb+srv://abc:pWd01!@test.mongodb.net`;
const connString2 = `mongodb+srv://test.mongodb.net`;
const connString3 = `mongodb://127.0.0.1:61839/testDb?`;
const builder1 = new MongoConnectionSettingsBuilder(connString1);
expect(builder1.domain).toEqual('test.mongodb.net');
const builder2 = new MongoConnectionSettingsBuilder(connString2);
expect(builder2.domain).toEqual('test.mongodb.net');
const builder3 = new MongoConnectionSettingsBuilder(connString3);
expect(builder3.domain).toEqual('127.0.0.1:61839');
});
it('Parse username and password', () => {
const connString = `mongodb+srv://abc:pWd01!@test.mongodb.net`;
const builder = new MongoConnectionSettingsBuilder(connString);
expect(builder.userName).toEqual('abc');
expect(builder.isPasswordSet).toBeTruthy();
});
it('Parse database name', () => {
const connString = `mongodb+srv://abc:pWd01!@test.mongodb.net/mySuperDB`;
const builder = new MongoConnectionSettingsBuilder(connString);
expect(builder.dbName).toEqual('mySuperDB');
});
it('Parse options', () => {
const connString = `mongodb+srv://abc:pWd01!@test.mongodb.net/mySuperDB?retryWrites=true&w=majority`;
const builder = new MongoConnectionSettingsBuilder(connString);
expect(builder.isRetryWrites).toBeTruthy();
expect(builder.writeConcern).toEqual('majority');
});
it('Returns MongoDb connection string', () => {
const builder = new MongoConnectionSettingsBuilder(testConnectionString);
const settings = builder.toSettings();
expect(settings.connectionString).toEqual(testConnectionString);
});
});
|
Python
|
UTF-8
| 1,324
| 2.5625
| 3
|
[] |
no_license
|
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
import pickle
import numpy as np
from tensorflow.keras.callbacks import TensorBoard
import datetime
NAME = 'Cats-vs-Dogs-CNN'
tensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))
def unpickle_this(filename):
with open(filename, 'rb') as file:
unpickled = pickle.load(file)
return unpickled
y = np.array(unpickle_this('/storage/y.pickle'))
X = unpickle_this('/storage/X.pickle')
X = X / 255.0
type(X)
model = Sequential()
model.add(Conv2D(64, (3,3), input_shape=X.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(X, y,
batch_size=32,
epochs=1,
validation_split=.3)
datestamp = datetime.datetime.now()
model_filename = f'{NAME}_{datestamp:%Y_%m_%d_%H:%M}_first_testing.model'
model.save(model_filename)
|
C
|
UTF-8
| 2,807
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user <user@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/10 00:29:35 by unite #+# #+# */
/* Updated: 2020/10/08 17:36:19 by user ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef UTILS_H
# define UTILS_H
# include <limits.h>
# include <stdlib.h>
# include "libftprintfgnl.h"
/*
** Mirrors the behaviour of `calloc` but terminates if memory allocation
** fails
*/
void *ft_xcalloc(size_t count, size_t size);
/*
** Mirrors the behaviour of `malloc` but terminates if memory allocation
** fails
*/
void *ft_xmalloc(size_t size);
/*
** Checks if the given string is a comment
** @return `1` if it's a comment, `0` otherwise
*/
int is_comment(const char *s);
/*
** Checks if the given string is a room coordinate
** @return `1` if it's a room coordinate, `0` otherwise
*/
int is_coord(const char *s);
/*
** Checks if the given string is the `##end` command
** @return `1` if it's the `##end` command, `0` otherwise
*/
int is_end(const char *s);
/*
** Checks if the given string represents a link between two rooms
** @return `1` if it represents a link, `0` otherwise
*/
int is_link(const char *s);
/*
** Checks if the given string specifies the number of ants
** @return `1` if it specifies the number of ants, `0` otherwise
*/
int is_nants(const char *s);
/*
** Checks if the given string is the name of a room
** @return `1` if it is the name of a room, `0` otherwise
*/
int is_room(const char *s);
/*
** Checks if the given string is the `##start` command
** @return `1` if it's the `##start` command, `0` otherwise
*/
int is_start(const char *s);
/*
** Frees all memory taken up by a `NULL`-terminated tab of strings
*/
void tab_delete(char **tab);
/*
** Computes the number of entries in `NULL`-terminated tab of strings
** @return The number of entries in the tab
*/
size_t tab_len(char **tab);
/*
** Prints a message to `STDERR` end exits
** @param mes The message to print to `STDERR`
*/
void terminate(const char *mes);
# define ERR_NO_MEMORY "Memory allocation error"
# define ERR_INVALID_INPUT "ERROR"
# define ERR_STDIN "Couldn't read from STDIN"
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.