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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 5,148 | 2.75 | 3 |
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 2
---
在六月初的几天里出了件事,保姆兼女管家阿加菲娅·米哈伊洛夫娜把她刚腌好的蘑菇送到地下室,脚下一滑摔倒了,导致手腕脱臼。来了那位年轻而又爱闲扯、刚完成大学学业的当地医生。他看看手,说她并没有脱臼,裹上敷布,便留下来吃饭,看来很享受能够同著名的谢尔盖·伊万诺维奇·科兹内舍夫交谈,为表达自己对待事物的开明见解,把县里的种种流言蜚语说给他听,抱怨着地方自治上的糟糕状况。谢尔盖·伊万诺维奇留心听了,并仔细询问,为新的倾听者所激励,畅谈起来,提出几个精辟而颇有分量、受到年轻医生恭敬赞赏的见解,便又进入弟弟所熟悉的,活跃的精神状态,通常他在一番精彩而活跃的谈话之后就会进入这种状态。医生走后,谢尔盖·伊万诺维奇打算带着鱼竿去河边。他喜欢钓鱼,似乎为自己会喜欢如此蠢笨的事情而自豪。
康斯坦丁·列文要去耕作地和草场,主动提出用轻便马车把哥哥送过去。
正值一年之中夏季转折的时节,当年的收成已然确定,这时节开始操心来年播种的事情,也该割草了;这时节,黑麦也都结了穗,那灰中带绿、未灌满浆且轻飘飘的麦穗在风中翻起波浪;这时节,绿色的燕麦和漫散其间的一簇簇黄草高低不平地冒出晚播田;这时节,早荞麦已经铺展开来,遮盖了大地;这时节,被牲口踩踏成石头一般的休耕地已经耕了一半,留下没有犁过的条条小径; 这时节,送到地里的一堆堆厩肥已经风干,每到黎明便混同甜叶菊一道散发出气味,低地上,等待镰刀收割的,是保留下来的一大片草海,夹杂着一堆堆拔干净的、发黑的酸模茎干。
这段时间,正是农务劳作中年年重复、年年都需要召集百姓尽全力地收获开始之前的短暂歇息。收成非常之好,晴朗炎热的夏日伴着有露而短暂的夜晚。
兄弟俩要穿过树林才能去草地那边。谢尔盖·伊万诺维奇一直在欣赏森林枝叶繁茂的沉寂之美,一会儿给弟弟指着背阴面很暗的一棵有黄色托叶装点的,就要开花的老椴树,一会儿指着当年幼树绿宝石般闪光的嫩芽。康斯坦丁·列文不喜欢说,也不愿意听别人说大自然的美。语言掠走了他所见之物中的美。他随声附和着哥哥,但不由自主地想起别的事情。当他们驶过林子,他的全部注意力都被小丘上休耕地的景象吸引了过去,某处草叶变黄,某处被践踏并割成方格子,某处散落着厩肥堆,而某处已经耕过。一串大车从田里驶过。列文数了数这些大车之后很是满意,因为该运来的全都运到了,他的思绪在看见草地时随即转到了割草的问题上。在收干草的事上他总是感到一种特别的东西搅扰他的内心。来到草地上,列文停下马。
清晨的露水仍留在密匝匝的草根上,谢尔盖·伊万诺维奇为了不弄湿双脚,请求让轻便马车把他载过草地,直到抓河鲈的柳树丛那里。尽管康斯坦丁·列文对轧到自己的草感到可惜,他还是驾车上了草地。高草在车轮和马腿边轻柔缠绕,把自己的种子留在潮湿的辐条和轮毂上。
哥哥坐在了树丛下,摆弄着鱼竿,列文则牵开马,拴起来,然后走进那风吹不动的、巨大的灰绿色草海。如丝的草挂着正待成熟的种子,在淹过水的地方已高及腰际。
穿过草地,康斯坦丁·列文走到路上,遇见一个肿了一只眼睛的老汉,肩上扛着蜂箱。
“怎么?莫非捉到了,福米奇?”他问。
“哪里是捉到的啊,康斯坦丁·密特里奇!把自己的保住就不错了。这群是第二次离巢的了……所幸啊,给小伙子们追上了。都在您那儿耕地呢。他们卸了马,就赶上去了……”
“嗯,你说说看,福米奇,是现在就割还是再等等?”
“这个呀!我们都是要等到圣彼得节。而您总是早割。是啊,上帝保佑草长得好,让牲口吃个够。”
“天气呢,你觉得怎么样?”
“上帝做主的。也许有好天气。”
列文走到哥哥那里。什么都没钓到,但谢尔盖·伊万诺维奇并不寂寞,似乎处在最愉悦的心境中。列文看出,与医生的一番交谈激起了他的兴致,哥哥想要说说话。列文呢,正相反,想要尽早回家,以便安排召集明天的割草工,解决很是占据他内心的有关割草的疑虑。
“好了,我们走吧。”他说。
“为什么要着急呢?再坐一会儿。可你怎么弄这么湿!虽说没钓到,但很好啊。各种捕猎都好,因为你要跟大自然相接触。瞧这银灰色的水多美!”他说,“这些青草遍布的河岸总是让我想起一个谜语——你知道吗?草对河水说:我们摇一摇,我们摆一摆。”
“我不知道这个谜语。”列文闷闷不乐地回答。
|
C#
|
UTF-8
| 1,704 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
namespace Discord_Bot.Events
{
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Discord.Commands;
using Discord.WebSocket;
public class Message_Received
{
public void Run()
{
Program.Client.MessageReceived += Client_MessageReceived;
}
private static async Task Client_MessageReceived(SocketMessage messagePram)
{
SocketUserMessage message = messagePram as SocketUserMessage;
SocketCommandContext context = new SocketCommandContext(Program.Client, message);
if (context.Message == null || context.Message.Content == "") return;
if (context.User.IsBot) return;
string prefix = Utils.GetPrefix(context);
int argPos = 0;
if (!(message.HasStringPrefix(prefix, ref argPos) || message.HasMentionPrefix(Program.Client.CurrentUser, ref argPos))) return;
if (context.Message.ToString() == prefix) return;
IResult result = await Program.Commands.ExecuteAsync(context, argPos, null);
if (!result.IsSuccess)
{
Program.MF.Invoke(new MethodInvoker(() => { Program.MF.AddText($"{DateTime.Now} at Commands] Something went wrong with a command Text: {context.Message.Content} | Error: {result.ErrorReason}", System.Drawing.Color.DarkRed); }));
string err = result.ErrorReason;
if (err == "Unknown command.")
{
err = $"Unknown Command! Use {prefix}Help to see the commands.";
}
await context.Channel.SendMessageAsync(err);
}
}
}
}
|
C
|
UTF-8
| 372 | 2.578125 | 3 |
[] |
no_license
|
#include<stdio.h>
int main(){
FILE *fp[6];
fp[0] = fopen("/tmp/r.txt", "r");
fp[1] = fopen("/tmp/r+.txt", "r+");
fp[2] = fopen("/tmp/w.txt", "w");
fp[3] = fopen("/tmp/w+.txt", "w+");
fp[4] = fopen("/tmp/a.txt", "a");
fp[5] = fopen("/tmp/a+.txt", "a+");
fclose(fp[0]);
fclose(fp[1]);
fclose(fp[2]);
fclose(fp[3]);
fclose(fp[4]);
fclose(fp[5]);
return 0;
}
|
JavaScript
|
UTF-8
| 342 | 2.546875 | 3 |
[] |
no_license
|
import * as constant from '../constants';
const initialState = {
data: {}
};
export function weatherReducer(state = initialState, action) {
switch (action.type) {
case constant.SET_WEATHER: {
return {
...state,
data: action.payload.data,
};
}
default:
return state;
}
}
|
Java
|
UTF-8
| 697 | 2.578125 | 3 |
[] |
no_license
|
/**
*
*/
package org.einnovator.notifications.client.model;
public enum ContentType {
HTML("Html"),
CSS("Css"),
TEXT("Text")
;
private final String displayValue;
ContentType(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
public static ContentType parse(String s) {
for (ContentType e: ContentType.class.getEnumConstants()) {
if (e.toString().equalsIgnoreCase(s)) {
return e;
}
}
return null;
}
public static ContentType parse(String s, ContentType defaultValue) {
ContentType value = parse(s);
return value!=null ? value: defaultValue;
}
}
|
Python
|
UTF-8
| 1,115 | 2.59375 | 3 |
[] |
no_license
|
import socketio
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from transformers import pipeline
#Start the conection as a Client
sio = socketio.Client()
#Use the hugging models
translation_pipeline = pipeline('translation_en_to_es', model='Helsinki-NLP/opus-mt-en-es')
summarization_pipeline = pipeline('summarization', model='Josmar/BART_Finetuned_CNN_dailymail')
@sio.event
def connect():
print('connection established')
@sio.on('text-long')
def action(data):
text = data['message']
#Set the parameters min and max length to make the summarize
summarize = summarization_pipeline(text, min_length=40, max_length=80)
print(summarize[0]['summary_text'])
#Make the traduction
results = translation_pipeline(summarize[0]['summary_text'])
print(results[0]['translation_text'])
#Emit with the topic 'text-short' the result
sio.emit('text-short', {'message': results[0]['translation_text']})
@sio.event
def disconnect():
print('disconnected from server')
sio.disconnect()
#Connected to the port 3000
sio.connect('http://localhost:3000')
sio.wait()
|
Python
|
UTF-8
| 148 | 2.546875 | 3 |
[] |
no_license
|
for _ in range(int(input())):
N,K,D= map(int,input().split())
A=map(int,input().split())
ans=sum(A)//K
print(ans if ans<=D else D)
|
Markdown
|
UTF-8
| 1,430 | 2.875 | 3 |
[] |
no_license
|
---
title: moveuserfilestore2context
icon: far fa-circle
tags: Administration, Command Line tools, User, Context, Filestore
package: open-xchange-admin
---
# NAME
moveuserfilestore2context - moves a user's files from his own to a context storage.
# SYNOPSIS
**moveuserfilestore2context** [OPTION]...
# DESCRIPTION
This command line tool moves a user's files from his own to a context storage.
# OPTIONS
**-c**, **--contextid** *contextId*
: The context identifier. Mandatory and mutually exclusive with `-N`.
**-N**, **--contextname** *contextName*
: The context name. Mandatory and mutually exclusive with `-c`.
**-i**, *--userid* *userId*
: Id of the user.
**-u**, *--username* *username*
: Username ofthe user.
**-A**, **--adminuser** *contextAdmin*
: Context admin user name for authentication. Optional, depending on your configuration.
**-P**, **--adminpass** *contextAdminPassword*
: Context admin password for authentication. Optional, depending on your configuration.
**-h**, **--help**
: Prints a help text.
**--environment**
: Show info about commandline environment.
**--nonl**
: Remove all newlines (\\n) from output.
**--responsetimeout**
: The optional response timeout in seconds when reading data from server (default: 0s; infinite).
# EXAMPLES
**moveuserfilestore2context -A contextAdmin -P secret -c 1138 -i 137**
Moves the filestore of the specified user from the his own to a context one.
|
Java
|
UTF-8
| 574 | 3.296875 | 3 |
[] |
no_license
|
package weeks9;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
try {
System.out.println(3/0);
} catch (IndexOutOfBoundsException | ArithmeticException e) {
System.out.println("IndexOutOfBoundsException 혹은 ArithmeticException 발생할 경우 수행");
}
try {
System.out.println(3/1);
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("반드시 수행");
}
}
}
|
SQL
|
UTF-8
| 239 | 3.203125 | 3 |
[] |
no_license
|
create table main.t_friendships(
id serial primary key,
userId int,
friendId int,
constraint fk_fuserid foreign key (userId) references main.t_user(id),
constraint fk_friendid foreign key (friendId) references main.t_user(id)
);
|
Java
|
UTF-8
| 545 | 3.09375 | 3 |
[] |
no_license
|
package les1;
public class CofeMashine {
String brendName;
public CofeMashine(String brendName){
this.brendName= brendName;
}
public void brewcofe(boolean filter,boolean water, int size){
if (filter==false){
System.out.println("Clean up filter");
} else
if (water==false){
System.out.println("Add water");
}else {
System.out.println("Caffe is brewing");
}
System.out.println("Done. Take your caffe "+ "size "+
size);
}
}
|
Java
|
UTF-8
| 1,144 | 3.296875 | 3 |
[] |
no_license
|
package xchess;
import java.util.ArrayList;
public class Bishop extends Piece {
public static ArrayList<Point> getPossibleMoves(Point current)
{
ArrayList<Point> moves= new ArrayList<Point>();
int x=current.getX(),y=current.getY();
System.out.println( "Accessing piece at location (" + x + "," + y + ")" );
int sign = (int)Math.signum(Game.cb.getElement(x,y));
for(int i=x+1,j=y+1;i<8 && j<8;i++,j++)
{
if((int)Math.signum(Game.cb.getElement(i,j))!=sign)
moves.add(new Point(i,j));
if(Game.cb.getElement(i,j)!=0)
break;
}
for(int i=x+1,j=y-1; i<8 && j>=0; i++,j--)
{
if((int)Math.signum(Game.cb.getElement(i,j))!=sign)
moves.add(new Point(i,j));
if(Game.cb.getElement(i,j)!=0)
break;
}
for(int i=x-1,j=y+1;i>=0 && j<8;i--,j++)
{
if((int)Math.signum(Game.cb.getElement(i,j))!=sign)
moves.add(new Point(i,j));
if(Game.cb.getElement(i,j)!=0)
break;
}
for(int i=x-1,j=y-1;i>=0 && j>=0;i--,j--)
{
if((int)Math.signum(Game.cb.getElement(i,j))!=sign)
moves.add(new Point(i,j));
if(Game.cb.getElement(i,j)!=0)
break;
}
return moves;
}
}
|
Markdown
|
UTF-8
| 5,067 | 2.96875 | 3 |
[] |
no_license
|
---
layout: page
title: Frequently Asked Questions
permalink: faqs.html
---
Below are a few questions we often receive about the Columbia University Libraries Studio.
{: .lead}
### What kinds of events does the Studio usually host?
The Studio is designed for ethical, sustainable, collaborative, <abbr
title="Findable, Accessible, Interoperable, Reusable" class="initialism">FAIR</abbr> digital
and data-driven research and pedagogy. We host conferences, seminars, talks
and workshops related to these concerns in addition to newer forms of
programming: hackathons, researchathons, tech meet-ups, and more. The spaces
are often used in conjunction with courses with a digital lab component. We
also design programs around our community’s needs. If you need a particular
workshop not offered elsewhere or would like to reverse-engineer a digital
scholarship project, the Studio is the right venue to host a learning session
around digital technologies, and we will be happy to match you with someone
who can help you.
### How is the Studio set up and how many people can it accommodate?
Please see the links to [Studio at Butler]({{ "/spaces/butler" | relative_url }})
and [Studio at Lehman]({{ "/spaces/lehman" | relative_url }}) for more information
about the structure of these spaces.
### What technology is in the Studio?
The Studio is typically bring-your-own-technology space. There are no
computers installed in Studio at Butler, but we are ready to plug your laptop
in for presentations or capture events with projectors, a video camera, and
microphones. Wireless connectivity has been upgraded to the fastest available
in the library.
Studio at Lehman has six desktop PCs with running Windows 10 with additional
software maintained by [Research Data
Services](https://library.columbia.edu/services/research-data-services.html).
If you need advanced software or scanning technology for your research, that
is available in the Digital Humanities Center (305 Butler); software and
computers for teaching support are available in the CTL’s Learning Commons
(204 Butler).
### When is the Studio open?
Studio programming is typically open to the Columbia community and beyond,
though many events may require an RSVP. Informal, [Open Labs]({{ "/open-lab.html" | relative_url }}) typically occur every week-day in the afternoon, with Studio at
Lehman hosting an Open Lab Mondays through Thursdays, and Studio at Butler
hosting an Open Lab Monday and Friday afternoons.
The Studio also hosts more focused events such as [Research Data
Services](https://library.columbia.edu/services/research-data-services.html)’s
labs proctored by Digital Centers Interns at Studio at Lehman. Studio at
Butler additionally hosts events managed by the GSAS Teaching Center and the
Digital Humanities Center.
[Our
calendar](https://library.columbia.edu/services/research-data-services/events.html)
provides more detailed information.
### I am looking for a good place to study (individually or with a group). Can I use the Studio for that?
The Studio is a space for active collaboration, training, presentation, and
consultation. We welcome your ideas for group activities in the Studio
pertaining to this focus. To book a traditional group study or presentation
practice space, please visit the [Libraries’s Room Reservation
system](https://roomreservations.cul.columbia.edu/).
### I am looking for a space to convene a meeting in Butler Library. Is Studio at Butler available for that?
If your meeting pertains to ethical, sustainable, collaborative and <abbr
title="Findable, Accessible, Interoperable, Reusable" class="initialism">FAIR</abbr>
digital, data-driven research or pedagogy, we are happy to work with you to
schedule it. Send us a description of the event.
### Can I bring food into the Studio?
Yes, you can, but you have to let us know first. Usually you will be working
with a library coordinator to plan your event. Make sure you let them know so
that they can inform the Library Information Office.
### I am teaching at Columbia, and my class includes a digital component. May I hold it in the Studio?
The libraries do not provide classroom space at Columbia. However, the
Studio may be booked for digital lab components of Columbia classes, as well
as course-related training, project-building, and evaluation activities. Send
us your ideas for use of the Studio in your course, and we’ll take it from
there.
### Is use of the Studio restricted to Columbia University affiliates?
Though events in the Studio must include a Columbia University component, they
may also draw in collaborators from outside the university, such as educators
at other New York City institutions, participants in NYC Digital Humanities
activities, and developers connected to teaching and scholarship projects. For
approved events we will work with you to set up access to the Studio for
participants without Columbia University UNIs.
### What if I have a question about the Studio that isn’t answered here?
Please email us your question: studio@libraries.cul.columbia.edu.
|
C++
|
UTF-8
| 1,864 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
#include<bits/stdc++.h>
using namespace std;
void dijkstras()
{
int n;
cout<<"Enter the number of vertices ";
cin>>n;
int am[n][n];
cout<<"Enter the adjacency matrix"<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>am[i][j];
}
}
int stnd;
cout<<"Enter the starting node"<<endl;
cin>>stnd;
int cost[n][n],distance[n],path[n],visited[n],ct=0,nextnode,min_dist;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(am[i][j] == 0)
{
cost[i][j] = +1e5;
}
else
cost[i][j] = am[i][j];
}
}
for(int i=0;i<n;i++)
{
distance[i] = cost[stnd][i];
path[i] = stnd;
visited[i] = 0;
}
distance[stnd] = 0,visited[stnd] = 1;
ct = 1;
while(ct<n-1)
{
min_dist = +1e5;
for(int i=0;i<n;i++)
{
if(distance[i]<min_dist && !visited[i])
{
min_dist = distance[i];
nextnode = i;
}
}
visited[nextnode]=1;
for(int i=0;i<n;i++)
{
if(!visited[i])
{
if(min_dist + cost[nextnode][i]<distance[i])
{
distance[i] = min_dist + cost[nextnode][i];
path[i] = nextnode;
}
}
}
ct++;
}
// print all the path
for(int i=0;i<n;i++)
{
if(i!=stnd)
{
cout<<"\n Distance of node "<<i<<"="<<distance[i];
cout<<"\n path = "<<i;
int j = i;
do
{
j = path[j];
cout<<"<-"<<j;
}while(j!=stnd);
}
}
}
int main()
{
dijkstras();
return 0;
}
|
JavaScript
|
UTF-8
| 1,236 | 2.953125 | 3 |
[] |
no_license
|
const c = document.getElementById("c");
const draw = c.getContext("2d");
let CO2 = [];
let temperature = [];
for (let i = 0; i < CO2UTC.length; i++) {
CO2.push(({
ts: CO2UTC[i][0] / 31536000000 + 1970,
value: CO2UTC[i][1]
}))
}
for (let i = 0; i < temperatureUTC.length; i++) {
temperature.push(({
ts: temperatureUTC[i][0] / 31536000000 + 1970,
value: temperatureUTC[i][1]
}))
}
c.width = window.innerWidth;
c.height = window.innerHeight;
let renderer = new dataThingy([CO2, temperature], ["CO2", "Temperature anomaly"], ["ppm", "°C"], ["rgb(64, 64, 255)", "rgb(255, 64, 64)"], [1, 0.1], "years", 1, "#fff", draw);
let i = 0;
function drawLoop() {
// setTimeout(drawLoop, 1000/60)
draw.fillStyle = "#000";
draw.fillRect(0, 0, c.width, c.height);
// renderer.lineGraph(1950, 2020, ["CO2", "Temperature anomaly"], [
// [290, 420],
// [-0.9, 1.5]
// ], 128, 48, 0, 0, c.width, c.height, "italic 32px Spectral");
renderer.key(16, 16, 32, "italic 32px Spectral");
renderer.pieChart(1972, c.width/2, (3/4)*c.height, 100, 0, 0.5, ["CO2", "Temperature anomaly"], "italic 32px Spectral");
console.log("bruh");
// setTimeout(()=>{requestAnimationFrame(drawLoop); i++;},1000)
}
drawLoop();
|
JavaScript
|
UTF-8
| 3,972 | 2.640625 | 3 |
[] |
no_license
|
import React, { Component, Fragment } from 'react';
import firebase from '../../firebase';
import TodoList from "./table";
import TodosStyles from './style';
class todosPage extends Component {
state = {
form: {
name: "",
hour: ""
},
todos: [],
errorMessage: ""
};
onChangeName = event => {
const { value } = event.target;
this.setState({
form: {
...this.state.form,
name: value
}
});
};
onChangeHour = event => {
const { value } = event.target;
this.setState({
form: {
...this.state.form,
hour: value
}
});
};
onSubmit = async event => {
event.preventDefault(); // previne que o browser atualize a página
// armazenamos um objeto com os dados do state + a data atual
if(this.state.form.name.length > 0) {
this.setState({
errorMessage: ''
});
const comment = {
...this.state.form,
createdAt: new Date().getTime()
};
// mandamos o firebase armazenar no banco "banco", o registro atual
await firebase
.database()
.ref("banco")
.push(comment);
// após o registro ser adicionado, vamos limpar o formulário
this.setState({
form: {
name: "",
hour: ""
}
});
} else {
this.setState({
errorMessage: 'messageError'
})
}
};
onRemove = uid => {
const todoRef = firebase
.database()
.ref("banco")
.child(uid);
todoRef.remove();
};
onEdit = uid => {
// const todoRef = firebase.database().ref(`banco/${uid}`);
// todoRef.update({
// name: "Nome editado",
// hour: "Comentário editado"
// });
};
componentDidMount() {
firebase
.database()
.ref("banco")
.on("value", snapshot => {
const response = snapshot.val();
const todos = !!response
? Object.keys(response).map(uid => ({
...response[uid],
uid
}))
: [];
this.setState({
todos
});
});
}
render() {
const { todos } = this.state;
return (
<Fragment>
<TodosStyles />
<main>
<section>
<h2 className="title">Lista de Afazeres</h2>
<div className="row">
<div className="col-md-4">
<label>Nome atividade:</label>
<input className={this.state.errorMessage} type="text" name="name" value={this.state.form.name} onChange={this.onChangeName} placeholder="Digite a atividade" />
</div>
<div className="col-md-4">
<label>Duração:</label>
<input className={this.state.errorMessage} type="text" name="hour" value={this.state.form.hour} onChange={this.onChangeHour} placeholder="Digite a duração" />
</div>
<div className="col-md-4">
<button className="btn-default" onClick={this.onSubmit}>Cadastrar</button>
</div>
</div>
<TodoList todos={todos} onRemove={this.onRemove} onEdit={this.onEdit}/>
</section>
</main>
</Fragment>
)
}
}
export default todosPage;
|
PHP
|
UTF-8
| 1,133 | 2.59375 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace App\Application\Actions\Config;
use App\Application\Models\ConfigModel;
use Psr\Http\Message\ResponseInterface as Response;
use App\Application\Actions\Action;
use Respect\Validation\Validator as v;
class ConfigDeleteAction extends Action
{
/**
* @var ConfigModel
*/
private $Config;
protected $headers;
protected $errorMessages = [];
protected $id;
protected function action(): Response
{
$this->id = $this->headers['id'];
$this->headers = $this->request->getHeaders();
$this->Config = new ConfigModel();
$this->delete();
return $this->respondWithData('OK');
}
/**
*
*/
public function delete(): void
{
$this->service->delete("config", [
"id" => $this->id,
]);
}
/**
* @return ConfigModel
*/
public function getConfig(): ConfigModel
{
return $this->Config;
}
/**
* @param ConfigModel $Config
*/
public function setConfig(ConfigModel $Config): void
{
$this->Config = $Config;
}
}
|
Go
|
UTF-8
| 2,038 | 2.84375 | 3 |
[] |
no_license
|
package main
import (
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"xorm.io/core"
)
/**
这里也是使用递归的方式来实现,不过这里只是查询一次数据库
*/
var dbenginer *xorm.Engine
//定义的格式如下:[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
const DATASOURCE = "root:jianghua@tcp(127.0.0.1:3306)/godb?charset=utf8" //这个可以简写为root:jianghua@/godb?charset=utf8,就是使用默认tcp协议连接本机的3306这个端口
func main() {
category := make([]Category,0)
dbenginer = InitDb()
if err := dbenginer.OrderBy("sort").Find(&category); err != nil{
fmt.Println(err.Error())
return
}
category2 := new(Category)
categories := category2.CategoryArrNew(category,0,0)
categoriesJson,err := json.Marshal(categories)
if err != nil{
return
}
fmt.Println(string(categoriesJson))
}
/**
参考文档:http://note.youdao.com/noteshare?id=94e30c5323cd7fba6b0dec26fb03c779&sub=2E5D03949EAE42B08AF9B8FAB44E6A7F这个来实现的
*/
func (cate *Category) CategoryArrNew(category []Category,pid ,level int) []Category {
list := []Category{}
for _, value := range category {
if value.Pid == pid{
value.Level = level
value.Son = cate.CategoryArrNew(category,value.Id,level+1)
list = append(list,value)
}
}
return list
}
//创建数据库连接
func InitDb() *xorm.Engine {
dbenginer,err := xorm.NewEngine("mysql",DATASOURCE)
if err != nil{
panic(err.Error())
}
if dbenginer.Ping() != nil {
panic(err.Error())
}
//defer dbenginer.Close()
dbenginer.ShowSQL(true)
//定义表的映射关系金和表前缀
tableMapper := core.NewPrefixMapper(core.SnakeMapper{},"jh_")
dbenginer.SetTableMapper(tableMapper)
return dbenginer
}
type Category struct {
Id int `json:"id" xorm:"id"`
Pid int `json:"pid" xorm:"pid"`
Name string `json:"name" xorm:"name"`
Sort int `json:"sort" xorm:"sort"`
Level int `json:"level" xorm:"-"`
Son []Category `json:"son" xorm:"-"`
}
|
C#
|
UTF-8
| 983 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PathfinderModelling.Model.Archetypes.Brawler
{
class WindingPathRenegade : Archetype
{
public WindingPathRenegade(Classes.Brawler brawler)
{
Name = "Winding Path Renegade";
ArchetypeAbilities = new List<ArchetypeAbility>
{
new ArchetypeAbility
{
Name = "School Focus",
Level = 2,
ReplacedAbilities = new List<ClassAbility> { brawler.BonusCombatFeat2, brawler.BonusCombatFeat8, brawler.BonusCombatFeat14 },
},
new ArchetypeAbility
{
Name = "Monk Moves",
Level = 4,
ReplacedAbilities = new List<ClassAbility>(brawler.ClassAbilities.Where(a => a.Name.Contains("AC Bonus"))),
}
};
}
}
}
|
Java
|
UTF-8
| 529 | 3.265625 | 3 |
[] |
no_license
|
package com.fundamental;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderWritter {
public static void main(String[] args) throws Exception {
FileWriter fw=new FileWriter("tops2.txt");
String s="This is file reader/writter demo";
fw.write(s);
fw.flush();
fw.close();
System.out.println("Data Written Successfully");
FileReader fr=new FileReader("tops2.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close();
}
}
|
C#
|
UTF-8
| 2,063 | 3.234375 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.IO;
namespace LumiSoft.Net.Mime
{
/// <summary>
/// Attachment.
/// </summary>
[Obsolete("This class will be removed, use Mime class instead !")]
public class Attachment
{
private string m_FileName = "";
private byte[] m_FileData = null;
private string m_AttachmentType = "";
/// <summary>
/// Creates attechment from file.
/// </summary>
/// <param name="fileName">File name which to attach. Eg. c:\aaa.eml .</param>
public Attachment(string fileName)
{
m_AttachmentType = "file";
m_FileName = Path.GetFileName(fileName);
using(FileStream fs = File.OpenRead(fileName)){
m_FileData = new byte[fs.Length];
fs.Read(m_FileData,0,(int)fs.Length);
}
}
/// <summary>
/// Creates attachment from stream with specified file name
/// </summary>
/// <param name="fileName">File name. Eg. aaa.eml .</param>
/// <param name="strm">Stream which data to attach. NOTE: Data will be taken from stream current position.</param>
public Attachment(string fileName,Stream strm)
{
m_AttachmentType = "data";
m_FileName = fileName;
int strmPos = (int)strm.Position;
m_FileData = new byte[strm.Length - strmPos];
strm.Read(m_FileData,0,(int)strm.Length - strmPos);
strm.Position = strmPos;
}
/// <summary>
/// Creates attachment from data with specified file name.
/// </summary>
/// <param name="fileName">File name. Eg. aaa.eml .</param>
/// <param name="fileData">Data which to attach.</param>
public Attachment(string fileName,byte[] fileData)
{
m_AttachmentType = "data";
m_FileName = fileName;
m_FileData = fileData;
}
#region Properties Implementation
/// <summary>
/// Gets file name.
/// </summary>
public string FileName
{
get{ return m_FileName; }
}
/// <summary>
/// Gets file data.
/// </summary>
public byte[] FileData
{
get{ return m_FileData; }
}
/// <summary>
///
/// </summary>
public string AttachmentType
{
get{ return m_AttachmentType; }
}
#endregion
}
}
|
Java
|
UTF-8
| 221 | 1.8125 | 2 |
[] |
no_license
|
package com.unichain.demo.service;
import com.unichain.demo.entity.User;
import com.unichain.demo.service.support.BaseService;
public interface UserService extends BaseService<User> {
User selectUser(User user);
}
|
Java
|
UTF-8
| 704 | 2.234375 | 2 |
[] |
no_license
|
package test;
import java.io.IOException;
import java.util.Iterator;
import javax.swing.JFrame;
import databall.DataBall;
import dataplayer.DataPlayer;
import datateam.DataTeam;
import gui.elements.DrawField;
import gui.elements.EndscreenPanel;
import process.management.CreaTeam;
import process.management.Map;
import process.management.Match;
import process.scores.Score;
public class TestMatch {
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame();
Score score = new Score(0, 0);
EndscreenPanel ep = new EndscreenPanel(score);
frame.add(ep.initLayout());
frame.setVisible(true);
frame.setSize(500, 500);
}
}
|
Go
|
UTF-8
| 1,039 | 2.671875 | 3 |
[] |
no_license
|
package mydata
import (
"testing"
"github.com/stretchr/testify/assert"
)
// go test -run '' -v
func TestTList(t *testing.T) {
t.Run("aaaa", func(t *testing.T) {
l := CreateList()
l.Append(0)
l.Append(1)
l.Append(2)
l.Append(3)
assert.Equal(t, "0,1,2,3", l.ToString())
})
t.Run("iiii", func(t *testing.T) {
l := CreateList()
l.Insert(0, 0)
l.Insert(1, 1)
l.Insert(2, 2)
l.Insert(3, 3)
assert.Equal(t, "0,1,2,3", l.ToString())
})
t.Run("iaia", func(t *testing.T) {
l := CreateList()
l.Insert(0, 0)
l.Append(1)
l.Insert(2, 2)
l.Append(3)
assert.Equal(t, "0,1,2,3", l.ToString())
})
t.Run("aaiid", func(t *testing.T) {
l := CreateList()
l.Append(1)
l.Add(0)
l.Insert(2, 2)
l.Insert(3, 3)
l.Delete(3)
assert.Equal(t, "0,1,2", l.ToString())
l.Reverse()
assert.Equal(t, "2,1,0", l.ToString())
})
t.Run("aaiid", func(t *testing.T) {
l := CreateList()
l.Append(1)
l.Add(0)
l.Insert(2, 2)
l.Insert(3, 3)
l.Delete(2)
assert.Equal(t, "0,1,3", l.ToString())
})
}
|
Java
|
UTF-8
| 2,224 | 2.015625 | 2 |
[] |
no_license
|
package ml.ibs.epi_droid_app;
import android.util.Log;
import com.orm.dsl.Ignore;
import java.util.Date;
public class StockData extends BaseData {
@Ignore
private static final String TAG = Constants.getLogTag("StockData");
Date send_date = null;
int pheno_quantite_recue = -1;
int pheno_quantite_utilisee = -1;
int pheno_quantite_perdue = -1;
int pheno_quantite_restante = -1;
int carba_quantite_recue = -1;
int carba_quantite_utilisee = -1;
int carba_quantite_perdue = -1;
int carba_quantite_restante = -1;
int sodi_quantite_recue = -1;
int sodi_quantite_utilisee = -1;
int sodi_quantite_perdue = -1;
int sodi_quantite_restante = -1;
Boolean isSend = false;
Boolean isSave = false;
public StockData() {}
public static StockData get() {
StockData report = getUniqueRecord(StockData.class);
if (report == null) {
Log.d(TAG, "No Record in DB. Creating.");
report = new StockData();
Log.d(TAG, "NEW : " + report.toString());
report.safeSave();
Log.d(TAG, "safeSave : " + report.toString());
} else {
Log.d(TAG, "Record exist in Database.");
}
return report;
}
public String buildSMSText() {
return Constants.keyStock + Constants.sepaData +
Utils.dateTostrDate(this.send_date) + Constants.sepaData +
this.pheno_quantite_recue + Constants.sepaData +
this.pheno_quantite_utilisee + Constants.sepaData +
this.pheno_quantite_perdue + Constants.sepaData +
this.pheno_quantite_restante + Constants.sepaData +
this.carba_quantite_recue + Constants.sepaData +
this.carba_quantite_utilisee + Constants.sepaData +
this.carba_quantite_perdue + Constants.sepaData +
this.carba_quantite_restante + Constants.sepaData +
this.sodi_quantite_recue + Constants.sepaData +
this.sodi_quantite_utilisee + Constants.sepaData +
this.sodi_quantite_perdue + Constants.sepaData +
this.sodi_quantite_restante;
}
}
|
Java
|
UTF-8
| 2,029 | 2.203125 | 2 |
[] |
no_license
|
package com.lauvan.meip.service.db.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import com.lauvan.meip.service.db.entity.BaseEntity;
import com.lauvan.meip.service.item.Item;
@SuppressWarnings("unchecked")
public abstract class CommonDao<E extends BaseEntity, I extends Item> extends HibernateDao<BaseEntity> {
public abstract I entityToItem(E paramE);
public abstract void buildSql(StringBuffer paramStringBuffer, I paramI);
public List<E> find(String sql) {
return (List<E>)super.find(sql, new Object[0]);
}
public List<E> getAll(Class<E> clazz) {
return (List<E>)super.find("select a from " + clazz.getSimpleName() + " a", new Object[0]);
}
public List<E> getAll(Class<E> clazz, String where) {
return (List<E>)super.find("select a from " + clazz.getSimpleName() + " a where " + where, new Object[0]);
}
@Override
@Autowired
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public Long executeUpdate(String sql) {
Session session = getSessionFactory().getCurrentSession();
Query query = session.createQuery(sql);
return (long)query.executeUpdate();
}
public Integer intValue(String sql) {
Session session = getSessionFactory().getCurrentSession();
if(!session.isOpen()) {
session = getSessionFactory().openSession();
}
Query query = session.createQuery(sql);
Integer i = (Integer)query.uniqueResult();
return i;
}
public Long longValue(String sql) {
Session session = getSessionFactory().getCurrentSession();
if(!session.isOpen()) {
session = getSessionFactory().openSession();
}
Query query = session.createQuery(sql);
Long l = (Long)query.uniqueResult();
return l;
}
public abstract List<E> list(String sql, Integer firstResult, Integer maxResults);
}
|
C
|
GB18030
| 628 | 3.21875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct node{
DataType data;
struct node* next;
}Qnode,*pQnode;
typedef struct {
pQnode front,rear;
}LinkQueue,*pLinkQueue;
//1.еijʼ
pLinkQueue Init_LinkQueue();
//2.жӶӿ
int Empty_LinkQueue(pLinkQueue pQueue);
//3.(1ʾɹ)
int In_LinkQueue(pLinkQueue pQueue,DataType x);
//4.ӣ1ʾɹ
int Out_LinkQueue(pLinkQueue pQueue,DataType *x);
//5.ͷԪأ1ʾɹ
int Front_LinkQueue(pLinkQueue pQueue,DataType *x);
//6.ٶ
void Destroy_LinkQueue(pLinkQueue *pQueue);
|
Java
|
UTF-8
| 4,335 | 3.5625 | 4 |
[] |
no_license
|
package Meituan;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* @author pandaxubo
* @description
* 题目描述:
* 在小团的公司中,有n位员工。除了最高领导——小团外,每位员工有且仅有一位直接领导。所以,公司内从属关系可以看成一棵树。
*
* 现在,公司接到一个项目,需要重新划分这n位员工的从属关系。新的划分描述如下:
*
* 1.每个人要么没有下属,要么有至少两个直接下属(即至少有两人的直接领导为这个人)
*
* 2.第 i 个人的下属(包括自己)有恰好 ai 个。
*
* 请注意,直接下属和下属(包括自己)可分别看做树上点的"儿子"和"子树"。
*
* 请问是否存在这么一种关系?注意,输入不会给出最高领导的编号。
*
*
*
* 输入描述
* 输入包含多组数据。
*
* 对于每组数据,第一行一个整数n,表示公司有n个人。
*
* 接下来一行n个数,第 i 个数为ai,含义如题面所示。
*
* (n≤24,数据组数在10以内)
*
* 输出描述
* 对每组数据,输出一行"YES"或"NO",代表是否存在这一种从属关系。
*
*
* 样例输入
* 3
* 1 1 3
* 2
* 1 2
* 样例输出
* YES
* NO
*
* 提示
* 对于第一组样例,1和2的直接领导均为3即可
* 对于第二组样例,无法构造出符合题目要求的关系。注意每个有下属的人至少有2个直接下属。
*/
public class RedesignStructure {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
boolean flag = false;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int empcnt = 0;
for (int a : arr) {
if (a == 1) {
empcnt++;
} else {
if (a == empcnt + 1 && a > 2 && a == n) {
flag = true;
}
}
}
if (flag) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
/***************************************
* c++版本:
*
* n=24明显提示我们是dfs+剪枝,先把输入从大到小排序。
* 首先预检查:1. arr[0]必须等于n 2. arr[i]不能等于2
* 然后dfs:
* 1. arr[i]表示i剩下多少总子节点未分配。child[i]表示i目前分配了多少子节点。set<int> can (candidate)存有子节点未分配的节点(即arr[i]大于1的所有i)。
* 2. 从x=1开始dfs,每轮dfs去找can中的节点i,如果arr[i] > arr[x],( 且不满足(arr[i] - arr[x] == 1 && child[i]==0),不然i就只能分配x一个子节点,这是不超时的关键。),则把x当成i的字节点,然后去试dfs(x+1).
* 3. 直到x=n,检查是否所有arr[i]==1 && child[i] != 1,arr[i]=1因为最后只剩下自己没分配出去。
*
* int n;
* int arr[25];
* int child[25];
*
* bool dfs(int x, set<int>& can) {
* if (x == n) {
* for (int i = 0; i < n; i++) {
* if (arr[i] != 1 || child[i] == 1) return false;
* }
* return true;
* }
* set<int> new_can = can;
* if (arr[x] != 1) new_can.insert(x);
* for (int i : can) {
* if (arr[i] > arr[x]) {
* if (arr[i] == arr[x] + 1 && child[i] == 0) continue;
* arr[i] -= arr[x];
* child[i]++;
* if (arr[i] == 1) new_can.erase(i);
* if (dfs(x + 1, new_can)) return true;
* if (arr[i] == 1) new_can.insert(i);
* arr[i] += arr[x];
* child[i]--;
* }
* }
* return false;
* }
*
* void solve() {
* bool flag = true;
* REP(i, n) {
* cin >> arr[i];
* if (arr[i] == 2) {
* flag = false;
* }
* }
* if (!flag) {
* cout << "NO" << endl;
* return;
* }
*
* sort(arr, arr + n, greater<int>());
*
* if (arr[0] != n) {
* cout << "NO" << endl;
* return;
* }
*
* set<int> can;
* can.insert(0);
* memset(child, 0, sizeof(child));
* if (dfs(1, can)) {
* cout << "YES" << endl;
* } else {
* cout << "NO" << endl;
* }
* }
*/
|
Shell
|
UTF-8
| 1,471 | 3.640625 | 4 |
[] |
no_license
|
#!/bin/bash
set -x
### puppet master hostname
puppet_server_hostname=""
puppet_server_ipaddress=""
if [ -z $puppet_server_hostname ]; then
echo "puppet_server_hostname not set!"
exit
fi
if [ -z $puppet_server_ipaddress ]; then
echo "puppet_server_ipaddress not set!"
exit
fi
### client props
hostname=$(hostname -f)
## all interfaces should be checked to find 192.168.[0-9].x
re="192\.168\.[0-9]\..*"
ips=$(ifconfig | grep "inet " | awk '{print $2}' | cut -d: -f2)
for ip in $ips
do
if [[ $ip =~ $re ]];then
ipaddress=$ip
break
fi
done
if [ -z $ipaddress ]; then
echo "no proper lan address"
exit
fi
### install necesarry repos.
wget http://apt.puppetlabs.com/puppetlabs-release-precise.deb -O /tmp/puppetlabs-release-precise.deb
sudo dpkg -i /tmp/puppetlabs-release-precise.deb
### install puppet client
sudo apt-get update
sudo apt-get install puppet=3.4.3-1puppetlabs1 -y
### so we can kick from puppet master
cat >> /etc/puppet/puppet.conf <<END
listen = true
END
### ensure puppet server is in client configuration
sudo sed -i "/\[main\]/aserver = $puppet_server_hostname" /etc/puppet/puppet.conf
### get configurations from puppetmaster
# fqdn of selfmachine
sudo puppet resource host $hostname ip="$ipaddress"
# fqdn of puppetmaster
sudo puppet resource host "$puppet_server_hostname" ip=$puppet_server_ipaddress
# init puppet agent
sudo puppet agent --test --server "$puppet_server_hostname"
|
Ruby
|
UTF-8
| 1,069 | 4 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# #write out your code here
# def least_coins(cents)
# if cents%25 ==0
# puts {:quarters => cents/25}
# elsif cents%5 == 0
# puts {:nickels => cents/5}
# elsif cents%1 == 0
# puts {:pennies => cents/1}
# elsif cents%10 == 0
# puts {:dimes => cents/10}
# end
# #Code your answer here!
# least_coins(50)
def least_coins(cents)
coins = {:quarters =>0, :nickels =>0, :dimes =>0, :pennies=>0}
quarters = cents / 25
if quarters ==0
coins[:quarters]=0
elsif quarters!=0
coins[:quarters]=quarters
cents = cents - quarters*25
end
nickels = cents/5
if nickels==0
coins[:nickels]=0
elsif nickels!=0
coins[:nickels]=nickels
cents=cents-nickels*5
end
dimes = cents/10
if dimes == 0
coins[:dimes] = 0
elsif dimes != 0
coins[:dimes] = dimes
cents = cents - dimes*10
puts coins
end
pennies=cents
if pennies==0
coins[:pennies]=0
elsif pennies!=0
coins[:pennies]=pennies
cents=cents
print coins
end
end
least_coins(78)
|
C
|
WINDOWS-1251
| 2,439 | 3.390625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <locale.h>
#define N 10
void menu()
{
printf("\n 1. ...\n");
printf("\n\n");
}
int cod(int str[])
{
int i,a;
printf(" -: \n");
do
{
scanf("%d", &a);
}
while (a < 1000 || a > 1009);
for (i = 0; i < N; i++)
{
str[i] = a;
return i;
}
}
void info(char tov[][15], int a[], int p[], float skd[], int b)
{
int i;
printf("\n : \n");
printf("%c", tov[b][i]);
printf("\n: %d\n", a[b]);
printf(": %d\n", p[b]);
printf(": %0.0f\n", skd[b]);
}
float summa(int p[], float skd[], int b)
{
int i;
float summa = 0.0;
for (i = 0; i < N; i++)
{
summa = p[b] - (skd[b] / 100) * p[b];
}
return summa;
}
void itog(char tov[][15], int p[], int kol[], float skd[], float price)
{
int i,j;
printf("\n:\n");
for (i = 0; i < N; i++)
{
if (kol[i] != 0)
{
printf("%c\n", tov[i][j]);
printf(" . : %d .\n", p[i]);
printf(" : %d\n", kol[i]);
printf(": %0.0f \n", skd[i]);
printf(" : %f", p[i] - (skd[i] / 100) * p[i] * kol[i]);
}
}
printf("\n : %f \n", price);
}
void main()
{
int c[N] = {1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009};
int p[N] = {1000, 450, 890, 2300, 3000, 800, 2100, 20, 300, 120};
int var;
int a = 0;
float price = 0;
char tov[N][15] = { "", "", "o", "- ", "", "", "", "", "", "" };
int str[100] = { 0 };
float skd[] = {10, 10, 1, 5, 30, 10, 10, 10, 20, 10};
setlocale(LC_ALL, "Rus");
menu();
while(1)
{
printf("1 - \n");
printf("2 - \n");
scanf("%d", &var);
switch (var)
{
case 1:
a = cod(c);
str[a] = str[a] + 1;
info(tov, c, p, skd, a);
price += summa(p, skd, a);
break;
case 2:
itog(tov, p, str, skd, price);
break;
}
if (var == 2)
{
break;
}
}
}
|
Markdown
|
UTF-8
| 1,759 | 3.296875 | 3 |
[] |
no_license
|
+++
title = "DevOps报表"
description = "DevOps报表会通过各种直观的图表向您展示某个项目下关于DevOps的各种指标,比如各个应用的代码提交情况、应用构建情况以及应用的部署情况。"
weight = 7
+++
## 介绍
DevOps报表会通过各种直观的图表向您展示某个项目下关于DevOps的各种指标,比如各个应用的代码提交情况、应用构建情况以及应用的部署情况。其中包含了代码提交图、构建次数图、构建时长图、部署次数图和部署时长图。
通过本文您将了解什么是DevOps报表,以及DevOps报表能传达出什么信息。
- **菜单层次**:项目层
- **菜单路径**:敏捷管理>报表>DevOps报表
- **默认角色**:项目成员
## 功能
* [代码提交图](../devops-report/code-commits):跟踪某个项目下团队与个人的代码提交情况。这有助于您了解团队的整体效率与个人效率。
* [构建次数图](../devops-report/build-frequency):从应用的维度展示某个应用在某段时间的构建次数,构建成功次数以及构建成功率。这将帮助您快速地了解到该应用的构建情况。
* [构建时长图](../devops-report/build-duration):从应用的维度展示所选时间段某个应用每一次构建的时长。这将帮助您更直观地了解应用构建的效率。
* [部署次数图](../devops-report/deploy-frequency):展示了项目下各个环境中各个应用的部署频率。这将帮助您了解团队的部署频次与整体的效率。
* [部署时长图](../devops-report/deploy-duration):展示该项目下某一环境中各个应用部署时长等部署相关的信息。这将帮助您了解各个应用的部署情况。
|
JavaScript
|
UTF-8
| 7,148 | 2.96875 | 3 |
[] |
no_license
|
// fetch
fetch("http://kea-alt-del.dk/t5/api/productlist")
.then(res => res.json())
.then(data => fml(data));
function fml(dishes) { // call a foreach function for each fetched element
dishes.forEach(addDish);
console.log(dishes.id);
}
// const declaration
const base = "https://kea-alt-del.dk/t5/site/imgs/";
let ol = 0;
// functions
function addDish(dish) { // adds the dishes (dish)
const myTemplate = document.querySelector("#dish").content;
const cloneDish = myTemplate.cloneNode(true);
cloneDish.querySelector(".pic").id=dish.id;
cloneDish.querySelector(".name").textContent = dish.name;
cloneDish.querySelector(".pic").src = base + "small/" + dish.image + "-sm.jpg";
cloneDish.querySelector(".price").textContent = dish.price + ",- kr";
if(dish.soldout)
{
cloneDish.querySelector("#soldOutText").style.display = "block";
cloneDish.querySelector(".price").style.color = "rgba(0,0,0, 0.3)";
cloneDish.querySelector(".pic").style.filter = "grayscale(100%)";
cloneDish.querySelector(".Btn").style.backgroundColor = "gray";
cloneDish.querySelector(".Btn").style.color = "white";
cloneDish.querySelector(".Btn").style.cursor = "initial";
}
else if(dish.discount)
{
cloneDish.querySelector(".price").style.textDecoration = "line-through";
cloneDish.querySelector(".price").style.color = "rgba(0, 0, 0, 0.5)";
cloneDish.querySelector(".newPrice").textContent = dish.price - (dish.price * dish.discount / 100) + " kr";
cloneDish.querySelector(".newPrice").textContent = cloneDish.querySelector(".newPrice").textContent.replace(".", ",");
}
else {
cloneDish.querySelector(".newPrice").style.display = "none";
}
cloneDish.querySelector(".shortDesc").textContent = dish.shortdescription;
const parentDishStarter = document.querySelector("section#starter");
const parentDishMain = document.querySelector("section#main");
const parentDishDessert = document.querySelector("section#dessert");
const parentDishDrinks = document.querySelector("section#drinks");
const parentDishSideorders = document.querySelector("section#sideorders");
if(dish.category == "starter")
parentDishStarter.appendChild(cloneDish);
else if(dish.category == "main")
parentDishMain.appendChild(cloneDish);
else if(dish.category == "dessert")
parentDishDessert.appendChild(cloneDish);
else if(dish.category == "drinks")
parentDishDrinks.appendChild(cloneDish);
else
parentDishSideorders.appendChild(cloneDish);
//overlay
}
function openCloseOverlay(_id) {
console.log(_id);
const list = document.getElementById("allergens");
const entry = document.createElement("li");
if(!ol) {
document.querySelector("#olBtn").style.display = "none";
document.querySelector(".overlay").style.display = "block";
ol++;
let c = 0;
fetch("https://kea-alt-del.dk/t5/api/product?id=" + _id)
.then(res => res.json())
.then(data => fml2(data))
function fml2(selDish) {
document.querySelector("#olBtn").style.display = "block";
document.querySelector(".olPic").src = base + "medium/" + selDish.image + "-md.jpg";
document.querySelector(".olName").textContent = selDish.name;
document.querySelector(".longDesc").textContent = selDish.longdescription;
document.querySelector(".priceOl").textContent = selDish.price + ",- kr";
document.querySelector("#region>p").textContent = selDish.region;
while(c < selDish.stars) {
document.querySelector("#stars>p").textContent += "★";
c++;
}
c=5;
while(c > selDish.stars) {
document.querySelector("#stars>p").textContent += "☆";
c--;
}
if(selDish.alcohol)
document.querySelector("#alcohol>p").textContent = "Yes";
else
document.querySelector("#alcohol>p").textContent = "No";
if(selDish.vegetarian)
document.querySelector("#vegetarian>p").textContent = "Yes";
else
document.querySelector("#vegetarian>p").textContent = "No";
if(selDish.allergens == "") {
entry.appendChild(document.createTextNode("None"));
list.appendChild(entry);
}
else {
selDish.allergens.forEach(putAl);
}
if(selDish.soldout)
{
document.querySelector(".priceOl").style.color = "rgba(0,0,0, 0.3)";
document.querySelector(".priceOl").style.textDecoration = "none";
document.querySelector("#olBtn").classList.remove("olBtn");
document.querySelector("#olBtn").classList.add("olBtn2");
document.querySelector(".newPriceOl").style.display = "none";
}
else if(selDish.discount)
{
document.querySelector("#olBtn").classList.remove("olBtn2");
document.querySelector("#olBtn").classList.add("olBtn");
document.querySelector(".priceOl").style.textDecoration = "line-through";
document.querySelector(".priceOl").style.color = "rgba(0, 0, 0, 0.5)";
document.querySelector(".newPriceOl").textContent = selDish.price - (selDish.price * selDish.discount / 100) + " kr";
document.querySelector(".newPriceOl").textContent = document.querySelector(".newPriceOl").textContent.replace(".", ",");
document.querySelector(".newPriceOl").style.display = "block";
}
else {
document.querySelector("#olBtn").classList.remove("olBtn2");
document.querySelector("#olBtn").classList.add("olBtn");
document.querySelector(".priceOl").style.textDecoration = "none";
document.querySelector(".priceOl").style.color = "black";
document.querySelector(".newPriceOl").style.display = "none";
}
console.log(_id);
}
function putAl(allergen) {
entry.appendChild(document.createTextNode("-" + allergen));
list.appendChild(entry);
}
}
else {
document.querySelector(".overlay").style.display = "none";
ol--;
while(document.querySelector("#allergens>li")) {
document.querySelector("#allergens>li").remove();
}
document.querySelector("#alcohol>p").textContent = "";
document.querySelector("#stars>p").textContent = "";
document.querySelector("#vegetarian>p").textContent = "";
document.querySelector(".olName").textContent = "";
document.querySelector(".longDesc").textContent = "";
document.querySelector(".olPic").src = "";
document.querySelector(".priceOl").textContent = "";
document.querySelector(".newPriceOl").textContent = "";
}
}
|
C#
|
UTF-8
| 1,402 | 2.578125 | 3 |
[] |
no_license
|
using CustomerManager.Code.Logic;
using CustomerManager.Code.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CustomerManager.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Trace.WriteLine("GET /HOME");
return View();
}
public ActionResult GuestsFor29()
{
Trace.WriteLine("GET /GuestsFor29");
GuestLogic guestLogic = new GuestLogic();
List<Guest> guests = guestLogic.GetGuestsFor29();
return View(guests);
}
public ActionResult Create()
{
Trace.WriteLine("CREATE /GUEST");
Guest guest = new Guest();
return View(guest);
}
[HttpPost]
public ActionResult Create(Guest guest)
{
Trace.WriteLine("POST /GUEST");
if (ModelState.IsValid)
{
Trace.WriteLine("ModelState valid");
GuestLogic logic = new GuestLogic();
logic.AddGuestFor29(guest);
Trace.WriteLine("RedirectingToIndex");
return RedirectToAction("Index");
}
else
{
return View(guest);
}
}
}
}
|
Java
|
UTF-8
| 417 | 2.109375 | 2 |
[] |
no_license
|
package org.jukeboxmc.item;
import org.jukeboxmc.block.BlockPrismarineBricksStairs;
/**
* @author LucGamesYT
* @version 1.0
*/
public class ItemPrismarineBricksStairs extends Item {
public ItemPrismarineBricksStairs() {
super ( "minecraft:prismarine_bricks_stairs" );
}
@Override
public BlockPrismarineBricksStairs getBlock() {
return new BlockPrismarineBricksStairs();
}
}
|
Python
|
UTF-8
| 870 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
import numpy as np
class FeatureDimension:
"""
Implements a feature dimension of the MAP-Elites algorithm
"""
def __init__(self, name, feature_simulator, bins):
"""
:param name: Name of the feature dimension
:param feature_simulator: Name of the method to evaluate the feature
:param bins: Array of bins, from starting value to last value of last bin
"""
self.name = name
self.feature_simulator = feature_simulator
self.min = np.inf
self.bins = bins
def feature_descriptor(self, map_elite, x):
"""
Simulate the candidate solution x and record its feature descriptor
:param map_elite:
:param x: genotype of candidate solution x
:return:
"""
i = map_elite.feature_simulator(self.feature_simulator, x)
return i
|
Java
|
UTF-8
| 32,477 | 2 | 2 |
[] |
no_license
|
package com.redhat.contentspec.processor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import com.redhat.contentspec.ContentSpec;
import com.redhat.contentspec.Level;
import com.redhat.contentspec.Process;
import com.redhat.contentspec.SpecNode;
import com.redhat.contentspec.SpecTopic;
import com.redhat.contentspec.entities.Relationship;
import com.redhat.contentspec.enums.LevelType;
import com.redhat.contentspec.enums.RelationshipType;
import com.redhat.contentspec.interfaces.ShutdownAbleApp;
import com.redhat.contentspec.constants.CSConstants;
import com.redhat.contentspec.processor.constants.ProcessorConstants;
import com.redhat.contentspec.processor.structures.ProcessingOptions;
import com.redhat.contentspec.processor.utils.ProcessorUtilities;
import com.redhat.contentspec.rest.RESTManager;
import com.redhat.contentspec.rest.RESTReader;
import com.redhat.contentspec.utils.logging.ErrorLogger;
import com.redhat.contentspec.utils.logging.ErrorLoggerManager;
import com.redhat.ecs.commonutils.DocBookUtilities;
import com.redhat.ecs.commonutils.HashUtilities;
import com.redhat.ecs.constants.CommonConstants;
import com.redhat.topicindex.rest.collections.BaseRestCollectionV1;
import com.redhat.topicindex.rest.entities.ComponentBaseTopicV1;
import com.redhat.topicindex.rest.entities.ComponentTagV1;
import com.redhat.topicindex.rest.entities.ComponentTopicV1;
import com.redhat.topicindex.rest.entities.interfaces.RESTBaseTopicV1;
import com.redhat.topicindex.rest.entities.interfaces.RESTCategoryV1;
import com.redhat.topicindex.rest.entities.interfaces.RESTTagV1;
import com.redhat.topicindex.rest.entities.interfaces.RESTTopicV1;
import com.redhat.topicindex.rest.entities.interfaces.RESTTranslatedTopicV1;
/**
* A class that is used to validate a Content Specification and the objects within a Content Specification. It provides methods for
* validating, ContentSpecs, Levels, Topics and Relationships.
*
* @author lnewson
*/
public class ContentSpecValidator<T extends RESTBaseTopicV1<T, U>, U extends BaseRestCollectionV1<T, U>> implements ShutdownAbleApp
{
private final RESTReader reader;
private final ErrorLogger log;
private final ProcessingOptions processingOptions;
private final AtomicBoolean isShuttingDown = new AtomicBoolean(false);
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private final Class<T> clazz;
private String locale;
@Override
public void shutdown()
{
isShuttingDown.set(true);
}
@Override
public boolean isShutdown()
{
return shutdown.get();
}
/**
* Constructor
*
* @param elm An Error Logger Manager that is used to capture log messages.
* @param restManager The manager that hands the rest communication.
* @param permissiveMode Whether validation should be done in permissive mode.
* @param ignoreSpecRevisions Whether the Checksum/SpecRevision attribute should be ignored.
*/
public ContentSpecValidator(final Class<T> clazz, final ErrorLoggerManager elm, final RESTManager restManager, final ProcessingOptions processingOptions)
{
this.clazz = clazz;
log = elm.getLogger(ContentSpecValidator.class);
reader = restManager.getReader();
this.processingOptions = processingOptions;
this.locale = CommonConstants.DEFAULT_LOCALE;
}
@SuppressWarnings("deprecation")
/**
* Validates that a Content Specification is valid by checking the META data, child levels and topics.
*
* @param contentSpec The content specification to be validated.
* @param specTopics The list of topics that exist within the content specification.
* @return True if the content specification is valid, otherwise false.
*/
public boolean validateContentSpec(final ContentSpec contentSpec, final Map<String, SpecTopic> specTopics)
{
locale = contentSpec.getLocale() == null ? locale : contentSpec.getLocale();
// Check if the app should be shutdown
if (isShuttingDown.get())
{
shutdown.set(true);
return false;
}
boolean valid = true;
if (contentSpec.getTitle() == null || contentSpec.getTitle().equals(""))
{
log.error(ProcessorConstants.ERROR_CS_NO_TITLE_MSG);
valid = false;
}
if (contentSpec.getProduct() == null || contentSpec.getProduct().equals(""))
{
log.error(ProcessorConstants.ERROR_CS_NO_PRODUCT_MSG);
valid = false;
}
if (contentSpec.getVersion() == null || contentSpec.getVersion().equals(""))
{
log.error(ProcessorConstants.ERROR_CS_NO_VERSION_MSG);
valid = false;
}
if (contentSpec.getPreProcessedText().isEmpty())
{
log.error(ProcessorConstants.ERROR_PROCESSING_ERROR_MSG);
valid = false;
}
if (contentSpec.getDtd() == null || contentSpec.getDtd().equals(""))
{
log.error(ProcessorConstants.ERROR_CS_NO_DTD_MSG);
valid = false;
// Check that the DTD specified is a valid DTD format
}
else if (!contentSpec.getDtd().toLowerCase().equals("docbook 4.5"))
{
log.error(ProcessorConstants.ERROR_CS_INVALID_DTD_MSG);
valid = false;
}
if (contentSpec.getCreatedBy() == null)
{
log.error(ProcessorConstants.ERROR_PROCESSING_ERROR_MSG);
valid = false;
}
if (contentSpec.getCopyrightHolder() == null || contentSpec.getCopyrightHolder().equals(""))
{
log.error(ProcessorConstants.ERROR_CS_NO_COPYRIGHT_MSG);
valid = false;
}
// Check that the content specification isn't empty
if (contentSpec.getBaseLevel() == null)
{
log.error(ProcessorConstants.ERROR_CS_EMPTY_MSG);
valid = false;
}
// If editing then check that the ID exists & the SpecRevision match
if (contentSpec.getId() != 0)
{
final RESTTopicV1 contentSpecTopic = reader.getPostContentSpecById(contentSpec.getId(), null);
if (contentSpecTopic == null)
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_CS_ID_MSG, "ID=" + contentSpec.getId()));
valid = false;
}
// Check that the revision is valid
if (!processingOptions.isIgnoreSpecRevision() && contentSpecTopic != null)
{
final String currentChecksum = HashUtilities.generateMD5(contentSpecTopic.getXml().replaceFirst("CHECKSUM[ ]*=.*(\r)?\n", ""));
if (contentSpec.getChecksum() != null)
{
if (!contentSpec.getChecksum().equals(currentChecksum))
{
log.error(String.format(ProcessorConstants.ERROR_CS_NONMATCH_CHECKSUM_MSG, contentSpec.getChecksum(), currentChecksum));
valid = false;
}
}
else if (contentSpec.getRevision() != null)
{
// Check that the revision matches
int latestRev = reader.getLatestCSRevById(contentSpec.getId());
if (contentSpec.getRevision() != latestRev)
{
log.error(String.format(ProcessorConstants.ERROR_CS_NONMATCH_SPEC_REVISION_MSG, contentSpec.getRevision(), latestRev));
valid = false;
}
}
else
{
log.error(String.format(ProcessorConstants.ERROR_CS_NONMATCH_CHECKSUM_MSG, null, currentChecksum));
valid = false;
}
}
// Check that the Content Spec isn't read only
if (contentSpecTopic != null && ComponentTopicV1.returnProperty(contentSpecTopic, CSConstants.CSP_READ_ONLY_PROPERTY_TAG_ID) != null)
{
if (!ComponentTopicV1.returnProperty(contentSpecTopic, CSConstants.CSP_READ_ONLY_PROPERTY_TAG_ID).getValue().matches("(^|.*,)" + contentSpec.getCreatedBy() + "(,.*|$)"))
{
log.error(ProcessorConstants.ERROR_CS_READ_ONLY_MSG);
valid = false;
}
}
}
// Check that the injection options are valid
if (contentSpec.getInjectionOptions() != null)
{
for (final String injectionType: contentSpec.getInjectionOptions().getStrictTopicTypes())
{
final List<RESTTagV1> tags = reader.getTagsByName(injectionType);
if (tags.size() == 1)
{
if (!ComponentTagV1.containedInCategory(tags.get(0), CSConstants.TYPE_CATEGORY_ID))
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_INJECTION_TYPE_MSG, injectionType));
valid = false;
}
}
else
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_INJECTION_TYPE_MSG, injectionType));
valid = false;
}
}
}
// Check that each level is valid
if (!validateLevel(contentSpec.getBaseLevel(), specTopics, contentSpec.getAllowEmptyLevels())) valid = false;
// reset the locale back to its default
this.locale = CommonConstants.DEFAULT_LOCALE;
return valid;
}
/**
* Validate a set of relationships created when parsing.
*
* @param relationships A list of all the relationships in a content specification.
* @param specTopics The list of topics that exist within the content specification.
* @param targetLevels The list of target levels in a content specification.
* @param targetTopics The list of target topics in a content specification.
* @return True if the relationships are valid, otherwise false.
*/
public boolean validateRelationships(final HashMap<String, List<Relationship>> relationships, final HashMap<String, SpecTopic> specTopics, final HashMap<String, Level> targetLevels, final HashMap<String, SpecTopic> targetTopics)
{
boolean error = false;
for(final String topicId: relationships.keySet())
{
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true);
return false;
}
for (final Relationship relationship: relationships.get(topicId))
{
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true);
return false;
}
final String relatedId = relationship.getSecondaryRelationshipTopicId();
// The relationship points to a target so it must be a level or topic
if (relatedId.toUpperCase().matches(ProcessorConstants.TARGET_REGEX))
{
if (targetTopics.containsKey(relatedId) && !targetLevels.containsKey(relatedId))
{
// Nothing to validate here so do nothing
}
else if (!targetTopics.containsKey(relatedId) && targetLevels.containsKey(relatedId))
{
if (relationship.getType() == RelationshipType.NEXT)
{
log.error(String.format(ProcessorConstants.ERROR_NEXT_RELATED_LEVEL_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
else if (relationship.getType() == RelationshipType.PREVIOUS)
{
log.error(String.format(ProcessorConstants.ERROR_PREV_RELATED_LEVEL_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
}
else
{
log.error(String.format(ProcessorConstants.ERROR_TARGET_NONEXIST_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
// The relationship isn't a target so it must point to a topic directly
}
else
{
if (!relatedId.matches(CSConstants.NEW_TOPIC_ID_REGEX))
{
// The relationship isn't a unique new topic so it will contain the line number in front of the topic ID
if (relatedId.startsWith("X"))
{
// Duplicated topics are never unique so throw an error straight away.
log.error(String.format(ProcessorConstants.ERROR_INVALID_DUPLICATE_RELATIONSHIP_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
else
{
int count = 0;
SpecTopic relatedTopic = null;
// Get the related topic and count if more then one is found
for (final String specTopicId: specTopics.keySet())
{
if (specTopicId.matches("^[0-9]+-" + relatedId + "$"))
{
relatedTopic = specTopics.get(specTopicId);
count++;
}
}
// Check to make sure the topic doesn't relate to itself
if (relatedTopic != specTopics.get(topicId))
{
if (count > 1)
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_RELATIONSHIP_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
else if (count == 0)
{
log.error(String.format(ProcessorConstants.ERROR_RELATED_TOPIC_NONEXIST_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
}
else
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_RELATED_TO_ITSELF_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
}
}
}
else
{
if (specTopics.containsKey(relatedId))
{
// Check to make sure the topic doesn't relate to itself
if (specTopics.get(relatedId) == specTopics.get(topicId))
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_RELATED_TO_ITSELF_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
}
}
else
{
log.error(String.format(ProcessorConstants.ERROR_RELATED_TOPIC_NONEXIST_MSG, specTopics.get(topicId).getLineNumber(), specTopics.get(topicId).getText()));
error = true;
}
}
}
}
}
return !error;
}
/**
* Validates a level to ensure its format and child levels/topics are valid.
*
* @param level The level to be validated.
* @param specTopics The list of topics that exist within the content specification.
* @param csAllowEmptyTopics If the "Allow Empty Topics" bit is set in a content specification.
* @return True if the level is valid otherwise false.
*/
public boolean validateLevel(final Level level, final Map<String, SpecTopic> specTopics, final boolean csAllowEmptyLevels)
{
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true);
return false;
}
boolean valid = true;
// Check that the level isn't empty
if (level.getNumberOfSpecTopics() <= 0 && level.getNumberOfChildLevels() <= 0 /*&& !allowEmptyLevels && (allowEmptyLevels && !csAllowEmptyLevels)*/)
{
log.error(String.format(ProcessorConstants.ERROR_LEVEL_NO_TOPICS_MSG, level.getLineNumber(), level.getType().getTitle(), level.getType().getTitle(), level.getText()));
valid = false;
}
if (level.getType() == null)
{
log.error(ProcessorConstants.ERROR_PROCESSING_ERROR_MSG);
valid = false;
}
if (level.getTitle() == null || level.getTitle().equals(""))
{
log.error(String.format(ProcessorConstants.ERROR_LEVEL_NO_TITLE_MSG, level.getLineNumber(), level.getType().getTitle(), level.getText()));
valid = false;
}
// Validate the tags
if (!validateTopicTags(level, level.getTags(false)))
{
valid = false;
}
// Validate the sub levels
for (final Level l: level.getChildLevels())
{
if (!validateLevel(l, specTopics, csAllowEmptyLevels)) valid = false;;
}
// Validate the topics in this level
for (final SpecTopic t: level.getSpecTopics())
{
if (!validateTopic(t, specTopics)) valid = false;;
}
// Validate certain requirements depending on the type of level
switch (level.getType())
{
case APPENDIX:
if (!(level.getParent().getType() == LevelType.BASE || level.getParent().getType() == LevelType.PART))
{
log.error(String.format(ProcessorConstants.ERROR_CS_NESTED_APPENDIX_MSG, level.getLineNumber(), level.getText()));
valid = false;
}
break;
case CHAPTER:
if (!(level.getParent().getType() == LevelType.BASE || level.getParent().getType() == LevelType.PART))
{
log.error(String.format(ProcessorConstants.ERROR_CS_NESTED_CHAPTER_MSG, level.getLineNumber(), level.getText()));
valid = false;
}
break;
case PROCESS:
// Check that the process has no children
Process process = (Process) level;
if (process.getNumberOfChildLevels() != 0)
{
log.error(String.format(ProcessorConstants.ERROR_PROCESS_HAS_LEVELS_MSG, process.getLineNumber(), process.getText()));
valid = false;
}
break;
case PART:
if (level.getParent().getType() != LevelType.BASE)
{
log.error(String.format(ProcessorConstants.ERROR_CS_NESTED_PART_MSG, level.getLineNumber(), level.getText()));
valid = false;
}
break;
case SECTION:
if (!(level.getParent().getType() == LevelType.APPENDIX || level.getParent().getType() == LevelType.CHAPTER || level.getParent().getType() == LevelType.SECTION))
{
log.error(String.format(ProcessorConstants.ERROR_CS_SECTION_NO_CHAPTER_MSG, level.getLineNumber(), level.getText()));
valid = false;
}
break;
}
return valid;
}
/**
* Validates a topic against the database and for formatting issues.
*
* @param specTopic The topic to be validated.
* @param specTopics The list of topics that exist within the content specification.
* @return True if the topic is valid otherwise false.
*/
@SuppressWarnings("unchecked")
public boolean validateTopic(final SpecTopic specTopic, final Map<String, SpecTopic> specTopics)
{
// Check if the app should be shutdown
if (isShuttingDown.get())
{
shutdown.set(true);
return false;
}
boolean valid = true;
// Check that the topic exists in the spec by checking it's step
if (specTopic.getStep() == 0)
{
log.error(ProcessorConstants.ERROR_PROCESSING_ERROR_MSG);
valid = false;
}
// Checks that the id isn't null and is a valid topic ID
if (specTopic.getId() == null || !specTopic.getId().matches(CSConstants.ALL_TOPIC_ID_REGEX))
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_TOPIC_ID_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that the topic is inside a chapter/section/process/appendix/part
if (specTopic.getParent() == null || !(specTopic.getParent().getType() == LevelType.CHAPTER || specTopic.getParent().getType() == LevelType.APPENDIX
|| specTopic.getParent().getType() == LevelType.PROCESS || specTopic.getParent().getType() == LevelType.SECTION
/*|| specTopic.getParent().getType() == LevelType.PART*/))
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_OUTSIDE_CHAPTER_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that the title exists
if (specTopic.getTitle() == null || specTopic.getTitle().equals(""))
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TITLE_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that it is valid when escaped
else if (DocBookUtilities.escapeTitle(specTopic.getTitle()).isEmpty())
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_TOPIC_TITLE_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that we aren't using translations for anything but existing topics
if (!specTopic.isTopicAnExistingTopic())
{
// Check that we aren't processing translations
if (clazz == RESTTranslatedTopicV1.class)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_NEW_TRANSLATION_TOPIC, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
}
// Check that we are allowed to create new topics
if (!specTopic.isTopicAnExistingTopic() && !processingOptions.isAllowNewTopics())
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_NEW_TOPIC_BUILD, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// New Topics
if (specTopic.isTopicANewTopic())
{
if (specTopic.getType() == null || specTopic.getType().equals(""))
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TYPE_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that the type entered exists
final RESTTagV1 type = reader.getTypeByName(specTopic.getType());
if (type == null)
{
log.error(String.format(ProcessorConstants.ERROR_TYPE_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Validate the tags
if (!validateTopicTags(specTopic, specTopic.getTags(false)))
{
valid = false;
}
//Check Assigned Writer exists
if (!validateAssignedWriter(specTopic)) valid = false;
}
// Existing Topics
else if (specTopic.isTopicAnExistingTopic())
{
// Check that the id actually exists
final T topic;
if (clazz == RESTTranslatedTopicV1.class)
{
topic = (T) reader.getTranslatedTopicByTopicId(Integer.parseInt(specTopic.getId()), null, locale);
if (processingOptions.isAddRevisions() && specTopic.getRevision() == null)
{
specTopic.setRevision(((RESTTranslatedTopicV1) topic).getTopicRevision());
}
}
else
{
topic = (T) reader.getTopicById(Integer.parseInt(specTopic.getId()), specTopic.getRevision());
if (processingOptions.isAddRevisions() && specTopic.getRevision() == null)
{
specTopic.setRevision(topic.getRevision());
}
}
// Check that the topic actually exists
if (topic == null)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_ID_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
return false;
}
else
{
specTopic.setTopic(topic);
// Check to see if the topic contains the "Internal-Only" tag
if (ComponentBaseTopicV1.hasTag(topic, CSConstants.RH_INTERNAL_TAG_ID))
{
log.warn(String.format(ProcessorConstants.WARN_INTERNAL_TOPIC_MSG, specTopic.getLineNumber(), specTopic.getText()));
}
}
// Check that the topic has a valid id
if (topic.getId() <= 0)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_ID_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Validate the title matches if we aren't using permissive mode
if (!processingOptions.isPermissiveMode() && !specTopic.getTitle().equals(topic.getTitle()))
{
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + topic.getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(), "Specified: " + specTopic.getText(), topicTitleMsg));
valid = false;
}
// If we are using permissive mode then change the title to the correct title
else if (processingOptions.isPermissiveMode() && !specTopic.getTitle().equals(topic.getTitle()))
{
specTopic.setTitle(topic.getTitle());
}
// Check that tags aren't trying to be removed
if (!specTopic.getRemoveTags(false).isEmpty())
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_TOPIC_CANNOT_REMOVE_TAGS, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that the assigned writer, description and source URLS haven't been set
if (specTopic.getAssignedWriter(false) != null || specTopic.getDescription(false) != null || !specTopic.getSourceUrls().isEmpty())
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_BAD_OPTIONS, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that we aren't processing translations
if (!specTopic.getTags(true).isEmpty() && clazz == RESTTranslatedTopicV1.class)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TAGS_TRANSLATION_TOPIC, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
else
{
// Validate the tags
if (!validateTopicTags(specTopic, specTopic.getTags(false)))
{
valid = false;
}
}
}
// Duplicated Topics
else if (specTopic.isTopicADuplicateTopic())
{
String temp = "N" + specTopic.getId().substring(1);
// Check that the topic exists in the content specification
if (!specTopics.containsKey(temp))
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
else
{
// Check that the topic titles match the original
if (!specTopic.getTitle().equals(specTopics.get(temp).getTitle()))
{
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + specTopics.get(temp).getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(), specTopic.getText(), topicTitleMsg));
valid = false;
}
}
}
// Cloned Topics
else if (specTopic.isTopicAClonedTopic())
{
// Check if a description or type exists. If one does then generate a warning.
if ((specTopic.getType() != null && !specTopic.getType().equals("")) || (specTopic.getDescription(false) != null && !specTopic.getDescription(false).equals("")))
{
String format = "";
if (specTopic.getType() != null && !specTopic.getType().equals(""))
{
format += String.format(ProcessorConstants.WARN_TYPE_IGNORE_MSG, specTopic.getLineNumber(), "Cloned");
}
if (specTopic.getDescription(false) != null && !specTopic.getDescription(false).equals(""))
{
if (!format.equals("")) format += "\n ";
format += String.format(ProcessorConstants.WARN_DESCRIPTION_IGNORE_MSG, specTopic.getLineNumber(), "Cloned");
}
log.warn(String.format("%s" + ProcessorConstants.CSLINE_MSG, format, specTopic.getText()));
}
// Get the original topic from the database
int temp = Integer.parseInt(specTopic.getId().substring(1));
final RESTTopicV1 topic = reader.getTopicById(temp, null);
// Check that the original topic was found
if (topic == null)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
else
{
// Validate the title matches if we aren't using permissive mode
if (!processingOptions.isPermissiveMode() && !specTopic.getTitle().equals(topic.getTitle()))
{
String topicTitleMsg = "Topic " + topic.getId() + ": " + topic.getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(), specTopic.getText(), topicTitleMsg));
valid = false;
}
// If we are using permissive mode then change the title to the correct title
else if (processingOptions.isPermissiveMode() && !specTopic.getTitle().equals(topic.getTitle()))
{
specTopic.setTitle(topic.getTitle());
}
//Check Assigned Writer exists
if (!validateAssignedWriter(specTopic)) valid = false;
}
// Validate the tags
if (!validateTopicTags(specTopic, specTopic.getTags(false)))
{
valid = false;
}
// Duplicated Cloned Topics
}
else if (specTopic.isTopicAClonedDuplicateTopic())
{
// Find the duplicate topic in the content spec
final String temp = specTopic.getId().substring(1);
int count = 0;
SpecTopic clonedTopic = null;
for (final String topicId: specTopics.keySet())
{
if (topicId.endsWith(temp) && !topicId.endsWith(specTopic.getId()))
{
clonedTopic = specTopics.get(topicId);
count++;
}
}
// Check that the topic exists
if (count == 0)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that the referenced topic is unique
else if (count > 1)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_DUPLICATE_CLONES_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
else
{
// Check that the title matches
if (!specTopic.getTitle().equals(clonedTopic.getTitle()))
{
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + clonedTopic.getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(), specTopic.getText(), topicTitleMsg));
valid = false;
}
}
}
return valid;
}
/**
* Checks to make sure that the assigned writer for the topic is valid.
*
* @return True if the assigned writer exists in the database and is under the Assigned Writer category otherwise false.
*/
private boolean validateAssignedWriter(SpecTopic topic)
{
if (topic.getAssignedWriter(true) == null)
{
log.error(String.format(ProcessorConstants.ERROR_NO_WRITER_MSG, topic.getLineNumber(), topic.getText()));
return false;
}
//Check Assigned Writer exists
final List<RESTTagV1> tagList = reader.getTagsByName(topic.getAssignedWriter(true));
if (tagList.size() != 1)
{
log.error(String.format(ProcessorConstants.ERROR_WRITER_NONEXIST_MSG, topic.getLineNumber(), topic.getText()));
return false;
}
// Check that the writer tag is actually part of the Assigned Writer category
final RESTCategoryV1 cat = reader.getCategoryByTagId(tagList.get(0).getId());
if (cat == null)
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_WRITER_MSG, topic.getLineNumber(), topic.getText()));
return false;
}
// Check that tag is actually in the Assigned Writer category
if (cat.getId() != ProcessorConstants.ASSIGNED_WRITER_CATEGORY_ID)
{
log.error(String.format(ProcessorConstants.ERROR_INVALID_WRITER_MSG, topic.getLineNumber(), topic.getText()));
return false;
}
return true;
}
/**
* Checks to see if the tags are valid for a particular topic.
*
* @param specNode The topic or level the tags below to.
* @param tagNames A list of all the tags in their string form to be validate.
* @return True if the tags are valid otherwise false.
*/
private boolean validateTopicTags(final SpecNode specNode, final List<String> tagNames)
{
boolean valid = true;
if (!tagNames.isEmpty())
{
final List<RESTTagV1> tags = new ArrayList<RESTTagV1>();
for (final String tagName: tagNames)
{
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true);
return false;
}
// Get the tag from the database
final List<RESTTagV1> tagList = reader.getTagsByName(tagName);
// Check that it exists
if (tagList.size() == 1)
{
tags.add(tagList.get(0));
}
else if (tagList.size() == 0)
{
log.error(String.format(ProcessorConstants.ERROR_TAG_NONEXIST_MSG, specNode.getLineNumber(), tagName, specNode.getText()));
valid = false;
}
else
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TAG_DUPLICATED_MSG, specNode.getLineNumber(), specNode.getText()));
valid = false;
}
}
// Check that the mutex value entered is correct
final Map<RESTCategoryV1, List<RESTTagV1>> mapping = ProcessorUtilities.getCategoryMappingFromTagList(tags);
for (final RESTCategoryV1 cat: mapping.keySet())
{
// Check if the app should be shutdown
if (isShuttingDown.get())
{
shutdown.set(true);
return false;
}
// Check that only one tag has been set if the category is mutually exclusive
if (cat.getMutuallyExclusive() && mapping.get(cat).size() > 1)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TOO_MANY_CATS_MSG, specNode.getLineNumber(), cat.getName(), specNode.getText()));
valid = false;
}
// Check that the tag isn't a type or writer
if (cat.getId() == CSConstants.WRITER_CATEGORY_ID)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_WRITER_AS_TAG_MSG, specNode.getLineNumber(), specNode.getText()));
valid = false;
}
// Check that the tag isn't a topic type
if (cat.getId() == CSConstants.TYPE_CATEGORY_ID)
{
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TYPE_AS_TAG_MSG, specNode.getLineNumber(), specNode.getText()));
valid = false;
}
}
}
return valid;
}
}
|
Markdown
|
UTF-8
| 816 | 2.609375 | 3 |
[] |
no_license
|
# Article 85-5
1. Sans préjudice de ce qui est dit aux articles 77-6 et 85-3, les modifications apportées au présent décret par les articles 1er et 3 à 23 du décret n° 67-1252 du 22 décembre 1967 prennent effet à compter du 1er janvier 1968.
Dans tous les cas où les nouvelles dispositions du présent décret se réfèrent à un arrêté, les dispositions de l'arrêté en vigueur au 31 décembre 1967 demeurent applicables tant qu'un nouvel arrêté n'est pas intervenu.
2. Sous réserve des dispositions de l'article 85-3, paragraphe 2, alinéa 1, les modifications apportées aux articles 42-1, 44, 57 et 85-3 (par. 1, 3°) du présent décret par le décret n° 73-313 du 14 mars 1973 prennent effet le premier jour du deuxième mois suivant la publication de ce dernier texte au Journal officiel.
|
Java
|
UTF-8
| 1,530 | 2.65625 | 3 |
[] |
no_license
|
package org.adrianwalker.callablefrom;
import org.adrianwalker.callablefrom.test.TestCaller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
public final class CallableFromTest implements TestCaller {
@Test
public void testCallableFromTestCaller() {
CallableCaller cc = new CallableCaller(new Callable());
cc.doStuff();
}
@Test
public void testCallableFromError() {
ErrorCaller er = new ErrorCaller(new CallableCaller(new Callable()));
try {
er.doStuff();
fail("Expected CallableFromError to be thrown");
} catch (final CallableFromError cfe) {
String expectedMessage
= "org.adrianwalker.callablefrom.Callable "
+ "is not callable from "
+ "org.adrianwalker.callablefrom.ErrorCaller";
String actualMessage = cfe.getMessage();
assertEquals(expectedMessage, actualMessage);
}
}
@Test
public void testNotCallableFromSubclass() {
CallableCallerSubclass ccs = new CallableCallerSubclass(new Callable());
try {
ccs.doStuff();
fail("Expected CallableFromError to be thrown");
} catch (final CallableFromError cfe) {
String expectedMessage
= "org.adrianwalker.callablefrom.Callable "
+ "is not callable from "
+ "org.adrianwalker.callablefrom.CallableCallerSubclass";
String actualMessage = cfe.getMessage();
assertEquals(expectedMessage, actualMessage);
}
}
}
|
Markdown
|
UTF-8
| 3,122 | 3.703125 | 4 |
[] |
no_license
|
# Media
A.1. Can you implement the sing() method for the bird? a. How did you unit test it? b. How did you optimize the code for maintainability? (Ask yourself the same question for all following exercises)
<i>Assumption: </i>
All birds can sing. This is a default characteristic of all birds.
A.2. Now, we have 2 special kinds of birds: the Duck and the Chicken... Can you implement them to make their own special sound? a. A duck says: “Quack, quack” b. A duck can swim c. A chicken says: “Cluck, cluck” d. A chicken cannot fly (assumption: its wings are clipped but ignore that)
<i>Assumption:</i> Chicken can't fly.
A.3. Now how would you model a rooster? a. A rooster says: “Cock-a-doodle-doo” b. How is the rooster related to the chicken? c. Can you think of other ways to model a rooster without using inheritance?
<i>Assumption: </i>Rooster is a bird and its type of chicken which makes a different noise.</i>
A.4. Can you model a parrot? We are specifically interested in three parrots, one that lived in a house with dogs one in a house with cats, the other lived on a farm next to the rooster. a. A parrot living with dogs says: “Woof, woof” b. A parrot living with cats says: “Meow” c. A parrot living near the rooster says: “Cock-a-doodle-doo” d. How do you keep the parrot maintainable? What if we need another parrot lives near a Duck? Or near a phone that rings frequently
<b>I have used a bridge pattern here, so we jut need to implement two class ParrotWithPhone or ParrotWithDuck to support both the sounds.</b>
B.1. In addition to the birds, can you model a fish?
a. Fishes don’t sing
b. Fishes don’t walk
c. Fishes can swim
B.2. Can you specialize the fish as a Shark and as a Clownfish? a. Sharks are large and grey b. Clownfish are small and colourful (orange) c. Clownfish make jokes d. Sharks eat other fish
B.3. 3. Dolphins are not exactly fish, yet, they are good swimmers a. Can you model a dolphin that swims without inheriting from a fish class? b. How do you avoid duplicating code or introducing unneeded overhead?
<i>Duplicate codes are already removed by design.</i>
D.1. Can you model a butterfly? a. A butterfly can fly b. A butterfly does not make a sound
E. Suppose you have an array of animals, e.g.
Animal[] animals = new Animal[]{ new Bird(), new Duck(), new Chicken(), new Rooster(), new Parrot(), new Fish(), new Shark(), new Clownfish(), new Dolhpin(), new Frog(), new Dog(), new Butterfly(), new Cat() };
Note: The above instantiation may be different if you chose to set up your object model differently… (hopefully you did)
1. Can you share the code to count: a. how many of these animals can fly? b. how many of these animals can walk? c. how many of these animals can sing? d. how many of these animals can swim?
<i>Assumptions</i>
1. All birds can't fly.
2. All birds can sing and walk.
3. All fish can swim and duck.
4. All butterfly can fly.
5. Frog can only jump.
|
Markdown
|
UTF-8
| 5,245 | 3 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Overview of the SynthDet Unity Project
This project utilizes the Unity [Perception](https://github.com/Unity-Technologies/com.unity.perception) package for randomizing the environment and generating ground-truth on each frame.
## Ground truth generation
To generate ground truth, the [Perception Camera](https://github.com/Unity-Technologies/com.unity.perception/blob/master/com.unity.perception/Documentation~/PerceptionCamera.md) is used, which is a pre-built component available in the Perception package. This special type of camera accepts a list of Labelers, each of which is capable of generating a specific type of ground truth. To speed up your workflow, the Perception package comes with several common labelers for object-detection and human keypoint labeling tasks; however, if you are comfortable with code, you can also add your own custom Labelers. SynthDet uses Labelers for 2D bounding boxes, object count and pixel count information, semantic segmentation, and reporting of metadata on various randomized parameters.
To see the list of Labelers attached to your Perception Camera, select the `Perception Camera` GameObject in the Scene ***Hierarchy*** window.
## Domain randomization
The Perception package comes with a [randomization](https://github.com/Unity-Technologies/com.unity.perception/blob/master/com.unity.perception/Documentation~/Randomization/index.md) toolset that makes it easy to coordinate simulations in which environments are continually randomized. Simulations are coordinated by Scenarios, which run a set of Randomizers in a deterministic order. Each Randomizer is then tasked with randomizing a certain aspect of the environment. Randomizers are flexible and extensible, making it easy for users to create their own custom randomization strategies.
To check out the list of Randomizers used in the SynthDet project, select the `Scenario` GameObject inside the `SynthDet` Scene. The **Inspector** window will then look like this:
<p align="center">
<img src="images/randomizers_collapsed.png" width="400"/>
</p>
Besides the list of Randomizers, you also see several properties for the Scenario. The `Random Seed` set here is the seed used for all randomizations that happen throughout the Scenario, in all Randomizers. If you only use the provided randomization toolset for generating random values throughout your project's C# code, you are guaranteed to have identical outputs between simulations that use the same exact Randomizers and `Random Seed` value. Each Scenario comprises a number of Iterations and each Iteration can be run for a number of frames. Randomizers can be scripted to perform operations at different times, including when the simulation first starts, the start or end of each Iteration, or on each frame of each Iteration. `Total Iterations` and `Frames Per Iteration` control how many Iterations the Scenario performs and how many frames each Iteration runs for.
In the above screenshot, the UI for all Randomizers is collapsed. Most Randomizers come with properties and parameters that you can modify. To modify a Randomizer, you just need to expand its UI by clicking the small triangle icon to the left of its name, like below:
<p align="center">
<img src="images/foreground_randomizer.png" width="400"/>
</p>
Here is what each Randomizer in SynthDet does:
* **BackgroundObjectPlacementRandomizer**
* The background consists of a large number of primitive shapes with randomized positions, rotations, textures, and hue offsets. The purpose of this background is to act as distraction for the machine learning model. This Randomizer has the task of instantiating and positioning these primitive shapes.
* **ForegroundObjectPlacementRandomizer**
* This Randomizer instantiates and positions the foreground objects. These are the grocery objects, for which we generate bounding boxes.
* **ForegroundScaleRandomizer**
* Assigns random scales to each of the foreground (grocery) objects.
* **ForegroundOccluderPlacementRandomizer**
* Another distraction for the model comes in the form of shapes that are placed between the camera and the objects that are to be detected (the grocery objects). These occluders are randomized in position, scale, texture, and hue offset. This Randomizer is tasked with instantiating and positioning them.
* **ForegroundOccluderScaleRandomizer**
* Randomizes the scale of the foreground occluder objects.
* **TextureRandomizer**
* Randomizes the textures of the background shapes and foreground occluder objects.
* **HueOffsetRandomizer**
* Randomizes the hue offset of the background shapes and foreground occluder objects.
* **RotationRandomizer**
* The background shapes, foreground occluder objects, and one of the four directional lights present in the Scene are rotated randomly using this Randomizer.
* **UnifiedRotationRandomizer**
* This Randomizer assigns a random rotation to all foreground (grocery) objects. The difference between this and `RotationRandomizer` is that here, the same rotation is applied to all target objects.
* **VolumeRandomizer**
* Randomizes the contrast, saturation, and blur of RGB output images.
* **LightRandomizer**
* Randomizes the Directional Light object in the Scene.
|
PHP
|
UTF-8
| 652 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin_master";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
if(!empty($id))
{
// Check record exists
// $checkRecord = mysqli_query($con,"SELECT * FROM users WHERE id=".$id);
// $totalrows = mysqli_num_rows($checkRecord);
// if($totalrows > 0){
// Delete record
$query = "DELETE FROM users WHERE id=".$id;
mysqli_query($conn,$query);
echo 1;
// }
}
else
{
echo 0;
}
exit;
|
Java
|
UTF-8
| 5,337 | 1.882813 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.yugandhar.mdm.corecomponentref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.yugandhar.common.exception.YugandharCommonException;
import com.yugandhar.common.transobj.TxnTransferObj;
import com.yugandhar.mdm.component.util.ReferenceTableHelper;
import com.yugandhar.mdm.extern.dobj.RefAddressTypeDO;
import com.yugandhar.common.util.CommonValidationUtil;
@Scope(value = "prototype")
@Component
public class RefAddressTypeComponentRule {
@Autowired
protected CommonValidationUtil commonValidationUtil;
@Autowired
ReferenceTableHelper referenceTableHelper;
/**
*Pre execute persist validation method for RefAddressTypeComp to validate mandatory attributes etc
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void prevalidateRefAddressTypeCompPersit(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute merge validation method for RefAddressTypeComp to validate mandatory attributes etc
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void PrevalidateRefAddressTypeCompMerge(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute findbyId validation method for RefAddressTypeComp to validate mandatory attributes etc
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void prevalidateRefAddressTypeCompFindById(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute findByBusinessKey validation method for RefAddressTypeComp to validate mandatory attributes etc
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void preValidateRefAddressTypefindByBusinessKey(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for persist in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void preExecuteRefAddressTypeCompPersist(RefAddressTypeDO reqRefAddressTypeDO,
TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for persist in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void postExecuteRefAddressTypeCompPersit(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for merge in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void preExecuteRefAddressTypeCompMerge(RefAddressTypeDO reqRefAddressTypeDO,
RefAddressTypeDO dbimageRefAddressTypeDO, TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for merge in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void postExecuteRefAddressTypeCompMerge(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for findbyId in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void postExecuteRefAddressTypeCompFindById(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for findByBusinessKey in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void preExecuteRefAddressTypefindByBusinessKey(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
/**
*Pre execute rule for findByBusinessKey in RefAddressTypeComp
* This method is modularized in respective rule class
* Use Aspect Oriented Programming (AOP) based Yugandhar Rule to override / extend the default OOTB validation
*@throws YugandharCommonException
*/
public void postExecuteRefAddressTypefindByBusinessKey(TxnTransferObj txnTransferObj) {
// TODO Auto-generated method stub
}
}
|
Markdown
|
UTF-8
| 1,107 | 3.015625 | 3 |
[] |
no_license
|
# Liri Node App
This is a CLI application that takes in commands, and uses APIs from Twitter, Spotify, and OMDB.
## Use
To use this application, you must clone the repo, then open the directory in your command line. There are several commands you can then enter:
* `node liri.js movie-this "Movie Title"` replacing "Movie Title" with whatever movie you want will return information on that movie, such as release date, cast, Rotten Tomatoes rating, and more
* `node liri.js spotify-this-song "Song Title"` replacing "Song Title" with whatever song you want will return the artist, the song, a Spotify link, and the album
* `node liri.js my-tweets` will return your tweets to the console
* `node liri.js do-what-it-says` will execute whatever is in the random.txt file
## Built With
* [File-System](https://www.npmjs.com/package/file-system "File-System NPM")
* Node
* [Node Spotify API](https://www.npmjs.com/package/node-spotify-api "Node-Spotify-Api")
* [Request](https://www.npmjs.com/package/request "Request NPM")
* [Twitter](https://www.npmjs.com/package/twitter "Twitter NPM")
## Developers
* Wenona Frankwich
|
PHP
|
UTF-8
| 1,401 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\Auth\ManagerRequest;
class ManagerRegisterController extends Controller
{
/**
* Show create Page
*
* @param Request $request
* @return view
*/
public function create(Request $request)
{
if (!$request->hasValidSignature()) {
abort(401, '该链接已经失效或验证码无效!详情请咨询管理员');
}
// 获取用户信息
$manager = User::select('email', 'id')
->findOrFail($request->id);
$url = URL::signedRoute(
'manager.inti.password',
['manager' => $manager]
);
return view('auth.auth', [
'title' => '注册',
'manager' => $manager,
'url' => $url
]);
}
/**
* Update Manager password
*
* @param ManagerRequest $request
* @return response
*/
public function update(ManagerRequest $request, User $manager)
{
$data = $request->validated();
$data['password'] = Hash::make($data['password']);
$data['email_verified_at'] = time();
$manager->update($data);
return response()->success('');
}
}
|
C#
|
UTF-8
| 1,825 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CommandLine;
using CommandLine.Text;
using OverwatchMatchHistoryTracker.Options.MatchOption;
#endregion
namespace OverwatchMatchHistoryTracker.Options.AverageOption
{
[Verb(nameof(Average), HelpText = _HELP_TEXT)]
public class Average : CommandRoleOption
{
private const string _HELP_TEXT = "Get average historic SR.";
[Usage]
public static IEnumerable<Example> Examples { get; } = new List<Example>
{
new Example(_HELP_TEXT, new Average
{
Name = "ShadowDragon",
Role = Role.DPS
}),
};
[Option('c', "change", Required = false, HelpText = "Returns average SR change instead.")]
public bool Change { get; set; }
[Value(2, MetaName = nameof(Outcome), Required = false, Default = Outcome.Overall,
HelpText = "Constrains the collation to only matches with given outcome (win / loss / draw / overall).")]
public Outcome Outcome { get; set; }
public override async ValueTask Process(MatchesContext matchesContext)
{
IAsyncEnumerable<(Match Match, int SR)> matches = matchesContext.GetMatchesByOutcomeAsync(Role, Outcome);
IAsyncEnumerable<int> srs = Change
? matches.Where(result => result.SR != 0).Select(result => Math.Abs(result.SR))
: matches.Select(result => result.Match.SR);
double average = await srs.DefaultIfEmpty().AverageAsync();
Console.WriteLine(average == 0d
? $"No or not enough historic SR data for outcome '{Outcome}'."
: $"Average historic SR for outcome '{Outcome}': {average:0}");
}
}
}
|
Ruby
|
UTF-8
| 458 | 3.8125 | 4 |
[] |
no_license
|
class Selection
class << self
def sort(array)
length = array.length - 1
for i in 0..length
min = i
for j in (i + 1)..length
min = j if (array[j] < array[min])
end
temp = array[i]
array[i] = array[min]
array[min] = temp
end
show(array)
end
def show(array)
array.join(" ")
end
end
end
array = (1..100).to_a.sample(100)
puts Selection.sort(array)
|
C++
|
ISO-8859-1
| 4,762 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
enum Color { Negro, Blanco };
inline bool par( int n )
{
return n % 2 == 0;
}
// IMPORTANTE: Si se llama a esta funcion con color negro, el valor inicial de columna tiene que ser 1, sino 0.
long ubicarAlfilesEnColor( int n, int k, Color c, vector< bool >& DiagonalSubida, vector< bool >& DiagonalBajada, int filaInicial, int columnaInicial )
{
// caso k == 0
if( k == 0 )
{
return 1;
}
// caso k > 1
long soluciones = 0;
for( int fila = filaInicial; fila < n; fila++ )
{
for( int columna = columnaInicial; columna < n; columna += 2 )
// voy sumandole de a 2 a j, para mantenerme en el mismo color
{
// Si esa diagonal esta libre, es decir, si ubicando el la fila y columna no se ataca con otro
if ( !DiagonalSubida[ fila + columna ] && !DiagonalBajada[ fila - columna + n - 1 ] )
{
// Ubico un alfil en la posicion fila columna
DiagonalSubida[ fila + columna ] = true;
DiagonalBajada[ fila - columna + n - 1 ] = true;
soluciones += ubicarAlfilesEnColor( n, k - 1, c, DiagonalSubida, DiagonalBajada, fila, columna + 2 );
DiagonalSubida[ fila + columna ] = false;
DiagonalBajada[ fila - columna + n - 1 ] = false;
}
}
// esto es necesario porque en el tablero las filas pares empiezan en blanco
// y las impares en negro
if( ( par( fila + 1 ) && c == Negro ) || ( !par( fila + 1 ) && c == Blanco ) )
{
columnaInicial = 1;
}
else
{
columnaInicial = 0;
}
}
return soluciones;
}
long solucionesUnColor( int n, int alfiles, Color color )
{
vector< bool > DiagonalSubida( 2 * n - 1, false );
vector< bool > DiagonalBajada( 2 * n - 1, false );
// para nosotros, los tableros de ajedrez comienzan con el color blanco en el casillero 0,0
// y en la proxima fila, los colores se invierten, es decir, si en una fila comienza el negro,
// en la proxima comenzara el blanco, y viceversa
if( color == Blanco )
{
return ubicarAlfilesEnColor( n, alfiles, color, DiagonalSubida, DiagonalBajada, 0, 0 );
}
else
{
return ubicarAlfilesEnColor( n, alfiles, color, DiagonalSubida, DiagonalBajada, 0, 1 );
}
}
long cantSoluciones( int n, int k )
{
// si k > 2 * ( n - 1 ) entonces la cantidad de formas en las que se pueden ubicar
// k alfiles en un tablero de n*n es 0, pues en todo tablero de n*n hay
// 2 * ( 2 * n - 1 ) diagonales y cada alfil ocupa dos diagonales, por lo tanto
// luego de ubicar el alfil nmero 2 * ( n - 1 ) no hay forma de posicionar
// el siguiente alfil sin que se ataque con otro.
if( k > 2 * ( n - 1 ) && n > 1 )
{
return 0;
}
long cantSoluciones = 0;
// si n es par, el tablero tiene igual cantidad de casilleros negros que blancos, por lo tanto puedo calcular
// la cantidad de soluciones para un solo color, y estar seguro que sera la misma cantidad de soluciones que
// para el otro color
if( par( n ) )
{
vector< long > solucionParcial( k + 1, 0 );
// pueden haber desde 0 hasta k alfiles en un solo color, por lo tanto vamos ubicando
// 0, 1, ..., k alfiles para un solo color y luego hacemos la sumatoria
for (int i = 0; i <= k && i < n; i++ )
{
solucionParcial[ i ] = solucionesUnColor( n, i, Negro );
}
for( int i = 0; i <= k; i++ )
{
cantSoluciones = cantSoluciones + ( solucionParcial[ i ] * solucionParcial[ k - i ] );
}
}
// si n es impar, la cantidad de casilleros blancos difiere en uno con la cantidad de casilleros negros.
else
{
vector< long > solucionParcialBlancas( k + 1, 0 );
vector< long > solucionParcialNegras( k + 1, 0 );
for ( int i = 0; i <= k && i <= n; i++ )
{
solucionParcialNegras[ i ] = solucionesUnColor( n, i, Negro );
solucionParcialBlancas[ i ] = solucionesUnColor( n, i, Blanco );
}
for ( int i = 0; i <= k; i++ )
{
cantSoluciones = cantSoluciones + ( solucionParcialNegras[ i ] * solucionParcialBlancas[ k - i ] );
}
}
return cantSoluciones;
}
int main(int argc, char* argv[])
{
int n, k;
scanf( "%i %i", &n, &k );
while ( n != 0 || k != 0 ){
cout << cantSoluciones( n, k ) << endl;
scanf( "%i %i", &n, &k );
}
return 0;
}
|
Markdown
|
UTF-8
| 1,078 | 3.5625 | 4 |
[
"ISC"
] |
permissive
|
# Banana Bread
* **Source**: http://www.simplyrecipes.com/recipes/banana_bread/
* **Prep time**: 10 minutes
* **Cook time**: 55 minutes
* **Yield**: 1 loaf
## Ingredients
* 2-3 very ripe bananas, peeled
* ⅓ cup melted butter
* ¾ cup sugar (½ cup if you would like it less sweet, 1 cup if more sweet)
* 1 egg, beaten
* 1 teaspoon vanilla extract
* 1 teaspoon baking soda
* Pinch of salt
* 1½ cups of all-purpose flour
## Directions
1. Preheat the oven to 350°F (175°C), and butter a 4x8-inch loaf pan.
2. In a mixing bowl, mash the ripe bananas with a fork until completely smooth. Stir the melted butter into the mashed bananas.
3. Mix in the baking soda and salt. Stir in the sugar, beaten egg, and vanilla extract. Mix in the flour.
4. Pour the batter into your prepared loaf pan. Bake for 50 minutes to 1 hour at 350°F (175°C), or until a tester inserted into the center comes out clean.
5. Remove from oven and cool completely on a rack. Remove the banana bread from the pan. Slice and serve. (A bread knife helps to make slices that aren't crumbly.)
|
Java
|
UTF-8
| 1,932 | 2.578125 | 3 |
[] |
no_license
|
package com.jy.dataaccess.cache.annotations.interceptor;
import java.lang.reflect.Method;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import com.jy.dataaccess.cache.CachingModel;
/**
*
* @author wdong
*
*/
public class CachingModelAdvisor extends StaticMethodMatcherPointcutAdvisor {
private static final long serialVersionUID = -8002757290679200365L;
/**
* Retrieves instances of <code>{@link CachingModel}</code> for
* intercepted methods.
*/
private CachingModelInfo cachingModelInfo;
/**
* Construct a <code>CachingModelSourceAdvisor</code>.
*
* @param interceptor
* Advice that caches the returned value of intercepted methods.
* @throws AopConfigException
* if the <code>CachingAttributeSource</code> of
* <code>cacheInterceptor</code> is <code>null</code>.
*/
public CachingModelAdvisor(NameMatchCachingInterceptor interceptor) {
super(interceptor);
CachingModelInfo tempInfo = interceptor.getCachingModelInfo();
if (tempInfo == null) {
throw new AopConfigException("<" + interceptor.getClass().getName()
+ "> has no <" + CachingModelInfo.class.getName()
+ "> configured");
}
cachingModelInfo = tempInfo;
}
/**
* Returns <code>true</code> if the return value of the intercepted method
* should be cached.
*
* @param method
* the intercepted method to verify.
* @param targetClass
* the class declaring the method.
* @return <code>true</code> if the return value of the intercepted method
* should be cached.
*/
public final boolean matches(Method method, Class<?> targetClass) {
CachingModel model = cachingModelInfo.model(method, targetClass);
boolean matches = (model != null);
return matches;
}
}
|
PHP
|
UTF-8
| 852 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Http\Controllers\Admin\ResellerController;
class WeeklyDeduction extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'weekly:deduction';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Weekly 250 Rs Deduction';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$reseller = new ResellerController;
$reseller->weekly_deduction();
$this->info('Weekly Deduction');
}
}
|
Shell
|
UTF-8
| 2,717 | 2.921875 | 3 |
[] |
no_license
|
#!/bin/sh
echo "Test 1"
set -e
echo "Test 2"
WORKSPACE=${WORKSPACE:=`pwd`}
DERIVED_DATA=${DERIVED_DATA:=`mktemp -qd $WORKSPACE/DerivedData.XXXXX`}
echo "WORKSPACE: $WORKSPACE"
echo "DERIVED_DATA: $DERIVED_DATA"
echo "Test 3"
function cleanup {
echo "Cleaning up..."
rm -fr $DERIVED_DATA
}
echo "Test 4"
trap cleanup EXIT
cd $WORKSPACE
echo "Test 5"
echo "Rebuilding projects..."; sleep 1
xcodebuild -scheme PolarBleSdk -configuration Release -sdk `xcrun --sdk iphoneos --show-sdk-path` -derivedDataPath $DERIVED_DATA ONLY_ACTIVE_ARCH=NO ARCHS="armv7 arm64" "OTHER_SWIFT_FLAGS=-DDISABLE_TEAM_PRO_DECRYPTION" CODE_SIGN_IDENTITY='' "OTHER_CFLAGS=-fembed-bitcode"
xcodebuild -scheme PolarBleSdk -configuration Release -sdk `xcrun --sdk iphonesimulator --show-sdk-path` -derivedDataPath $DERIVED_DATA ONLY_ACTIVE_ARCH=NO ARCHS="i386 x86_64" "OTHER_SWIFT_FLAGS=-DDISABLE_TEAM_PRO_DECRYPTION" CODE_SIGN_IDENTITY='' "OTHER_CFLAGS=-fembed-bitcode"
echo "Creating universal ios-communications..."
cd $DERIVED_DATA
lipo -create -output ../3rd_party_sdk/PolarBleSdk.framework/PolarBleSdk Build/Products/Release-iphoneos/PolarBleSdk.framework/PolarBleSdk Build/Products/Release-iphonesimulator/PolarBleSdk.framework/PolarBleSdk
echo "Copying swift modules..."
cp Build/Products/Release-iphoneos/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule/*.swiftmodule ../3rd_party_sdk/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule
cp Build/Products/Release-iphoneos/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule/*.swiftdoc ../3rd_party_sdk/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule
cp Build/Products/Release-iphonesimulator/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule/*.swiftmodule ../3rd_party_sdk/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule
cp Build/Products/Release-iphonesimulator/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule/*.swiftdoc ../3rd_party_sdk/PolarBleSdk.framework/Modules/PolarBleSdk.swiftmodule
cp Build/Products/Release-iphoneos/PolarBleSdk.framework/Modules/module.modulemap ../3rd_party_sdk/PolarBleSdk.framework/Modules
# copy info list
cp Build/Products/Release-iphoneos/PolarBleSdk.framework/info.plist ../3rd_party_sdk/PolarBleSdk.framework/info.plist
cp -r Build/Products/Release-iphoneos/PolarBleSdk.framework/Headers ../3rd_party_sdk/PolarBleSdk.framework
sed -i -- 's/#import <PolarProtobuf.h>//' ../3rd_party_sdk/PolarBleSdk.framework/Headers/PolarBleSdk.h
rm ../3rd_party_sdk/PolarBleSdk.framework/Headers/PolarBleSdk.h--
sudo codesign --force --sign - ../3rd_party_sdk/PolarBleSdk.framework
sudo codesign --force --sign - ../3rd_party_sdk/PolarBleSdk.framework/PolarBleSdk
echo "=== release build ready ==="
cd ../3rd_party_sdk
|
Shell
|
UTF-8
| 242 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
source ${DIR}/delta_configs/env.delta
echo
docker-compose up -d
echo
echo "Sleep an additional 120s to wait for docker containers to start"
sleep 120
echo "..."
|
Python
|
UTF-8
| 1,801 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
import random
import typing
from typing import List
from hearthstone.agent import Agent, Action, generate_valid_actions, BuyAction, EndPhaseAction, SummonAction, \
TavernUpgradeAction
if typing.TYPE_CHECKING:
from hearthstone.cards import Card
from hearthstone.player import Player
class SupremacyBot(Agent):
authors = ["Jeremy Salwen"]
def __init__(self, monster_type: str, upgrade: bool, seed: int):
self.local_random = random.Random(seed)
self.monster_type = monster_type
self.upgrade = upgrade
def rearrange_cards(self, player: 'Player') -> List['Card']:
card_list = player.in_play.copy()
self.local_random.shuffle(card_list)
return card_list
def buy_phase_action(self, player: 'Player') -> Action:
all_actions = list(generate_valid_actions(player))
if self.upgrade:
upgrade_actions = [action for action in all_actions if type(action) is TavernUpgradeAction]
if upgrade_actions:
return upgrade_actions[0]
summon_actions = [action for action in all_actions if type(action) is SummonAction]
if summon_actions:
return summon_actions[0]
buy_actions = [action for action in all_actions if type(action) is BuyAction and player.store[action.index].monster_type == self.monster_type]
buy_actions = sorted(buy_actions, key=lambda buy_action: player.store[buy_action.index].tier, reverse=True)
if buy_actions:
return buy_actions[0]
return EndPhaseAction(False)
def discover_choice_action(self, player: 'Player') -> 'Card':
discover_cards = player.discovered_cards
discover_cards = sorted(discover_cards, key=lambda card: card.tier, reverse=True)
return discover_cards[0]
|
Python
|
UTF-8
| 9,118 | 2.734375 | 3 |
[] |
no_license
|
import tensorflow as tf
import numpy as np
import cv2
weights_small='weights/YOLO_small.ckpt'
layer_names = ['conv1s', 'max_pool1', 'conv2', 'max_pool2',
'conv3_1', 'conv3_2', 'conv3_3', 'conv3_4', 'max_pool3',
'conv4_1', 'conv4_2', 'conv4_3', 'conv4_4', 'conv4_5', 'conv4_6', 'conv4_7', 'conv4_8', 'conv4_9', 'conv4_10', 'max_pool4',
'conv5_1', 'conv5_2', 'conv5_3', 'conv5_4', 'conv5_5', 'conv5_6s',
'conv6_1', 'conv6_2',
'transform',
'full_7', 'full_8', 'full_9']
# 定义基本的网络类
class Net:
# mode
# 0 => 舰船检测的完整模式;1 => 只有全连接层的模式; 2=> 物体检测的模式; 3 => 只有卷积层的模式
def __init__ ( self, mode, weight_file, layer_names):
print('创建网络类')
self.alpha = 0.1
self.mode = mode
self.layer_names = layer_names
# 从ckpt文件里面把权重啥的都给读出来
weights = self.read_weights(weight_file,mode)
# 先定义输入输出
if mode == 0: # 舰船检测的完整模式
self.input = tf.placeholder('float32', [None, 448, 448, 3])
self.output = tf.placeholder('float32', [None, 7*7*5])
elif mode == 1: # 只有全连接层
self.input = tf.placeholder('float32', [None, 7*7*1024])
self.output = tf.placeholder('float32', [None, 7*7*5])
elif mode == 2: # 完整的物体检测模式
self.input = tf.placeholder('float32', [None, 448, 448, 3])
self.output = tf.placeholder('float32', [None, 7*7*30])
elif mode == 3: # 只要卷积层
self.input = tf.placeholder('float32', [None, 448, 448, 3])
self.output = tf.placeholder('float32', [None, 7*7*1024])
# 把网络结构搭起来
self.build(layer_names, weights)
# 创建session
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
self.load_weights(weights)
def build(self, layer_names, weights):
self.temp = self.input
if self.mode == 0:
i = 0
# 定义网络的基本结构
for layer_name in layer_names:
if layer_name[0] == 'c':
if layer_name[-1] == 's':
self.temp = self.conv_layer(layer_name[:-1], self.temp, weights[i].shape, 2)
print('这是一个卷积层 => '+str(layer_name) + ' => 尺寸为' + str(weights[i].shape))
else:
self.temp = self.conv_layer(layer_name, self.temp, weights[i].shape, 1)
print('这是一个卷积层 => '+str(layer_name) + ' => 尺寸为' + str(weights[i].shape))
i = i + 2
elif layer_name[0] == 'm':
# self.pre = self.max_pool("max_pool_3", self.pre)
self.temp = self.max_pool(layer_name, self.temp)
print('这是一个池化层 => '+str(layer_name))
elif layer_name[0] == 'f':
if layer_name[-1] != '9':
self.temp = self.fc_layer(layer_name, self.temp, weights[i].shape, True, False)
print('这是一个全连接层 => '+str(layer_name)+ ' => 尺寸为' + str(weights[i].shape))
i = i + 2
else:
self.temp = self.fc_layer(layer_name, self.temp, weights[i].shape, True, False, False)
print(weights[i].shape)
print('这是一个全连接层 => '+str(layer_name)+ ' => 尺寸为' + str(weights[i].shape))
i = i + 2
elif layer_name[0] == 't':
self.temp= tf.transpose(self.temp,(0,3,1,2))
self.temp = tf.reshape(self.temp, [-1, 7*7*1024 ])
self.out = self.temp
elif self.mode == 1:
pass
elif self.mode == 2:
i = 0
# 定义网络的基本结构
for layer_name in layer_names:
''' print(weights[i].shape[0])
i = i + 1 '''
if layer_name[0] == 'c':
if layer_name[-1] == 's':
self.temp = self.conv_layer(layer_name[:-1], self.temp, weights[i].shape, 2)
print('这是一个卷积层 => '+str(layer_name) + ' => 尺寸为' + str(weights[i].shape))
else:
self.temp = self.conv_layer(layer_name, self.temp, weights[i].shape, 1)
print('这是一个卷积层 => '+str(layer_name) + ' => 尺寸为' + str(weights[i].shape))
i = i + 2
elif layer_name[0] == 'm':
# self.pre = self.max_pool("max_pool_3", self.pre)
self.temp = self.max_pool(layer_name, self.temp)
print('这是一个池化层 => '+str(layer_name))
elif layer_name[0] == 'f':
self.temp = self.fc_layer(layer_name, self.temp, [4096, 7*7*5], True, False)
print('这是一个全连接层 => '+str(layer_name)+ ' => 尺寸为' + str([4096,7*7*5]))
i = i + 2
elif layer_name[0] == 't':
self.temp= tf.transpose(self.temp,(0,3,1,2))
self.temp = tf.reshape(self.temp, [-1, 7*7*1024 ])
self.out = self.temp
elif self.mode == 3:
pass
def read_weights(self, weights_file, mode):
weights = []
# 加载权重文件
if mode != 1:
reader = tf.train.NewCheckpointReader(weights_file)
name = 'Variable'
weights.append(reader.get_tensor(name))
for i in range(1,54):
name = 'Variable_' + str(i)
weights.append(reader.get_tensor(name))
return weights
def load_weights(self, weights):
# 初始化权重
if self.mode == 0:
pass
elif self.mode == 1:
pass
elif self.mode == 2: # 物体检测模式
i = 0
for w in tf.get_collection('conv_weights'):
self.sess.run(w.assign(weights[i]))
i = i + 1
for w in tf.get_collection('fc_weights'):
self.sess.run(w.assign(weights[i]))
i = i + 1
elif self.mode == 3:
pass
def conv_layer(self, layer_name, inputs, filter, stride, trainable = False):
weight = tf.get_variable(name='w_'+layer_name, trainable = trainable, shape = filter, initializer = tf.contrib.layers.xavier_initializer() )
bias = tf.get_variable(name='b_'+layer_name, trainable = trainable, shape = [ filter[-1] ], initializer = tf.constant_initializer(0.0) )
tf.add_to_collection('conv_weights', weight)
tf.add_to_collection('conv_weights',bias)
inputs = tf.nn.conv2d(inputs, weight, [1,stride,stride,1], padding='SAME', name=layer_name+'_conv')
inputs = tf.nn.bias_add(inputs, bias, name=layer_name+'_bias')
inputs = tf.maximum(self.alpha*inputs, inputs, name=layer_name+'_leaky_relu')
return inputs
def max_pool(self, layer_name, inputs):
inputs = tf.nn.max_pool(inputs, [1,2,2,1], strides = [1,2,2,1], padding = 'SAME', name = layer_name)
return inputs
def fc_layer(self, layer_name, inputs, shape, is_read_weights, is_output, is_collect=True):
weight = tf.get_variable(name='w_'+layer_name, trainable = True, shape = shape, initializer = tf.contrib.layers.xavier_initializer() )
bias = tf.get_variable(name='b_'+layer_name, trainable = True, shape = [ shape[-1] ], initializer = tf.constant_initializer(0.0) )
if is_collect:
tf.add_to_collection('fc_weights', weight)
tf.add_to_collection('fc_weights',bias)
inputs = tf.add(tf.matmul(inputs, weight), bias)
if is_output:
inputs = tf.maximum(0.1*inputs,inputs,name=layer_name+'_leaky_relu')
return inputs
def loss(self):
pass
def run(self, input):
return self.sess.run(self.out,feed_dict={self.input:input})
def object_detection(self):
pass
def ship_detection(self):
pass
# 随便刷个更新而已
# 这玩意是准备数据集用的,因为谷歌那破玩意执行.py的步骤整不明白所以干脆放到一起来了
class Dataset:
def __init__(self):
pass
# index 索引数目
# num 返回的数据数目
# type 是随机还是按顺序返回
def get_placeholder(self, index, num, type):
pass
if __name__ == '__main__':
img = cv2.imread('test.jpg')
img = cv2.resize(img,(448,448),interpolation=cv2.INTER_CUBIC)
inputs = np.zeros((1,448,448,3),dtype='float32')
inputs[0] = (img/255.0)*2.0-1.0
net = Net(0, weights_small, layer_names)
out = net.run(inputs)
print(out)
|
C++
|
UTF-8
| 1,628 | 2.859375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
#define INF 999999
#define NIL -1
using namespace std;
int V,d[100],pa[100];
bool S[100];
int ExtractMin()
{
int v,min_,loc_min;
min_=INF;
for(v=0;v<V;v++)
{
if((S[v] == false) && (d[v]<=min_))
{
min_=d[v];
loc_min=v;
//cout<<"FROM int ExtractMin()\n";
}
}
return loc_min;
}
int Relax(int u,int v,int w[100][100])
{
if(w[u][v] && d[v]>d[u]+w[u][v])
{
d[v]=d[u]+w[u][v];
pa[v]=u;
//cout<<"FROM int Relax()\n";
}
}
int Initialize_Single_Source(int s)
{
int v;
for(v=0;v<V;v++)
{
d[v]=INF;
pa[v]=NIL;
S[v]=false;
//cout<<"FROM int ISS\n";
}
d[s]=0;
}
int Dijkstra_m(int w[100][100],int s)
{
int u,i,v;
Initialize_Single_Source(s);
for(i=0;i<V-1;i++)
{
u=ExtractMin();
S[u]=true;
//cout<<"FROM int DIJ()\n";
for(v=0;v<V;v++)
{
//cout<<"FROM int DIJ----()\n";
Relax(u,v,w);
}
}
}
int Print_D()
{
int v;
for(v=0;v<V;v++)
{
cout<<v<<" "<<d[v]<<" "<<pa[v]<<"\n";
}
}
int main()
{
freopen("DijkstraIn.txt","r",stdin);
int i,j,u,w[100][100];
//cout<<"How many vertex:";
cin>>V;
cout<<"Vertex "<<"distance "<<"parents\n";
cout<<"\n";
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
{
cin>>w[i][j];
}
}
Dijkstra_m(w,0);
Print_D();
return 0;
}
|
C++
|
UTF-8
| 1,252 | 2.53125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int keys[] = {10, 12, 15, 20};
int freq[] = {4, 8, 5, 9};
int n = sizeof(keys)/sizeof(keys[0]);
int dp[n][n];
memset(dp, 0, sizeof(dp));
for(int gap=0; gap<n; gap++)
{
for(int i=0; i<n-gap; i++)
{
int j = gap+i;
if(gap ==0)
{
dp[i][j] = freq[i];
}
else if(gap == 1)
{
dp[i][j] = min((freq[i]+2*freq[j]), freq[j]+2*freq[i]);
}
else
{
int sum = 0;
int minimum = INT_MAX;
for(int k=i; k<=j; k++)
{
sum += freq[k];
}
for(int k=i; k<=j; k++)
{
int left = dp[i][k-1];
int right = dp[k+1][j];
if(left+right+sum < minimum)
minimum = left+right+sum;
}
dp[i][j] = minimum;
}
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout << dp[i][j] << " ";
}
cout << endl;
}
return 0;
}
|
Python
|
UTF-8
| 1,117 | 2.953125 | 3 |
[] |
no_license
|
import csv, json
from datetime import datetime
# Import the Canvas class
from canvasapi import Canvas
# Canvas API URL
API_URL = "https://yourinstitution.instructure.com/"
# Canvas API key
API_KEY = "Token Goes Here"
# Initialize a new Canvas object
canvas = Canvas(API_URL, API_KEY)
#Fill out this stuff below:
course_number = 'Canvas Course Number Goes Here'
publish = True
#Don't change the stuff below
course = canvas.get_course(course_number)
csvdates = 'dates.csv'
with open(csvdates, 'r') as csvFile:
csvReader = csv.reader(csvFile, delimiter = ',')
next(csvReader) #skips the header row
for row in csvReader:
new_assignment = course.create_assignment({
'name': row[0],
'submission_types': ['online_upload'],
'points_possible': row[1],
'due_at': datetime.strptime(row[2], '%m/%d/%Y %H %p'),
'unlock_at': datetime.strptime(row[3], '%m/%d/%Y %H %p'),
'lock_at': datetime.strptime(row[4], '%m/%d/%Y %H %p'),
'description': row[5],
'published': publish
})
print(row[0])
|
Go
|
UTF-8
| 601 | 3.328125 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fmt.Println("Lector")
new_text := []byte(os.Args[1])
// Escribe o "reescribe el archivo"
write := ioutil.WriteFile("file_test.txt", new_text, 0777)
showError(write)
fmt.Println("\nParametro recibido (Valor a insertar)")
fmt.Println(string(new_text))
file, errorFile := ioutil.ReadFile("file_test.txt")
showError(errorFile)
fmt.Println("\nArchivo en formato numerico")
fmt.Println(file)
fmt.Println("\nConvertirlo a string")
fmt.Println(string(file))
}
func showError(e error) {
if e != nil {
panic(e)
}
}
|
C++
|
UTF-8
| 1,501 | 2.859375 | 3 |
[] |
no_license
|
#pragma once
#include <stdint.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <Packet.h>
enum PacketProcessErrors
{
PACKET_PROCESSOR_ERROR_NONE, // everything is fine
PACKET_PROCESSOR_ERROR_KEY_IS_NULL, // we needed an encryption/decryption key but it was passed in as NULL
PACKET_PROCESSOR_ERROR_PACKET_TOO_SMALL, // an encrypted packet was discarded because it was too short to possibly contain valid data
PACKET_PROCESSOR_ERROR_WRITE_PACKET_FAILED, // failed to write packet
PACKET_PROCESSOR_ERROR_READ_PACKET_FAILED, // failed to read packet
PACKET_PROCESSOR_ERROR_ENCRYPT_FAILED, // encrypt packet failed
PACKET_PROCESSOR_ERROR_DECRYPT_FAILED, // decrypt packet failed
};
class PacketProcessor
{
public:
PacketProcessor(uint32_t protocolId, int maxPacketSize, void * context = NULL );
~PacketProcessor();
const uint8_t * WritePacket( Packet * packet, uint64_t sequence, int & packetBytes);
Packet * ReadPacket( const uint8_t * packetData, uint64_t & sequence, int packetBytes);
int GetMaxPacketSize() const { return m_maxPacketSize; }
int GetError() const { return m_error; }
private:
uint32_t m_protocolId;
int m_error;
int m_maxPacketSize;
int m_absoluteMaxPacketSize;
uint8_t * m_packetBuffer;
uint8_t * m_scratchBuffer;
void * m_context;
};
|
Java
|
UTF-8
| 3,207 | 1.742188 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018-2019 adorsys GmbH & Co KG
*
* 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 de.adorsys.psd2.consent.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.adorsys.psd2.consent.api.pis.CmsBasePaymentResponse;
import de.adorsys.psd2.consent.api.pis.CmsCommonPayment;
import de.adorsys.psd2.consent.api.pis.CmsCommonPaymentMapper;
import de.adorsys.psd2.consent.api.pis.PisPayment;
import de.adorsys.psd2.consent.service.mapper.CmsCorePaymentMapper;
import de.adorsys.psd2.mapper.Xs2aObjectMapper;
import de.adorsys.psd2.xs2a.core.profile.PaymentType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class CorePaymentsConvertService {
private final CmsCorePaymentMapper cmsCorePaymentMapper;
private final Xs2aObjectMapper xs2aObjectMapper;
private final PaymentMapperResolver paymentMapperResolver;
public byte[] buildPaymentData(List<PisPayment> pisPayments, PaymentType paymentType) {
switch (paymentType) {
case SINGLE:
return writeValueAsBytes(cmsCorePaymentMapper.mapToPaymentInitiationJson(pisPayments));
case BULK:
return writeValueAsBytes(cmsCorePaymentMapper.mapToBulkPaymentInitiationJson(pisPayments));
case PERIODIC:
return writeValueAsBytes(cmsCorePaymentMapper.mapToPeriodicPaymentInitiationJson(pisPayments));
default:
return new byte[0];
}
}
public CmsBasePaymentResponse expandCommonPaymentWithCorePayment(CmsCommonPayment cmsCommonPayment) {
CmsCommonPaymentMapper cmsCommonPaymentMapper = paymentMapperResolver.getCmsCommonPaymentMapper(cmsCommonPayment.getPaymentProduct());
switch (cmsCommonPayment.getPaymentType()) {
case SINGLE:
return cmsCommonPaymentMapper.mapToCmsSinglePayment(cmsCommonPayment);
case BULK:
return cmsCommonPaymentMapper.mapToCmsBulkPayment(cmsCommonPayment);
case PERIODIC:
return cmsCommonPaymentMapper.mapToCmsPeriodicPayment(cmsCommonPayment);
default:
return cmsCommonPayment;
}
}
private byte[] writeValueAsBytes(Object object) {
if (object == null) {
return new byte[0];
}
try {
return xs2aObjectMapper.writeValueAsBytes(object);
} catch (JsonProcessingException e) {
log.warn("Can't convert object to byte[] : {}", e.getMessage());
return new byte[0];
}
}
}
|
Rust
|
UTF-8
| 403 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
const STARTING_MISSILES: i32 = 8;
const READY_AMOUNT: i32 = 2;
fn main(){
let mut missiles: i32 = STARTING_MISSILES;
let ready: i32 = READY_AMOUNT;
println!("Firing {} of my {} missiles.....", ready, missiles);
missiles = missiles - ready;
println!("{} missiles left", ready);
let (mut x ,y):(i32, f64) = (6, 5.0);
let (mut q ,r) = (6, 5.0);
println!("{} {}", x, y);
}
|
C++
|
GB18030
| 1,957 | 2.921875 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
//
using namespace std;
int a[4][4];
int n,best=0;
void read()
{
char c;
getchar();
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
c=getchar();
if(c=='X')
{
a[i][j]=1;
}
else
{
a[i][j]=0;
}
}
getchar();
}
}
bool canplace(int m){
int r,c;
r=m/n;
c=m%n;
int row=r,col=c;
if(a[r][c]==1||a[r][c]==2){
return false;
}
while(c>=0&&a[row][c]==0){
c--;//жͬһǷ
if(c<0||(c>=0&&a[row][c]==1)){
while(r>=0&&a[r][col]==0){
r--;//жͬһǷ
/*˴ı߽ʼδã磺
* 3
...
.XX
.XX
ִ
*/
if(r<=0||(r>0&&a[r][col]==1)){
return true;
}
}
}
}
return false;
}
void check(){
int s=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j]==2){
s++;
}
}
}
best=s>best?s:best;
}
void out(){
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
void search(int m){
int r,c;
r=m/n;
c=m%n;
if(m==n*n){
check();//õн⣬
}else{
if(canplace(m)){
a[r][c]=2;//ű
search(m+1);
a[r][c]=0;
}else{
search(m+1);
}
}
}
int main()
{
while(cin>>n&&n){
best=0;
read();
//out();
search(0);
cout<<best<<endl;
}
return 0;
}
|
SQL
|
UTF-8
| 1,223 | 3.546875 | 4 |
[] |
no_license
|
DROP DATABASE IF EXISTS COMP3095;
CREATE DATABASE IF NOT EXISTS COMP3095;
USE COMP3095;
grant all on COMP3095.* to 'admin'@'localhost' identified by 'admin';
CREATE TABLE USERS
(
id int(11) AUTO_INCREMENT PRIMARY KEY,
employee_number varchar(255),
role varchar(20),
email varchar(255),
password varchar(20),
first_name varchar(255),
last_name varchar(255),
username varchar(20),
year_hired varchar(255),
department_id int(11)
);
CREATE TABLE DEPARTMENTS
(
id int(11) AUTO_INCREMENT PRIMARY KEY,
department_name varchar(255),
location varchar(255)
);
CREATE TABLE GROUPS
(
id int(11) AUTO_INCREMENT PRIMARY KEY,
department_id int(11),
group_name varchar(255)
);
CREATE TABLE USER_GROUP
(
id int(11) AUTO_INCREMENT PRIMARY KEY,
user_id int(11),
group_id int(11)
);
CREATE TABLE ATTENDANCE
(
id int(11) AUTO_INCREMENT PRIMARY KEY,
attendance_date varchar(255),
department_id int(11)
);
CREATE TABLE USER_ATTENDANCE
(
id int(11) AUTO_INCREMENT PRIMARY KEY,
attendance_id int(11),
user_id int(11)
);
INSERT INTO `USERS` (`first_name`, `last_name`, `email`, `role`, `username`, `password`) VALUES
("adminfirst", "adminlast", "admin@domain.ca", 1, "admin", "admin");
|
Java
|
UTF-8
| 1,616 | 2.71875 | 3 |
[] |
no_license
|
package com.shuhao.clean.apps.model.ext;
public class NumberField extends BaseField {
protected boolean allowBlank = true;
protected String blankText = "该项不能为空";
/*private Integer minValue;
private Integer maxValue;*/
private Double minValue;
private Double maxValue;
public String output() throws Exception {
StringBuffer buffer = new StringBuffer();
buffer.append("_"+this.name).append("Field = new Ext.form.NumberField({").append(enter);
buffer.append(this.fieldParams()).append(",").append(enter);
buffer.append("allowBlank : ").append(this.allowBlank);
if(this.allowBlank){
buffer.append(",").append(enter);
buffer.append("blankText : '").append(this.blankText).append("'");
}
if(isNotNull(this.minValue)){
buffer.append(",").append(enter);
buffer.append("minValue : ").append(this.minValue);
}
if(isNotNull(this.maxValue)){
buffer.append(",").append(enter);
buffer.append("maxValue : ").append(this.maxValue);
}
buffer.append(enter);
buffer.append("})").append(enter);
return buffer.toString();
}
public boolean isAllowBlank() {
return allowBlank;
}
public void setAllowBlank(boolean allowBlank) {
this.allowBlank = allowBlank;
}
public String getBlankText() {
return blankText;
}
public void setBlankText(String blankText) {
this.blankText = blankText;
}
public Double getMinValue() {
return minValue;
}
public void setMinValue(Double minValue) {
this.minValue = minValue;
}
public Double getMaxValue() {
return maxValue;
}
public void setMaxValue(Double maxValue) {
this.maxValue = maxValue;
}
}
|
C++
|
UTF-8
| 2,479 | 2.71875 | 3 |
[] |
no_license
|
#include<cstdio>
#include<cmath>
#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
void dfs(int u);
void scc(int u);
vector<int>edge[10010],revedge[10010];
struct data
{
int time,pos;
}timing[10010];
bool comp(data p, data q )
{
return p.time>q.time;
}
int num,ss;
int n,m;
int color[10010];
int cs=1;
int main()
{
int t;
cin>>t;
while(t--)
{
num=0,ss=0;
cin>>n>>m;
while(m--)
{
int u,v;
cin>>u>>v;
edge[u-1].push_back(v-1);
revedge[v-1].push_back(u-1);
}
for(int i=0;i<n;i++)
timing[i].pos=i;
memset(color,0,sizeof(color));
for(int i=0;i<n;i++)
{
if(!color[i])
{
// ss++;
color[i]=1;
dfs(i);
}
}
sort(timing,timing+n,comp);
/* for(int i=0; i<n-1; i++)
for(int j=i+1; j<n; j++)
{
data temp;
if(timing[i].time<timing[j].time)
{
temp=timing[i];
timing[i]=timing[j];
timing[j]=temp;
}
}*/
memset(color,0,sizeof(color));
for(int i=0;i<n;i++)
{
if(!color[timing[i].pos])
{
color[timing[i].pos]=1;
// ss++;
scc(timing[i].pos);
ss++;
}
}
printf("Case %d: %d\n",cs++,ss);
for(int i=0;i<=n;i++)
{
edge[i].clear();
revedge[i].clear();
}
}
return 0;
}
void dfs(int u)
{
++num;
for(int i=0;i<edge[u].size();i++)
{
int v=edge[u][i];
if(!color[v])
{
color[v]=1;
dfs(v);
}
}
timing[u].time=++num;
}
void scc(int u)
{
for(int i=0;i<edge[u].size();i++)
{
int v=edge[u][i];
if(!color[v])
{
color[v]=1;
scc(v);
}
}
}
|
Python
|
UTF-8
| 554 | 4.1875 | 4 |
[] |
no_license
|
#Implementation of iterator, lambda
class Spelling:
def __init__(self, word='Python'):
self.word = word
self.index = -1
def __iter__(self):
# some initialization
return self
def __next__(self):
self.index += 1
if self.index == len(self.word):
raise StopIteration
else:
return self.word[self.index]
def main():
for i in Spelling('Computer'):
print(i, end=' ')
l1 = [1,2,3,4,5,6,7,8,9]
l2 = list(filter(lambda q: q%2==1, l1))
print(l2)
l3 = list(filter(lambda q : q in "aeiou" , Spelling('elephant')))
print(l3)
main()
|
Java
|
UTF-8
| 337 | 2.53125 | 3 |
[] |
no_license
|
package _extends;
/**
* Created by USER on 24.02.2017, 2:14.
*
* @author Vadim Gamaliev <a href="mailto:gamaliev-vadim@yandex.com">gamaliev-vadim@yandex.com</a>
* @version 1.0
*/
public class Sub extends Parent {
public void test() {
System.out.println("Sub test");
}
@Override
public void test2() {
System.out.println("Sub test2");
}
}
|
Java
|
UTF-8
| 670 | 2.078125 | 2 |
[] |
no_license
|
package com.aurora.core.database.models.constants;
import static com.aurora.core.database.DbTableNames.CORE_STATES;
import lombok.Data;
import lombok.EqualsAndHashCode;
import androidx.room.Entity;
import androidx.room.Ignore;
import lombok.experimental.SuperBuilder;
import com.aurora.core.database.models.helpers.Rules;
@EqualsAndHashCode(callSuper = true)
@Data
@SuperBuilder
@Entity(tableName = CORE_STATES, inheritSuperIndices = true)
public class CoreStates extends Rules {
public CoreStates() {
super();
}
public CoreStates(String name) {
super(name);
}
public CoreStates(CoreStates source) {
new CoreStates(source.getName());
}
}
|
Java
|
UTF-8
| 614 | 2.265625 | 2 |
[] |
no_license
|
package main.Models.entities;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "stock_items")
public class StockItemsEntity {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
protected int id ;
@Column
private float quantity;
@Column float priceOfBuy;
@ManyToOne
protected StockEntity stock;
@ManyToOne
protected ArticleEntity article;
}
|
TypeScript
|
UTF-8
| 420 | 3.015625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
/**
* Represents a CBOR simple value (major type 7).
*/
export enum CborSimpleValue {
/**
* Represents the value 'false'.
*/
False = 20,
/**
* Represents the value 'true'.
*/
True = 21,
/**
* Represents the value 'null'.
*/
Null = 22,
/**
* Represents an undefined value, to be used by an encoder as a substitute for a data item with an encoding problem.
*/
Undefined = 23
}
|
C#
|
UTF-8
| 7,070 | 3.203125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main(string[] args)
{
Aula04 a = new Aula04();
Console.Write(a.GetImagem());
Thread.Sleep(100000);
//Aula04.Exercicio07semArray();
// game();
/*
var stopwatch = new Stopwatch();
stopwatch.Start();
List<int> lista = ProgramVar.executar(999999);
stopwatch.Stop();
Console.WriteLine($"Tempo passado: {stopwatch.Elapsed}");
lista.Sort();
for (int i =0; i< lista.Count; i++) {
Console.WriteLine(lista[i]);
}
Console.ReadKey();
*/
/*
String Concat
// string[] array = { "gian", "Felipe", "Euclides"};
try
{
var testeTemplate = @"Nome do usuario:{0}
Idade:{1}
Descricao:{2}";
var usuario = string.Format(testeTemplate
, Console.ReadLine()
, Console.ReadLine()
, Console.ReadLine());
}
catch (Exception e) {
Console.WriteLine(e);
}
*/
/*
Console.WriteLine("Informe o livro a ser consultado: ");
var numeroLivro = Console.ReadLine();
if (numeroLivro == "123456")
{
Console.WriteLine("Livro indisponivel");
}
else {
Console.WriteLine("Deseja alocar o livro? (1-sim, 2-nao)");
var resposta = Console.ReadLine();
if (resposta == "1")
{
Console.WriteLine("livro Alocado");
}
}*/
}
public static void cairBoneco() {
string c = "(+ -)";
string b = "\n |";
string p = "\n / \\ ";
bool aux = true;
while (true)
{
Console.Write(c + b + b + p);
if (aux) {
Console.ReadKey();
aux = false;
}
Thread.Sleep(100);
Console.Clear();
if (true)
{
c = "\n" + c;
b = "\n" + (b.Substring(1, b.Length - 1));
p = "\n" + (p.Substring(1, p.Length - 1));
}
Thread.Sleep(100);
}
}
public static void normalBoneco()
{
string c = "(+ -)";
string b = " |";
string mao = " /|\\";
string p = " / \\ ";
string p2 = " \\ \\";
bool anda = false;
while (true)
{
if (!anda)
{
Console.WriteLine(c);
Console.WriteLine(b);
Console.WriteLine(mao);
Console.WriteLine(b);
Console.WriteLine(p);
anda = true;
}
else {
Console.WriteLine(c);
Console.WriteLine(b);
Console.WriteLine(mao);
Console.WriteLine(b);
Console.WriteLine(p2);
anda = false;
}
Thread.Sleep(5);
Console.Clear();
c = " " + c;
b = " " + b;
p = " " + p;
mao = " " + mao;
p2 = " " + p2;
Thread.Sleep(5);
}
}
public static void cairBuracoNegro()
{
string c = "(+ -)";
string b = "\n |";
string p = "\n / \\ ";
bool aux = true;
int t = 0;
while (true)
{
Console.Write(c + b + b + p);
if (aux)
{
Console.ReadKey();
aux = false;
}
Thread.Sleep(200);
t++;
Console.Clear();
if (t > 6)
{
c = "\n" + c;
b = "\n" + b;
p = "\n" + p;
}
else {
c = "\n" + c;
b = "\n" + (b.Substring(1, b.Length - 1));
p = "\n" + (p.Substring(1, p.Length - 1));
}
Thread.Sleep(200);
}
}
public static void game() {
Thread t = new Thread(run);
Thread t2 = new Thread(run2);
t.Start();
t2.Start();
while (true) {
Console.WriteLine(p1);
Console.WriteLine(p2);
Thread.Sleep(10);
Console.Clear();
Thread.Sleep(10);
if (p1.Length == 40) {
Console.Clear();
p2 = null;
Console.WriteLine("Player 1 wins");
break;
}else
if (p2.Length == 40) {
Console.Clear();
p1 = null;
Console.WriteLine("Player 2 wins");
break;
}
}
t = null;
Thread.Sleep(100000);
}
static void run() {
while (true)
{
string v = Console.ReadKey().KeyChar.ToString();
if (v == "d") {
p1 = " " + p1;
} else if (v=="6") {
p1 = " P1";
}
}
}
static void run2()
{
while (true)
{
string v = Console.ReadKey().KeyChar.ToString();
if (v == "5")
{
p2 = " " + p2;
}
}
}
static string p1 = "P1";
static string p2 = "P2";
private static void Arvore(int nivel)
{
for (int linha = 1; linha <= nivel; linha++)
{
for (int coluna = 1; coluna <= linha; coluna++)
{
Console.Write ("*");
}
Console.WriteLine();
}
Console.WriteLine("||");
Console.WriteLine("||");
Console.WriteLine("||");
Console.WriteLine("||");
Console.WriteLine("||");
}
}
}
|
Markdown
|
UTF-8
| 409 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
### 不包含
设置```exclude```为, 将不高亮显示数值小于当前数值部分。
```javascript
class Demo extends React.Component {
render(){
return (
<div className="demo-slider">
<Slider defaultValue={35} exclude />
<Slider defaultValue={65} exclude disabled />
</div>
)
}
}
```
|
Java
|
UTF-8
| 1,642 | 2.5 | 2 |
[
"MIT"
] |
permissive
|
package com.netease.demo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by stone on 16/3/30.
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
public static final int HORIZONTAL = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL = LinearLayoutManager.VERTICAL;
private boolean reverse;
private int mOrientation;
public DividerItemDecoration(int orientation) {
setOrientation(orientation);
}
public DividerItemDecoration(int orientation, boolean reverse) {
mOrientation = orientation;
this.reverse = reverse;
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL && orientation != VERTICAL) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL) {
outRect.set(0, reverse ? 20 : 0, 0, reverse ? 0 : 20);
} else {
outRect.set(reverse ? 20 : 0, 0, reverse ? 0 : 20, 0);
}
}
}
|
C#
|
UTF-8
| 1,140 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CG2.Mathematics;
using CG2.Rendering;
using CG2.Shading;
namespace CG2.Modeling
{
public class Plane : Model
{
#region Properties
public Vector4 Origin;
public Vector4 Normal;
#endregion
#region Init
public Plane()
{
}
public Plane(Shader shader, Vector4 origin, Vector4 normal)
{
Shader = shader;
Origin = origin;
Normal = normal;
}
#endregion
#region Raytracing
public override void Collide(Ray ray)
{
Collide(ray, this);
}
public static void Collide(Ray ray, Plane plane)
{
Double nv = plane.Normal * ray.Direction;
if (nv >= -0.00001 && nv <= 0.00001) return;
Double param = (plane.Normal * (plane.Origin - ray.Origin)) / nv;
if (param < ray.Bias || param >= (ray.HitParam + 0.0000001)) return;
ray.HitModel = plane;
ray.HitParam = param;
// Yes, normal vector is also important
ray.HitNormal = plane.Normal;
ray.HitModelCount++;
}
#endregion
}
}
|
Java
|
UTF-8
| 783 | 2.359375 | 2 |
[] |
no_license
|
package com.dart.common.service.http;
import com.dart.data.domain.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.security.Principal;
/**
* @author RMPader
*/
public class UserRequestWrapper extends HttpServletRequestWrapper {
private final HttpServletRequest realRequest;
private final UserPrincipal principal;
public UserRequestWrapper(User user, HttpServletRequest request) {
super(request);
this.principal = new UserPrincipal(user);
this.realRequest = request;
}
@Override
public Principal getUserPrincipal() {
if (this.principal.getUser() == null) {
return realRequest.getUserPrincipal();
}
return principal;
}
}
|
Python
|
UTF-8
| 1,102 | 4.09375 | 4 |
[] |
no_license
|
# Pytanie 11 - na podstawie listy jezyki stworz listę jezyki_odwrocone
# zawierającą elementy listy jezyki w odwroconej kolejnosci
jezyki = ['Python', 'Java', 'C#', 'Ruby']
# 1
# jezyki.reverse() # odwróć listę języki (nastąpi nadpisanie wcześniejszej listy)
# jezyki_odwrocone = jezyki # przypisz wartość listy języki do nowej zmiennej jezyki_odwrocone
# print(jezyki_odwrocone) # wydrukuj liste jezyki_odwrocone
# 2
# jezyki_odwrocone = list(reversed(jezyki)) # stwórz listę na podstawie obiektu zawierającego odwrócone elementy listy języki i przypisz do języki_odwrócone
# print(jezyki_odwrocone)
# print(jezyki)
# 3
# jezyki_odwrocone = jezyki[::-1] # do zmiennej jezyki_odwrocone przypisz wartosci listy jezyki odczytane od tyłu
# print(jezyki_odwrocone)
# 4
jezyki_odwrocone = [] # stworz pusta liste jezyki_odwrocone
for jezyk in jezyki: # dla kolejnego jezyka w liscie jezyki
jezyki_odwrocone.insert(0,jezyk) # umiesc ten jezyk na indeksie zerowym listy jezyki_odwrocone
print(jezyki_odwrocone)
|
Markdown
|
UTF-8
| 919 | 2.921875 | 3 |
[] |
no_license
|
---
layout: post
title: "Piano Compositions"
date: 2012-02-25 19:11
comments: false
categories:
- family
tags: video
tags:
- piano
---
Libby and Jasmine composed piano music on the computer. Libby really likes working on the songs, Jasmine, not so much. Libby learned the life-lesson about computers and *saving your work*. She didn't save for a few days (I wasn't done Daddy!), and then lost all her work when the power went off. After some crying, she got back to work and finished the left hand.
They used the iMac to compose the music, and the iPad to play it. Now they have to learn to play their songs on the piano for real.
Libby wrote "The Bumpy Carriage Ride" and Jasmine wrote "The Dancing Puppy."
{% video http://media.eick.us/video/2012/02/piano-compositions/2012-02-14-Compositions-540p 960 540 http://media.eick.us/video/2012/02/piano-compositions/2012-02-14-Compositions-poster-960x540.png %}
|
C++
|
UTF-8
| 3,284 | 2.6875 | 3 |
[] |
no_license
|
//////////////////////////////////////////////////////////////////////
// D2Monster.h: interface of the CD2Monster class.
//
// CD2Monster, derived from CD2Unit, is used for manipulating monsters'
// attributes and states.
//
// Written by Abin (abinn32@yahoo.com)
// http://www.wxjindu.com/abin/
//
// July 14th, 2004
//////////////////////////////////////////////////////////////////////
#ifndef __D2MONSTER_H__
#define __D2MONSTER_H__
#include "D2Unit.h"
// Calculate 0x80 based HP percentage
#define CALC80BASEDHPPERCENT(x) ((BYTE)((double)(x) * 100.0 / 128.0))
///////////////////////////////////////////////////////////////////////
// CD2Monster Class Definition
///////////////////////////////////////////////////////////////////////
class CD2Monster : public CD2Unit
{
public:
///////////////////////////////////////////////////////////////////////
// Constructor(s) & destructor
///////////////////////////////////////////////////////////////////////
CD2Monster();
virtual ~CD2Monster();
///////////////////////////////////////////////////////////////////////
// Client Entries
///////////////////////////////////////////////////////////////////////
virtual void OnGameJoin(const THISGAMESTRUCT* pGame);
virtual void OnGameLeave();
virtual void OnGamePacketBeforeReceived(const BYTE* aPacket, DWORD aLen);
///////////////////////////////////////////////////////////////////////
// Public Attributes
///////////////////////////////////////////////////////////////////////
BYTE GetHPPercent() const; // Monster's current HP percentage (0 to 100)
BOOL IsAlive() const; // Whether the object is alive
BOOL IsCorpse() const; // Whether the object's corpse has appeared
///////////////////////////////////////////////////////////////////////
// Public Operations
///////////////////////////////////////////////////////////////////////
virtual void InitAttributes(); // Clean all attributes
protected:
///////////////////////////////////////////////////////////////////////
// Overrides
///////////////////////////////////////////////////////////////////////
virtual void OnMonsterSpawn(DWORD dwObjectID, WORD x, WORD y); // Monster spawned
virtual void OnHPPercentUp(BYTE iOldPercent, BYTE iNewPercent); // Monster's HP percent increased
virtual void OnHPPercentDown(BYTE iOldPercent, BYTE iNewPercent); // Monster's HP percent decreased
virtual void OnAttack(WORD x, WORD y, DWORD dwVictimID); // Monster attacked some targets
virtual void OnUnderAttack(WORD x, WORD y, DWORD dwAttackerID); // Monster is under attack
virtual void OnDeath(); // Monster died
virtual void OnCorpseAppeared(DWORD dwCorpseID, WORD x, WORD y); // Monster's corpse appeared
virtual void OnRevived(BOOL bByOther, WORD x, WORD y);
///////////////////////////////////////////////////////////////////////
// Protected Operations
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Protected Member Data
///////////////////////////////////////////////////////////////////////
BOOL m_bIsAlive; // Whether the Monster is alive
BOOL m_bIsCorpse; // Whether the Monster's corpse has appeared
BYTE m_iHPPercent; // Monster HP remaining percent
};
#endif // __D2MONSTER_H__
|
Python
|
UTF-8
| 722 | 2.78125 | 3 |
[] |
no_license
|
import os
import sys
import glob
import argparse
import imghdr
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('dir', help='directory of images')
args = parser.parse_args()
dir = os.path.normpath(args.dir)
for image in os.scandir(dir):
if imghdr.what(image.path): #if it is an image
if image.name.endswith('_rgb.jpg'):
print(image.name,'already right format')
else:
image = str(image.path)
image_name = (os.path.splitext(image))[0]
new_name = image_name + '_rgb.jpg'
print("Renaming from",image,'to',new_name)
os.rename(image, new_name)
|
Markdown
|
UTF-8
| 4,844 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
NearbyStores for Finding Stores
====
NearbyStores is constructed `async`, so when you instantiate it, you should await it, like this : ` const nearbyStores = await new NearbyStores(...)` this will work in your main node code without wrapping it in an anonymous async function.
If you have cloned this repo, you can run the example with this command:
`node ./example/nearby.js`
Constructor
====
`await new NearbyStores({...})`
|argument |type |default |description|
|-------- |---- |------- |--------|
|address |[Address](https://github.com/RIAEvangelist/node-dominos-pizza-api/blob/master/docs/Address.md) instance, or AddressObject or AddressString | |either an instance of the Address class or anthing that could be passed to the `Address` class to make an instance|
|type |String|`Delivery`|`Delivery`, `Carryout`, `all`|
Instance
====
|member/method |type |description|
|------------- |------|------- |
|address |[Address](https://github.com/RIAEvangelist/node-dominos-pizza-api/blob/master/docs/Address.md)|An Address Instance populated with the Domino's Store information|
|stores |Array| Array of basic store objects, see below.|
|dominosAPIResponse |[Dominos API Response Object](https://github.com/RIAEvangelist/node-dominos-pizza-api/blob/master/docs/DominosAPIResponse.md)|Raw response from Domino's Each response is a little different, but you can see the core info in the [Domino's API Response Doc](https://github.com/RIAEvangelist/node-dominos-pizza-api/blob/master/docs/DominosAPIResponse.md). |
### By PostalCode
***this yields a wide variety of stores*** because it is not a very specific address. To find stores closer to you (or your user), use a more specific address.
You can see the all the ways to pass an address [in the dominos pizza Address.md](https://github.com/RIAEvangelist/node-dominos-pizza-api/blob/master/docs/Address.md).
```js
import {NearbyStores} from 'dominos';
const nearbyStores=await new NearbyStores('63102');
console.dir(nearbyStores,{depth:1});
console.dir(nearbyStores.stores[0],{depth:1});
```
`nearbyStores.stores` is automatically populated from the dominos API when the class is instantiated. It is an `Array` of basic Store information. This info can be used as is, or you can create a `new Store(StoreID)` to get even more detailed information on the Store and its Menu as well.
``` js
import {NearbyStores, Store} from 'dominos';
const nearbyStores=await new NearbyStores('88 Colin P Kelly Jr St, 94107');
console.dir(nearbyStores,{depth:1});
console.dir(nearbyStores.stores[0],{depth:1});
//initialize the frst of the nearbyStores.stores
const store=await new Store(nearbyStores.stores[0].StoreID);
console.dir(store,{depth:1});
```
### Detailed class insight
```js
//nearbyStores high level instance
NearbyStores {
address: Address {
street: '88 COLIN P KELLY JR ST',
streetNumber: '88',
streetName: 'COLIN P KELLY JR ST',
unitType: '',
unitNumber: '',
city: 'SAN FRANCISCO',
region: 'CA',
postalCode: '94107-2008',
deliveryInstructions: ''
},
stores: [
[Object], [Object],
...
],
dominosAPIResponse: {
//core
Status: 0,
StatusItems: [Array],
//specific to this request
Granularity: 'Exact',
Address: [Object],
Stores: [Array]
}
}
//nearbyStores.stores[0] basic store info
{
StoreID: '8302',
IsDeliveryStore: false,
MinDistance: 22.7,
MaxDistance: 22.7,
Phone: '831-728-4444',
AddressDescription: '512 Main Street\nWatsonville, CA 95076\n',
HolidaysDescription: '',
HoursDescription: 'Su-Th 10:30am-12:00am\nFr-Sa 10:30am-1:00am',
ServiceHoursDescription: {
Carryout: 'Su-Sa 10:30am-10:00pm',
Delivery: 'Su-Th 10:30am-12:00am\nFr-Sa 10:30am-1:00am',
DriveUpCarryout: 'Su-Sa 4:30pm-9:00pm'
},
IsOnlineCapable: true,
IsOnlineNow: true,
IsNEONow: true,
IsSpanish: true,
LocationInfo: '',
LanguageLocationInfo: { en: '', es: '' },
AllowDeliveryOrders: true,
AllowCarryoutOrders: true,
AllowDuc: true,
ServiceMethodEstimatedWaitMinutes: {
Delivery: { Min: 29, Max: 34 },
Carryout: { Min: 13, Max: 18 }
},
StoreCoordinates: { StoreLatitude: '36.912', StoreLongitude: '-121.759' },
AllowPickupWindowOrders: false,
ContactlessDelivery: 'REQUIRED',
ContactlessCarryout: 'INSTRUCTION',
IsOpen: true,
ServiceIsOpen: { Carryout: true, Delivery: true, DriveUpCarryout: false }
}
```
|
TypeScript
|
UTF-8
| 3,368 | 2.5625 | 3 |
[] |
no_license
|
import { Injectable, NgZone } from '@angular/core';
import { ElectronService } from 'ngx-electron';
import { MediaFile } from '../../file-explorer/models/media-file';
import { MatDialog } from '@angular/material/dialog';
import { SelectUploadDialogComponent } from '../../file-explorer/modals/select-upload-dialog/select-upload-dialog.component';
export interface IMediaService {
openFileUploadDialog(callback: Function);
openImageUploadDialog(media: MediaFile);
createMediaFile(filePath: string): MediaFile;
add(media: MediaFile);
getMediaFiles(): MediaFile[];
delete(media: MediaFile);
}
@Injectable({
providedIn: 'root'
})
export class MediaService implements IMediaService {
private _mediaFiles: MediaFile[] = [];
constructor(
private electron: ElectronService,
private zone: NgZone,
private dialog: MatDialog) { }
getMediaFiles(): MediaFile[] {
return this._mediaFiles;
}
openImageUploadDialog(media: MediaFile) {
this.electron.ipcRenderer.send('open-image-dialog', ['png', 'jpg', 'jpeg']);
this.electron.ipcRenderer.on('selected-files', (event, file) => {
if (!file) {
console.log('No file was selected');
return;
}
this.zone.run(() => {
media.image = { name: this.getFileNameFromPath(file), path: file };
});
this.electron.ipcRenderer.removeAllListeners('selected-files');
});
}
openFileUploadDialog(callback: Function) {
const dialogRef = this.dialog.open(SelectUploadDialogComponent);
dialogRef.afterClosed().subscribe(res => {
if (res) {
if (res.isFolder) {
this.electron.ipcRenderer.send('open-folder-dialog', res.fileTypes);
} else {
this.electron.ipcRenderer.send('open-file-dialog', res.fileTypes);
}
this.electron.ipcRenderer.on('selected-files', (event: Event, files: string[]) => {
if (!files || !files.length) {
console.log('No files were selected');
return;
}
// Electron is running outside of the angular zone (NgZone)
// So change detection will not be run automatically
// NgZone.run() is used to run change detection manually
this.zone.run(() => {
callback(files);
});
this.electron.ipcRenderer.removeAllListeners('selected-files');
})
}
})
}
add(media: MediaFile) {
if (!this.mediaFileExists(media)) {
this._mediaFiles.push(media);
}
}
createMediaFile(filePath: string): MediaFile {
const name = this.getFileNameFromPath(filePath);
const path = filePath;
const type = this.getFileTypeFromPath(filePath);
const mediaFile = { name: name, path: path, type: type };
this.add(mediaFile);
return mediaFile;
}
delete(media: MediaFile) {
const index = this._mediaFiles.map(mf => mf.name).indexOf(media.name);
this._mediaFiles.splice(index, 1);
}
private mediaFileExists(mediaFile: MediaFile): boolean {
return this._mediaFiles.map(mf => mf.path).indexOf(mediaFile.path) > -1;
}
private getFileNameFromPath(path: string) {
const fileName = path.replace(/^.*[\\\/]/, '');
return fileName.replace(/\.[^/.]+$/, '');
}
private getFileTypeFromPath(path: string) {
const regex: RegExp = /(?:\.([^.]+))?$/;
return regex.exec(path)[1];
}
}
|
C++
|
GB18030
| 1,576 | 3.625 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
struct Node{
int data;
Node *link;
Node(Node *ptr = NULL){ link = ptr; }
Node(const int&item, Node *ptr = NULL)
{data = item; link = ptr;}
};
Node *merge(Node*,Node*);//ϲ
Node *printin(int); //
void printout(Node*);//
Node *merge(Node *a, Node *b){
Node *newhead;
if (a->data <= b->data)//ͷ
newhead = a;
else
newhead = b;
Node *prev1 = a, *prev2 = b;//Ϊ
while (a && b){
if (prev1->data <= prev2->data){
if (prev1->link == NULL)//һڵʱֹѭ
break;
a = prev1->link;//Ԥһڵ
if (prev1->link->data>prev2->data)//
prev1->link = prev2;
prev1 = a; //ƶڵ
}
else{
if (prev2->link == NULL)
break;
b = prev2->link;
if (prev2->link->data>=prev1->data)
prev2->link = prev1;
prev2 = b;
}
}
if (prev1->link == NULL) //aβʱ
prev1->link = prev2;
else
prev2->link = prev1;
return newhead;
}
Node *printin(int n){
Node *head = new Node();
Node *p = head;
for (int i = 0; i < n; i++){
int temp;
cin >> temp;
Node *newNode = new Node(temp);
p->link = newNode;
p = p->link;
}
return head->link;
}
void printout(Node* head){
Node*p = head;
while (p){
cout << p->data;
if (p->link){
cout << " ";
p = p->link;
}
else
break;
}
}
int main(){
int lena, lenb;
cin >> lena >> lenb;
if (lena&&lenb){
Node *a = printin(lena);
Node *b = printin(lenb);
Node *c = merge(a, b);
printout(c);
}
}
|
Markdown
|
UTF-8
| 982 | 2.828125 | 3 |
[] |
no_license
|
# mastermind
A [mastermind](https://en.wikipedia.org/wiki/Mastermind_(board_game)) game I made. This was fun and it was probably the game I made that I played the most. Either this or [gomoku](https://github.com/ca98am79/my-first-programs/tree/master/gomoku), although I was more proud of gomoku because it had some intelligence.





|
C
|
UTF-8
| 7,137 | 2.953125 | 3 |
[] |
no_license
|
#include "global.h"
#include "common.h"
Message createElectionMessage(char *content) {
return createCommonMessage(ELECTION, content);
}
Message createElectionOverMessage(char *content) {
return createCommonMessage(ELECTION_OVER, content);
}
Message createMessage(char *content) {
return createCommonMessage(MESSAGE, content);
}
Message createQuitMessage() {
return createCommonMessage(QUIT, NULL);
}
Message createCommonMessage(MessageType messageType, char *content) {
Message message;
message.messageType = messageType;
if (content != NULL) {
message.content = calloc(MESSAGE_SIZE, sizeof(char));
strcpy(message.content, content);
}
return message;
}
void convertMessageToData(MessageType messageType, char *content, char *message) {
strcpy(message, messageTypeToString(messageType));
strcat(message, content);
}
Message readMessage(char *message) {
Message mess;
size_t index = 0;
while (message[index] != '\n' && index <= MESSAGE_SIZE) {
index++;
}
char *mts = calloc(index + 1, sizeof(char));
strncpy(mts, message, index);
mess.messageType = messageStringToType(mts);
free(mts);
mess.content = calloc(strlen(message) - index + 1, sizeof(char));
strncpy(mess.content, message + index + 1, strlen(message) - index);
return mess;
}
char *messageTypeToString(MessageType messageType) {
switch (messageType) {
case ELECTION:
return "ELECTION\n";
case ELECTION_OVER:
return "ELECTION_OVER\n";
case MESSAGE:
return "MESSAGE\n";
default:
printf("ERROR! MessageType not handled\n");
return "";
}
}
MessageType messageStringToType(char *messageType) {
if (strcmp(messageType, "ELECTION") == 0) {
return ELECTION;
} else if (strcmp(messageType, "ELECTION_OVER") == 0) {
return ELECTION_OVER;
} else if (strcmp(messageType, "MESSAGE") == 0) {
return MESSAGE;
}
printf("ERROR! MessageType (%s) not handled\n", messageType);
return MESSAGE;
}
int getFQDN(char *fqdn, size_t n) {
char hostname[256];
int r = gethostname(hostname, 256);
if (r != 0) {
return 1;
}
struct addrinfo h = {0};
h.ai_family = AF_INET;
h.ai_socktype = SOCK_STREAM;
h.ai_flags = AI_CANONNAME;
struct addrinfo *info;
if (getaddrinfo(hostname, NULL, &h, &info) != 0) {
return 2;
}
strncpy(fqdn, info->ai_canonname, n);
freeaddrinfo(info);
return 0;
}
char *buildID(char *port) {
char fqdn[256];
int res = getFQDN(fqdn, 256);
if (res == 1 || res == 2) {
// Something went wrong
}
char *ID = calloc(strlen(fqdn) + strlen(port) + 3, sizeof(char));
strcpy(ID, fqdn);
strcat(ID, ",");
strcat(ID, port);
strcat(ID, "\n");
return ID;
}
int setupServerConnection(const int port, const int sockType) {
int server_fd;
struct addrinfo *addrInfo = 0;
fillInAddrInfo(&addrInfo, port, NULL, AI_PASSIVE, sockType);
server_fd = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);
if (server_fd == -1) {
fprintf(stderr, "Failed to create socket\n");
exit(EXIT_FAILURE);
}
// Allow reuse of local addresses.
int resueAddr = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &(resueAddr), sizeof(&resueAddr)) == -1) {
close(server_fd);
fprintf(stderr, "Failed to set socket optionals\n");
exit(EXIT_FAILURE);
}
if (bind(server_fd, addrInfo->ai_addr, addrInfo->ai_addrlen) == -1) {
close(server_fd);
fprintf(stderr, "Failed to bind socket\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(addrInfo);
if (sockType == SOCK_DGRAM) {
return server_fd;
}
if (listen(server_fd, SOMAXCONN)) {
fprintf(stderr, "Failed to listen to socket\n");
exit(EXIT_FAILURE);
}
return server_fd;
}
void fillInAddrInfo(struct addrinfo **addrInfo, const int port, const char *IPAddress, int flags, int sockType) {
char portId[15];
sprintf(portId, "%d", port);
struct addrinfo info;
memset(&info, 0, sizeof(info));
info.ai_family = AF_INET;
info.ai_socktype = sockType;
info.ai_protocol = 0;
info.ai_flags = flags;
if (getaddrinfo(IPAddress, portId, &info, addrInfo) != 0) {
fprintf(stderr, "Failed to get address info\n");
exit(EXIT_FAILURE);
}
}
int listenForIncomingConnection(int server_fd) {
int connection_fd;
fprintf(stdout, "Listening for connections...\n");
// Listen for ONE incoming connection.
while ((connection_fd = accept(server_fd, 0, 0)) == -1) {
fprintf(stderr, "SERVER ERROR: %s", strerror(errno));
}
return connection_fd;
}
int setupConnectionToServer(const char *ip, const uint16_t port, int sockType) {
// Convert Port to String
char portId[15];
sprintf(portId, "%d", port);
struct addrinfo *addrInfo = 0;
fillInAddrInfo(&addrInfo, port, ip, AI_ADDRCONFIG, sockType);
int sock = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);
if (sock == -1) {
freeaddrinfo(addrInfo);
fprintf(stderr, "Socket creation error\n");
exit(EXIT_FAILURE);
}
// Used to prioritize packets from this socket.
int optval = 6;
if (setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &optval, sizeof(int)) == -1) {
close(sock);
fprintf(stderr, "Failed to prioritize packets\n");
exit(EXIT_FAILURE);
}
// Try to connect to Server. Retry if unsuccessful.
while (connect(sock, addrInfo->ai_addr, addrInfo->ai_addrlen) == -1) {
fprintf(stderr, "Unable to connect, retrying in 1 sec...\n");
sleep(1);
}
freeaddrinfo(addrInfo);
return sock;
}
void postMessageWithWait(Message message) {
while (!postMessage(message)) {
//printf("Cant post electionOverMessage, waiting...\n");
}
}
uint32_t getCurrentTime() {
return (uint32_t )clock();
}
void handleElectionMessage(Message message, char *myID) {
int result = strcmp(myID, message.content);
if (result == 0) {
// My electionOverMessage
Message electionOverMessage = createElectionOverMessage(myID);
postMessageWithWait(electionOverMessage);
free(message.content);
} else if (result < 0) {
// Someone else is better, forward
postMessageWithWait(message);
} else {
// I'm better, don't forward
free(message.content);
}
}
void handleElectionOverMessage(Message message, char *myID) {
printf("Election Over\n");
if (strcmp(myID, message.content) == 0) {
Message messagePhase = createMessage(myID);
postMessageWithWait(messagePhase);
start = getCurrentTime();
free(message.content);
} else {
postMessageWithWait(message);
}
}
void handleMessageMessage(Message message, char *myID) {
if (strcmp(myID, message.content) == 0) {
// My message
printf("Time: %u\n", getCurrentTime() - start);
postMessageWithWait(message);
start = getCurrentTime();
} else {
postMessageWithWait(message);
}
}
void sendMessage(Message* message, int socket) {
if (socket != -1) {
char *messageData = calloc(MESSAGE_SIZE, sizeof(char));
convertMessageToData(message->messageType, message->content, messageData);
printf("Sending message: %s\n", messageData);
send(socket, messageData, MESSAGE_SIZE, 0);
free(messageData);
}
}
|
Java
|
UTF-8
| 1,096 | 2.953125 | 3 |
[] |
no_license
|
package backend;
/**
*
* @author Alex + Aiden
*/
public class AnswerParser {
public AnswerParser() {
}
public void questionType(String questionType, String realAnswer, String answers) {
switch (questionType) {
case "MC":
checkMultipleChoice(realAnswer, answers);
break;
case "SA":
checkMultipleChoice(realAnswer, answers);
break;
case "FB":
checkMultipleChoice(realAnswer, answers);
default:
System.out.println("Error =<^.^>=");
break;
}
}
public boolean checkMultipleChoice(String realAnswer, String answers) {
boolean answerIsCorrect = answers.equals(realAnswer);
if (answerIsCorrect)
System.out.println("Correct! Yay! <>< (<––– Fish)");
else
System.out.println("WRONG! TRY AGAIN STUPID! D:<");
return answerIsCorrect;
}
public boolean checkShortAnswer() {
return false; //SEND TO GUY BRO
}
}
|
PHP
|
UTF-8
| 331 | 2.984375 | 3 |
[] |
no_license
|
<?php
namespace Dancras\TicTacToe\Line;
use Dancras\TicTacToe\ValueObject\Coordinate;
use Dancras\TicTacToe\ValueObject\Symbol;
interface ILine
{
public function set(Coordinate $i, Symbol $symbol);
public function getNumberOfCoordinates();
public function getHighestCoordinate();
public function getSize();
}
|
Ruby
|
UTF-8
| 928 | 2.921875 | 3 |
[] |
no_license
|
# Include the helper
require 'spec_helper'
# Tests
describe 'Utils' do
context 'merge method' do
# Define the first array
let(:first) {
{
a: 1,
b: {
c: 2,
d: 3
},
e: {
f: 4,
g: 5
}
}
}
# Define the second array
let(:second) {
{
b: {
c: 15,
abc: '123'
},
e: {
g: 35
}
}
}
it 'should merge to arrays perfectly' do
# Merge first -> second
first_merge_result = Caracara::Utils.merge first, second
# Merge second -> first
second_merge_result = Caracara::Utils.merge second, first
# Assertions
expect(first_merge_result).to eq({a: 1, b: {abc: '123', c: 15, d: 3}, e: {f: 4, g: 35}})
expect(second_merge_result).to eq({b: {c: 2, abc: '123', d: 3}, e: {g: 5, f: 4}, a: 1})
end
end
end
|
C++
|
UTF-8
| 1,008 | 2.578125 | 3 |
[] |
no_license
|
#pragma once
#include <cmath>
namespace range_mi {
namespace p_not_measured {
template<unsigned int dimension>
void line(
const unsigned int * const line,
const double * const vacancy,
const double * const width,
unsigned int num_cells,
double dtheta,
double * const output_) {
double width_sum = 0;
double miss_p_product = 1;
double pnm = 0;
for (unsigned int i = 0; i < num_cells; i++) {
unsigned int j = line[i];
// Scale the probability by r^d to account
// for radial overlap as well as the width
// to account for aliasing.
output_[j] +=
width[i] * dtheta *
std::pow(width_sum, dimension - 1) *
pnm;
// The probability of the next cell not being
// measured is the probability some previous
// combination of cells were missed followed
// by a hit.
double miss_p = std::pow(vacancy[j], width[i]);
pnm += miss_p_product * (1 - miss_p);
width_sum += width[i];
miss_p_product *= miss_p;
}
}
}}
|
C#
|
UTF-8
| 927 | 3.09375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab5A
{
/// <summary>
/// This class contains information on how to create a doctor object
/// </summary>
class Doctor
{
public int ordinal { get; set; } //ordinal of a doctor
public string actor { get; set; } //actor of a docor
public int series { get; set; } //series of a doctor
public int age { get; set; } //age of a doctor
public string debut { get; set; } //debut of a doctor
public Doctor(int ordinal, string actor, int series, int age, string debut)
{
this.ordinal = ordinal;
this.actor = actor;
this.series = series;
this.age = age;
this.debut = debut;
}
}
}
|
C++
|
UTF-8
| 1,747 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Repeated_SoftwareSerial_TX
*
* Publish messages of all basic levels every 5 seconds
*
* Tested on:
* - Arduino Mega (ATMEGA 2560)
* - Arduino Uno (ATMEGA 328P)
* Test comments:
* Library works.
* Takes about 6 ms to send messages if baud rate of software serial being used is 115200
* Check the end of file for more comments on testing
*
* Created by : @TheProjectsGuy
* Maintained by : RoboManipal organization
*/
// Include header files for the library
#include <DebuggerSerial.h>
// Header file for SoftwareSerial
#include <SoftwareSerial.h>
// SoftwareSerial object
SoftwareSerial softSerial(10, 11); // Rx, Tx
// Debugger object with name
DebuggerSerial debuggerObj("MyDebugger");
void setup() {
// Setup the software serial
softSerial.begin(115200);
// Attach the software serial to the debugger
debuggerObj.AttachSerial(&softSerial);
}
void loop() {
// Publish all kinds of possible messages every five seconds
debuggerObj.print(DEBUG, "This is a DEBUG message");
debuggerObj.print(INFO, "This is an INFO message");
debuggerObj.print(WARNING, "This is a WARNING message");
debuggerObj.print(ERROR, "This is an ERROR message");
debuggerObj.print(FATAL, "This is a DEBUG message");
debuggerObj.printSensorData(10);
delay(5000);
}
/* Testing Comments
* Use the following code for the receiving end
```
void setup() {
// put your setup code here, to run once:
Serial1.begin(115200);
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial1.available()) {
Serial.print(Serial1.readStringUntil("\n"));
}
}
```
* Uploaded and tested on arduino mega
* Connect 10 to Serial1 TX
* Connect 11 to Serial1 RX
*/
|
Markdown
|
UTF-8
| 7,630 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
---
title: jen week
tags: jen
author: Rob Nugen
date: 1999-04-26
---
<p class=note>(transcribed from my diary)</p>
<p class=date>1:30pm Monday 26 April 1999</p>
<p>Jen and I just finished at KTRU. We had big fun! She browsed the stacks and chose discs and I played them. Great variety and she helped pronounce some of the artists and gave background information on a lot of them. Way cool. I recorded on tape most of the times she was speaking.
<p>Planned: my dad's on Tuesday, Kathy Fey at Whole Foods on Wednesday, Beach on Thursday, Rice Concert Thursday, Drum Circle Friday nite, Astroworld on Saturday!!
<p class=date></p>
<p><font size="+1" face="arial">1:00am Thursday 29 April 1999</font>
<p>Dad's was cool. we talked then ate at The Nook in Tomball. Drove out via 290, back via 249 to show Jen more roads. Saw some backwards cement mixers, with the cab in front and engine in back and the pointy end of the barrel pointing forward.
<p>Back to my dad's house he had to go to work; Jen and I read "83 Reasons Why Bill Gates Can Be Beat" or something out of WIRED magazine.
<p>Drove back to my area and watched <em>Never Been Kissed</em> starring the infinitely cute Drew Barrymore. I worked on website stuff and found a super incredible applet composer that allowed me to create a vertical scrolling applet in 30 minutes! I downloaded the composer from <a href="http://www.opencube.com">www.opencube.com</a>. Jen slept at Wende's.
<p>Today: up, got Jen, hi to Cassandra and Tere and Mad Potter, got Wende's credit card at her work, went to Whole Foods so Jen could get her shoulders massaged by Kathy Fey, went to KTRU at 4pm to meet Alex et. al. for an economics experiment. We bid on various pie charts' values, and actually made money! I got $14.75; Jen got $16.25!! Super cool!
<p>Then to Cost Plus and returned Wende's stuff and I got a picture of Sydney Australia Opera House and bay. Then to Mad Potter where youth painted tiles for Children's Museum on Sunday.
<p>Then to Rice U and I read 3.5 chapters of <a
href="/writings/thepin/index.shtml">The Past Is Now</a> (last half of
Air vs Atmosphere, Bigg Decision, Brain Removal, and Flash Furnace) at
950 watts, outdoors in the courtyard at Ley Center. Jen said I did
great. One guy (crowd of like 30) went "WHooo Hooo!!" after I
finished so I gave him my copy of the chapters.</p>
<p>Listened to other readers and then home. It's 1:10am. Must be up in 2.3 hours to DJ at KTRU!
<p class=date>7:30am Thursday 29 April 1999</p>
<p>KTRU with Jen was great. She essentially chose all the music (all but 3 songs) and I played it. She greatly expanded on certain artists with which she was familiar and made the show hella more interesting. I really apreciated her help since we had to write down all the songs and artist twice, Plus the composer and time it was played for BMI, some music survey thing.
<br>At the end of the shift, Mark wasn't there so we played some long tracks and signed off after the first long one at 7:12 or so and had an 18 minute track cued up for Mark as he came in. Thank you Jen for a great shift!!
<p class=date>1pm or so</p>
<p>We slept till 11:15 and are now at Stewart Beach in Galveston. We checked out the nice warm water (nice and warm for Jen, barely warm for me) and I buried my toes in the sand while standing in stomach-deep water in an attempt to stay in a relatively fixed position despite the wave motion.
<p class=date>3pm</p>
<p>Eating at Bennos Cajun Style Seafood. A dude offred us "best crawfish on the island! Come on and try it" and another guy was munching some so we grabbed some off his platter covered in cayan pepper so thick it's now stuck in my cuticles. Crazy. Weather is beautiful and sunny; we're eating outside.
<p>"So how'd you get to be The Crawfish King?" I asked the man.
<p>"I just started. I dunno. I sell live crawfish to about 75% of the places on the island."
<p>"Wow. hey <em>blah blah blah</em> want me to build you a website?"
<p>He smiled. "Naw, that's alright. I quit advertising about 2 years ago." He burst into laughter.
<p>"Congratulations."
<p><hr width="20%" align="left">
<p>Back to eating and suddenly <em><b>bing:</b> it's time to go to the ferry.</em> We had planned to ride the ferry, and now my angels said it was time to go. We leisurely said bye after cleaning up and leisurely drove to the ferry. Parked. Walked on. <em><b>HONK</b></em> went the ferry and away we went across the bay. Amazing perfect timing. Thank you, angels.
<p>Walked around on that end; Jen went down a pier; I talked to some kids on a school bus waiting for the ferry.
<p class=date>7pm</p>
<p>Hopped back on a ferry once we were done chillin' and a super friendly guy saw Jen taking pictures of sea gulls being fed. He was all, "here, stand in the back of my truck and feed them these Fritos." He put down the tailgate and we got some great shots of Jen feeding sea gulls, and I think some of me too.
<p>Back to my place via Dairy Queen, each showered, took Jen to Rice for a concert and I'm at FlashNet meeting with Rhonda, my first possible distributor who I didn't previously know.
<p class=date>2:20am Friday 30 April 1999</p>
<p>She signed up! We'll talk on Sunday afternoon after she gets back from the weekend.
<p>Talking to Jennifer (a different Jen) from Mad Potter now.
<p class=date>9:17am Friday 30 April 1999</p>
<p>Last night when Jennifer called, I was in the middle of pouring hot wax on Wende's feet as she was complaining about them being cold. Jen was there and we had been playing and wrestling and doing our own silly fun talking and having a supre great time when Jennifer called at midnight.
<p>I totally broke the connection with Jen and only paid attention to Wende to peel the wax from her feet. I was totally focused on <em>new girl</em>, a pattern I've seen too many times in my past.
<p>I am thankful that Wende called me on it this morning; I literally didn't notice last night what was happening and how I hurt Wen and Jen.
<p>After doing some self analysis, I find that I didn't want to ignore Jennifer's phone call because then she might not like me and I'd never see her again and then I'd be alone. (base level fear). I meditated on it and set the intention to become aware if that happens again.
<p class=date>12:40am Saturday 1 May 1999</p>
<p>Today I took Jen to Rice and then worked on Meagyn's tile at Mad Potter. Got Jen then did web stuff. Did more when Wen and Jen went to Ikea. Then Jen and I went to NPI where the guy ruined some of the film in her camera by opening it. Doh. not all lost though - got lots of pics from Galveston yesterday. Pics of Jen feeding birds on Ferry. Then bookstop and then drum circle and wrestled with Wen and Jen on bed now we are at House of Pies. I am tired as shit. Even "Tubthumping" couldn't even wake me up.
<p class=date>6pm Sunday 2 May 1999</p>
<p>Took Jen to the airport then went to youth group, then to Beck's Prime, then picked up tiles for the Children's Museum thing.
<p>The youth had super big fun arranging the tiles in the cement, decorating the whole thing with little jeweled stone things, and the youth honored me by having my right footprint splat hugely in the middle of the square. Wow.
<p>kT and I played in the museum with a ping pong ball blower tube thing that essentially used fans to blow ping pong balls through clear tubing to the other person's station. We laughed and laughed at our respective stations for like 20 minutes, seeing who could shove the most ping pong balls toward the other person's thing. So much fun.
|
C++
|
UTF-8
| 2,682 | 3.328125 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
using namespace std;
struct empleado{
string nombre;
string apellido;
int codemp;
float salario;
};
void mp();
void registro();
void lectura();
int main(){
mp();
system("pause");
exit(1);
}
void mp(){//Menu principal
int resp;
do {
system("cls");
cout<<" --------------------------"<<"\n";
cout<<" Menu Principal"<<"\n";
cout<<" --------------------------"<<"\n";
cout<<" 1 - Ingresar un nuevo seguro "<<"\n";
cout<<" 2 - Mostrar seguros guardados "<<"\n";
cout<<" 3 - Salir"<<"\n";
cout<<" --------------------------"<<"\n";
cout<<" Seleccione su opcion: ";
cin>>resp;
if (resp==1){
system("CLS");
registro();
}
else if (resp==2){
system("CLS");
lectura();
system("pause");
}
else if (resp==3)
break;
else
break;
} while(resp!=3);
}
void registro(){
string nombre, modelo, color;
int edad;
float precio, incremento, aux;
fflush(stdin);
cout<<"Ingrese Nombre: ";
getline(cin,nombre);
cout<<"Ingrese su Edad: ";
cin>>edad;
fflush(stdin);
cout<<"Ingrese modelo: ";
getline(cin,modelo);
if(modelo=="A"){
cout<<"Ingrese el color del vehiculo A: ";
getline(cin,color);
if (color=="Blanco"){
precio=240.50;
}
else if(color=="Metalizado"){
precio=330.00;
}
else{
precio=270.50;
}
}
else if(modelo=="B"){
cout<<"Ingrese el color del vehiculo B: ";
getline(cin,color);
if (color=="Blanco"){
precio=300.00;
}
else if(color=="Metalizado"){
precio=360.50;
}
else{
precio=330.00;
}
}
else{
system("cls");
cout<<"Ingrese A o B\n";
system("Pause");
}
if(edad<=31){
aux=precio*0.25;
incremento=aux+precio;
}
else if(edad>31&edad<=65){
incremento=0;
}
else if(edad>65){
aux=precio*0.30;
incremento=aux+precio;
}
fflush(stdin);
ofstream archivo; //leer archivo
archivo.open("Seguros.txt",ios::app);
archivo<<nombre<<"\t"<<edad<<"\t"<<modelo<<"\t"<<color<<"\t"<<precio<<"\t"<<incremento<<endl;
archivo.close();
}
void lectura(){
ifstream archivo;
string texto;
archivo.open("Seguros.txt",ios::in);//in: abrir archivo modo lectura
if(archivo.fail()){
cout<<"No se pudo abrir el archivo";
exit(1);
}
cout<<"Nombre"<<"\t"<<"Edad"<<"\t"<<"Modelo"<<"\t"<<"Color"<<"\t"<<"Precio"<<"\t"<<"Incremento"<<endl;
while(!archivo.eof()){//mientras no sea el final del archivo
getline(archivo,texto);
cout<<texto<<endl;
}
archivo.close();
}
|
Swift
|
UTF-8
| 1,139 | 2.703125 | 3 |
[] |
no_license
|
//
// ViewController.swift
// DemoSwift116_stackview
//
// Created by zhangshaoyu on 16/9/30.
// Copyright © 2016年 zhangshaoyu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = "stackview的使用"
// 实例化(注意:UIStackView在iOS9.0及以上系统版本才有)
let stackview = UIStackView(frame: self.view.bounds)
self.view.addSubview(stackview)
stackview.backgroundColor = UIColor.greenColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadView()
{
super.loadView()
self.view.backgroundColor = UIColor.whiteColor()
// UI适配
if self.respondsToSelector(Selector("edgesForExtendedLayout"))
{
self.edgesForExtendedLayout = UIRectEdge.None
}
}
}
|
C
|
UTF-8
| 8,899 | 3.46875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[])
{
int MAX_DATA=4;
int MAX_ROWS=5;
struct Address {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
//初始化的时候顺便定义长度
};
// 数据项
struct Database {
struct Address rows[MAX_ROWS];
};
struct Connection {
FILE *file;
//来自stdlib的类型,跟后续的fopen,fread,fclose和rewind有关
struct Database *db;
};
//Connection类型包括文件指针,以及接收文件的内存起始点
void Database_close(struct Connection *conn)
{
if(conn) {
if(conn->file) fclose(conn->file);
//使用fclose()函数就可以把缓冲区内最后剩余的数据输出到内核缓冲区,并释放文件指针和有关的缓冲区。
if(conn->db) free(conn->db);
//把文件指针释放掉,line 61
free(conn);
//line 58
}
}
void die(const char *message, struct Connection *conn)
{
if(errno) {
perror(message);
//print error
} else {
printf("ERROR: %s\n", message);
}
Database_close(conn);
exit(1);
}
void Address_print(struct Address *addr)
{
printf("%d %s %s\n",
addr->id, addr->name, addr->email);
}
void Database_load(struct Connection *conn)
{
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
// file read,从文件conn->file中读取数据
// conn->db是接收数据的起点
// 读取sizeof(struct Database)个元素
// 每个元素1个字节
// 返回实际读取的数据项个数
if(rc != 1) die("Failed to load database.", conn);
}
struct Connection *Database_open(const char *filename, char mode)
{
struct Connection *conn = malloc(sizeof(struct Connection));
if(!conn) die("Memory error", conn);
conn->db = malloc(sizeof(struct Database));
if(!conn->db) die("Memory error", conn);
if(mode == 'c') {
conn->file = fopen(filename, "w");
//file open,filename为文件路径,w是模式
//w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
} else {
conn->file = fopen(filename, "r+");
//r+ 以可读写方式打开文件,该文件必须存在。
if(conn->file) {
Database_load(conn);
}
}
if(!conn->file) die("Failed to open the file", conn);
return conn;
}
void Database_write(struct Connection *conn)
{
rewind(conn->file);
// 将文件内部的位置指针重新指向一个流(数据流/文件)的开头
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
// conn->db,写入数据的内存起始点,指针
// sizeof(struct Database),写入多少数据元素
// 1,每个数据的字节
// conn->file,文件流
// 返回写入数据项个数
if(rc != 1) die("Failed to write database.", conn);
rc = fflush(conn->file);
// 刷新缓冲读写区,清除掉缓冲读写区
if(rc == -1) die("Cannot flush database.", conn);
}
void Database_create(struct Connection *conn)
{
int i = 0;
for(i = 0; i < MAX_ROWS; i++) {
// make a prototype to initialize it
struct Address addr = {.id = i, .set = 0};
// then just assign it
// 初始化文件,并且用空的数据项填充进去,填充好的话set为1,未填充的set为0
conn->db->rows[i] = addr;
}
}
void Database_set(struct Connection *conn, int id, char *name, const char *email)
{
struct Address *addr = &conn->db->rows[id];
if(addr->set) die("Already set, delete it first", conn);
addr->set = 1;
name[MAX_DATA] = '\0';
// WARNING: bug, read the "How To Break It" and fix this
char *res = strncpy(addr->name, name, MAX_DATA);
// demonstrate the strncpy bug
// 把addr->name的MAX_DATA个字节复制到name
// 不足MAX_DATA的话以null填充剩余字节
// 返回指向addr->name的指针
if(!res) die("Name copy failed", conn);
res = strncpy(addr->email, email, MAX_DATA);
if(!res) die("Email copy failed", conn);
}
void Database_get(struct Connection *conn, int id)
{
struct Address *addr = &conn->db->rows[id];
if(addr->set) {
Address_print(addr);
} else {
die("ID is not set", conn);
}
}
void Database_delete(struct Connection *conn, int id)
{
struct Address addr = {.id = id, .set = 0};
conn->db->rows[id] = addr;
}
void Database_list(struct Connection *conn)
{
int i = 0;
struct Database *db = conn->db;
for(i = 0; i < MAX_ROWS; i++) {
struct Address *cur = &db->rows[i];
if(cur->set) {
Address_print(cur);
}
}
}
char *filename = argv[1];
char action = argv[2][0];
struct Connection *conn = Database_open(filename, action);
// 先malloc一个空间给文件,然后再malloc一个文件指针
// 如果是create模式的话,就以只写模式创建文件,如果文件已存在,就覆盖一个空文件
// 如果是其他模式,就以可读写方式打开文件
// 如果文件已经读取到内存里,就直接从内存读取
if(argc < 3) die("USAGE: ex17 <dbfile> <action> [action params]", conn);
int id = 0;
if(argc > 3) id = atoi(argv[3]);
// argv[3]在main开头声明是char,在这里需要把字符串转换成int
if(id >= MAX_ROWS) die("There's not that many records.", conn);
switch(action) {
// create,创建数据文件
case 'c':
Database_create(conn);
// 初始化并且填充空数据项
Database_write(conn);
// 重新读取文件
break;
// get,获取数据项
case 'g':
if(argc != 4) die("Need an id to get", conn);
Database_get(conn, id);
break;
// set,设置数据项
case 's':
if(argc != 6) die("Need id, name, email to set", conn);
Database_set(conn, id, argv[4], argv[5]);
// 把数据项的set打个标记
// 把数据项复制过去
Database_write(conn);
// 修改的只是内存里的数据,这里把内存里的数据再写到文件里
break;
// delete,删除数据项
case 'd':
if(argc != 4) die("Need id to delete", conn);
Database_delete(conn, id);
// 创建一个空的数据项,然后覆盖到要删除的数据项上
Database_write(conn);
break;
// list,列出数据项
case 'l':
Database_list(conn);
// 按照顺序把数据项print出来
break;
default:
die("Invalid action, only: c=create, g=get, s=set, d=del, l=list", conn);
}
Database_close(conn);
// free掉所有东西,包括文件指针,文件,数据项指针
return 0;
}
|
Python
|
UTF-8
| 4,306 | 3.65625 | 4 |
[] |
no_license
|
# coding:utf8
# Author : huxiaoyi
# Date: 2019-04-16
# Time: 22:31
# At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals. Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had as each key’s value.
# medal_count = {
# 'United States': 70,
# 'Great Britain': 38,
# 'China': 45,
# 'Russia': 30,
# 'Germany': 17,
# }
# Given the dictionary swimmers, add an additional key-value pair to the dictionary with "Phelps" as the key and the integer 23 as the value. Do not rewrite the entire dictionary.
# swimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4}
# swimmers['Phelps'] = 23
# print(swimmers)
# Add the string “hockey” as a key to the dictionary sports_periods and assign it the value of 3. Do not rewrite the entire dictionary.
# sports_periods = {'baseball': 9, 'basketball': 4, 'soccer': 4, 'cricket': 2}
# sports_periods['hockey'] = 3
# print(sports_periods)
# The dictionary golds contains information about how many gold medals each country won in the 2016 Olympics. But today, Spain won 2 more gold medals. Update golds to reflect this information.
# golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29}
# golds['Spain'] = 19+2
# print(golds)
# Create a list of the countries that are in the dictionary golds, and assign that list to the variable name countries. Do not hard code this.
# golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29}
#
# countries = list(golds.keys())
# Provided is the dictionary, medal_count, which lists countries and their respective medal count at the halfway point in the 2016 Rio Olympics. Using dictionary mechanics, assign the medal count value for "Belarus" to the variable belarus. Do not hardcode this.
# medal_count = {'United States': 70, 'Great Britain': 38, 'China': 45, 'Russia': 30, 'Germany': 17, 'Italy': 22,
# 'France': 22, 'Japan': 26, 'Australia': 22, 'South Korea': 14, 'Hungary': 12, 'Netherlands': 10,
# 'Spain': 5, 'New Zealand': 8, 'Canada': 13, 'Kazakhstan': 8, 'Colombia': 4, 'Switzerland': 5,
# 'Belgium': 4, 'Thailand': 4, 'Croatia': 3, 'Iran': 3, 'Jamaica': 3, 'South Africa': 7, 'Sweden': 6,
# 'Denmark': 7, 'North Korea': 6, 'Kenya': 4, 'Brazil': 7, 'Belarus': 4, 'Cuba': 5, 'Poland': 4,
# 'Romania': 4, 'Slovenia': 3, 'Argentina': 2, 'Bahrain': 2, 'Slovakia': 2, 'Vietnam': 2,
# 'Czech Republic': 6, 'Uzbekistan': 5}
# belarus = medal_count['Belarus']
# print(belarus)
# The dictionary total_golds contains the total number of gold medals that countries have won over the course of history. Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable name chile_golds. Do not hard code this!
# total_golds = {"Italy": 114, "Germany": 782, "Pakistan": 10, "Sweden": 627, "USA": 2681, "Zimbabwe": 8, "Greece": 111,
# "Mongolia": 24, "Brazil": 108, "Croatia": 34, "Algeria": 15, "Switzerland": 323, "Yugoslavia": 87,
# "China": 526, "Egypt": 26, "Norway": 477, "Spain": 133, "Australia": 480, "Slovakia": 29, "Canada": 22,
# "New Zealand": 100, "Denmark": 180, "Chile": 13, "Argentina": 70, "Thailand": 24, "Cuba": 209,
# "Uganda": 7, "England": 806, "Denmark": 180, "Ukraine": 122, "Bahamas": 12}
# chile_golds = total_golds['Chile']
# Provided is a dictionary called US_medals which has the first 70 metals that the United States has won in 2016, and in which category they have won it in. Using dictionary mechanics, assign the value of the key "Fencing" to a variable fencing_value. Remember, do not hard code this.
US_medals = {"Swimming": 33, "Gymnastics": 6, "Track & Field": 6, "Tennis": 3, "Judo": 2, "Rowing": 2, "Shooting": 3,
"Cycling - Road": 1, "Fencing": 4, "Diving": 2, "Archery": 2, "Cycling - Track": 1, "Equestrian": 2,
"Golf": 1, "Weightlifting": 1}
fencing_value = US_medals['Fencing']
|
C#
|
UTF-8
| 2,515 | 2.734375 | 3 |
[] |
no_license
|
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
namespace BRSPRJ_A3_WebAPI.Models.SrcMessage
{
/// <summary>
/// 客製Json序列化物件器類別
/// </summary>
public class CustomResolver : DefaultContractResolver
{
/// <summary>
/// 傳遞訊息(BoardingBagList)之訊息內容種類之列舉項目
/// </summary>
public BodyChoice Choice { get; set; }
/// <summary>
/// 建構子
/// </summary>
/// <param name="choice">傳遞訊息(BoardingBagList)之訊息內容種類之列舉項目</param>
public CustomResolver(BodyChoice choice)
{
Choice = choice;
}
/// <summary>
/// Create a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>
/// <param name="member">The member to create a <see cref="JsonProperty"/> for</param>
/// <param name="memberSerialization">The member parent's <see cref="MemberSerialization"/></param>
/// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/></returns>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (member.GetCustomAttribute<JsonPropertyOnSealObjAttribute>() != null)
{
prop.PropertyName = ChooseOneOf(prop.PropertyName);
}
return prop;
}
/// <summary>
/// 客製化Json序列化物件轉換中SealObj物件名稱選擇
/// </summary>
/// <param name="name">原SealObj物件名稱</param>
/// <returns>依<c>BodyChoice</c>轉換後名稱</returns>
protected string ChooseOneOf(string name)
{
switch (Choice)
{
case BodyChoice.Truck:
name = typeof(Truck).Name;
break;
case BodyChoice.Container:
name = typeof(Container).Name;
break;
case BodyChoice.Baggage:
name = typeof(Baggage).Name;
break;
default:
name = typeof(Container).Name;
break;
}
return name;
}
}
}
|
SQL
|
UTF-8
| 5,098 | 3.0625 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 16-08-2019 a las 21:26:02
-- Versión del servidor: 10.3.16-MariaDB
-- Versión de PHP: 7.3.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `bd_app_quindio`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `hoteles`
--
CREATE TABLE `hoteles` (
`id` int(11) NOT NULL,
`nombre` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`direccion` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`sitio_web` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`correo` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`telefono` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`celular` varchar(30) COLLATE utf8_spanish2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `hoteles`
--
INSERT INTO `hoteles` (`id`, `nombre`, `direccion`, `sitio_web`, `correo`, `telefono`, `celular`) VALUES
(1, ' luna ', 'porvenir', 'www.porvenir.com', 'luna@gmail.com', '0000', '321755890'),
(2, ' luna azul', 'Quindio', 'www.laquindio.com', 'lunaA@gmail.com', '321456', '3217890'),
(3, ' plaza mayor', 'centro', 'www.plazam.com', 'plazaM@gmail.com', '0000', '321789067');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `operadores_turisticos`
--
CREATE TABLE `operadores_turisticos` (
`id` int(11) NOT NULL,
`nombre` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`direccion` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`sitio_web` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`correo` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`telefono` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`celular` varchar(20) COLLATE utf8_spanish2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `operadores_turisticos`
--
INSERT INTO `operadores_turisticos` (`id`, `nombre`, `direccion`, `sitio_web`, `correo`, `telefono`, `celular`) VALUES
(1, 'turismo ya', 'plaza quindio', 'www.opquindi@gmail.com', 'quindi@gmail.com', '321456', '3217890'),
(2, 'Turi quindio', 'plaza quindio', 'www.opquindi@gmail.com', 'quindi@gmail.com', '321456', '3217890');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `sitio_turisticos`
--
CREATE TABLE `sitio_turisticos` (
`id` int(11) NOT NULL,
`nombre` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`direccion` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`sitio_web` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`correo` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`telefono` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`celular` varchar(20) COLLATE utf8_spanish2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Volcado de datos para la tabla `sitio_turisticos`
--
INSERT INTO `sitio_turisticos` (`id`, `nombre`, `direccion`, `sitio_web`, `correo`, `telefono`, `celular`) VALUES
(1, ' Parque del cafe', 'Panaca', 'www.pcafe.com', 'pc@gmail.com', '0000', '321755890'),
(2, ' Finca don pancho', 'Quindio', 'www.pancho.com', 'pc@gmail.com', '0000', '321755890');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios`
--
CREATE TABLE `usuarios` (
`id` int(11) NOT NULL,
`username` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,
`password` varchar(30) COLLATE utf8_spanish2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `hoteles`
--
ALTER TABLE `hoteles`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `operadores_turisticos`
--
ALTER TABLE `operadores_turisticos`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `sitio_turisticos`
--
ALTER TABLE `sitio_turisticos`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `usuarios`
--
ALTER TABLE `usuarios`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `hoteles`
--
ALTER TABLE `hoteles`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `operadores_turisticos`
--
ALTER TABLE `operadores_turisticos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `sitio_turisticos`
--
ALTER TABLE `sitio_turisticos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `usuarios`
--
ALTER TABLE `usuarios`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
PHP
|
UTF-8
| 6,783 | 3.078125 | 3 |
[] |
no_license
|
<?php
/**
* @package PHPClassCollection
* @subpackage Catcher
* @link http://php-classes.sourceforge.net/ PHP Class Collection
* @author Dennis Wronka <reptiler@users.sourceforge.net>
*/
/**
* @package PHPClassCollection
* @subpackage Catcher
* @link http://php-classes.sourceforge.net/ PHP Class Collection
* @author Dennis Wronka <reptiler@users.sourceforge.net>
* @version 1.1
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPL 2.1
*/
class catcher
{
/**
* Decide if exceptions are handled.
*
* @var bool
*/
private $exceptions;
/**
* Decide if errors are handled.
*
* @var bool
*/
private $errors;
/**
* Decide if the class should stop the script on fatal errors.
*
* @var bool
*/
private $dieonfatal;
/**
* Decide if the class should resume the script on recoverable errors.
*
* @var bool
*/
private $recovery;
/**
* Decide if the class should stop the script on unknown errors.
*
* @var bool
*/
private $dieonunknown;
/**
* Decide if message should be printed.
*
* @var bool
*/
private $output=true;
/**
* Decide if output should be HTML.
*
* @var bool
*/
private $outputhtml=true;
/**
* The recipient of error-mails.
*
* @var mixed
*/
private $mailto=false;
/**
* The sender of error-mails.
*
* @var mixed
*/
private $mailfrom=false;
/**
* The subject of error-mails.
*
* @var mixed
*/
private $mailsubject=false;
/**
* The log-file for errors.
*
* @var mixed
*/
private $logfile=false;
/**
* Decide if error-reports should include a backtrace.
*
* @var bool
*/
private $backtrace=false;
/**
* Information on the last error.
*
* @var array
*/
private $lasterror;
/**
* Information on the last exception.
*
* @var array
*/
private $lastexception;
/**
* Constructor
*
* @param bool $exceptions
* @param bool $errors
* @param bool $dieonfatal
* @param bool $recovery
* @param bool $dieonunknown;
*/
public function __construct($exceptions=true,$errors=true,$dieonfatal=true,$recovery=false,$dieonunknown=true)
{
$this->exceptions=$exceptions;
$this->errors=$errors;
$this->dieonfatal=$dieonfatal;
$this->recovery=$recovery;
$this->dieonunknown=$dieonunknown;
if ($this->exceptions===true)
{
set_exception_handler(array($this,'catchexception'));
}
if ($this->errors===true)
{
set_error_handler(array($this,'catcherror'));
}
}
/**
* Destructor
*
*/
public function __destruct()
{
if ($this->exceptions===true)
{
restore_exception_handler();
}
if ($this->errors===true)
{
restore_error_handler();
}
}
/**
* Set backtrace-parameters.
*
* @param bool $backtrace
*/
public function setbacktrace($backtrace)
{
$this->backtrace=$backtrace;
}
/**
* Set output-parameters.
*
* @param bool $output
* @param bool $outputhtml
*/
public function setoutput($output,$outputhtml=true)
{
$this->output=$output;
$this->outputhtml=$outputhtml;
}
/**
* Set mail-parameters.
*
* @param mixed $mailto
* @param mixed $mailfrom
* @param mixed $mailsubject
*/
public function setmail($mailto,$mailfrom,$mailsubject)
{
$this->mailto=$mailto;
$this->mailfrom=$mailfrom;
$this->mailsubject=$mailsubject;
}
/**
* Set log-parameters.
*
* @param mixed $logfile
*/
public function setlogfile($logfile)
{
$this->logfile=$logfile;
}
/**
* Catch an exception.
*
* @param Exception $exception
*/
public function catchexception($exception)
{
$message='Catcher (Exception): '.$exception->getMessage().' (File: '.$exception->getFile().' - Line: '.$exception->getLine().')';
$this->lastexception=array('message'=>$exception->getMessage(),'file'=>$exception->getFile(),'line'=>$exception->getLine());
$this->outputmessage($message);
$this->mailmessage($message);
$this->logmessage($message);
}
/**
* Catch an error.
*
* @param int $errornr
* @param string $errortext
* @param string $errorfile
* @param int $errorline
* @param array $errorcontext
*/
public function catcherror($errornr,$errortext,$errorfile,$errorline,$errorcontext)
{
$this->lasterror=array('errornr'=>$errornr,'errortext'=>$errortext,'errorfile'=>$errorfile,'errorline'=>$errorline,'errorcontext'=>$errorcontext);
switch($errornr)
{
case E_USER_ERROR:
$errortype='Error';
break;
case E_RECOVERABLE_ERROR:
$errortype='Recoverable Error';
break;
case E_WARNING:
case E_USER_WARNING:
$errortype='Warning';
break;
case E_NOTICE:
case E_USER_NOTICE:
$errortype='Notice';
break;
case E_STRICT:
$errortype='Strict Notice';
break;
default:
$errortype='Unknown Error';
break;
}
$message='Catcher ('.$errortype.'): '.$errortext.' (File: '.$errorfile.' - Line: '.$errorline.')'."\n";
if ($this->backtrace===true)
{
$backtrace=debug_backtrace();
if (count($backtrace)>1)
{
$message.='Backtrace: '."\n";
for ($step=count($backtrace)-1;$step>0;$step--)
{
if (!empty($backtrace[$step]['class']))
{
$message.=$backtrace[$step]['class'].'->';
}
$message.=$backtrace[$step]['function'].'()';
if ((!empty($backtrace[$step]['file'])) && (!empty($backtrace[$step]['line'])))
{
$message.=' (File: '.$backtrace[$step]['file'].' - Line: '.$backtrace[$step]['line'].')';
}
$message.="\n";
}
$message.="\n";
}
}
$this->outputmessage($message);
$this->mailmessage($message);
$this->logmessage($message);
if ((($this->dieonfatal===true) && (($errortype=='Error') || (($errortype=='Recoverable Error') && ($this->recovery===false)))) || (($this->dieonunknown===true) && ($errortype=='Unknown Error')))
{
die();
}
}
/**
* Print error-message.
*
* @param string $message
*/
private function outputmessage($message)
{
if ($this->output===true)
{
if ($this->outputhtml===true)
{
echo nl2br($message);
}
else
{
echo $message;
}
}
}
/**
* Mail error-message.
*
* @param string $message
*/
private function mailmessage($message)
{
if (($this->mailto!=false) && ($this->mailfrom!=false) && ($this->mailsubject!=false))
{
mail($this->mailto,$this->mailsubject,$message,'From: '.$this->mailfrom."\n");
}
}
/**
* Log error-message.
*
* @param string $message
*/
private function logmessage($message)
{
if ($this->logfile!=false)
{
$file=fopen($this->logfile,'a');
fwrite($file,'['.date('d/M/Y H:i:s',time()).'] '.$message);
fclose($file);
}
}
/**
* Get the last exception.
*
* @return array
*/
public function getlastexception()
{
return $this->lastexception;
}
/**
* Get the last error.
*
* @return array
*/
public function getlasterror()
{
return $this->lasterror;
}
}
?>
|
Markdown
|
UTF-8
| 1,291 | 2.75 | 3 |
[] |
no_license
|
# 14
Смотрю на него и не вижу:</br>
Называю его глубочайшим.</br>
Вслушиваюсь в него и не слышу:</br>
Называю его тишайшим.</br>
Касаюсь его и не могу ухватить:</br>
Называю его мельчайшим.</br>
Эти три невозможно определить,</br>
Посему я смешиваю их и рассматриваю как одно.</br>
[Это одно] вверху не светло, внизу не темно,</br>
Тянется без конца и без края, нельзя дать ему имя.</br>
И вновь возвращается туда, где нет вещей.</br>
Оно зовется бесформенной формой,</br>
невещественным образом</br>
Оно зовется туманным и смутным.</br>
Встречаешь его – не видишь его главы,</br>
Провожаешь его – не видишь его спины.</br>
Держаться Пути древних,</br>
Чтобы повелевать ныне сущим,</br>
И знать Первозданное Начало –</br>
Вот что такое основа и нить Пути.</br>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.