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
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 1,950
| 1.898438
| 2
|
[] |
no_license
|
package cn.kingtous.diplomagenerator.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.kingtous.diplomagenerator.Base.BaseActivity;
import cn.kingtous.diplomagenerator.R;
import cn.kingtous.diplomagenerator.Tools.FileUtil;
public class GenSuccessActivity extends BaseActivity {
@BindView(R.id.image_id)
ImageView imageId;
@BindView(R.id.btn_open_other)
QMUIRoundButton btnOpenOther;
@BindView(R.id.btn_send)
QMUIRoundButton btnSend;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
ButterKnife.bind(this);
initView();
initTopBar();
initEvent();
}
@Override
protected void initView() {
super.initView();
Glide.with(this).load(Uri.fromFile(new File(getIntent().getStringExtra(PhotoEditActivity.INTENT_OUTPUT_PATH)))).into(imageId);
}
@Override
protected void initEvent() {
super.initEvent();
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FileUtil.sendFiles(GenSuccessActivity.this,getIntent().getStringExtra(PhotoEditActivity.INTENT_OUTPUT_PATH));
}
});
btnOpenOther.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FileUtil.processFile(GenSuccessActivity.this,getIntent().getStringExtra(PhotoEditActivity.INTENT_OUTPUT_PATH));
}
});
}
}
|
Ruby
|
UTF-8
| 1,079
| 3.828125
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def admin_login(username, password)
if username == "ADMIN" && password == "12345"
return "Access granted"
elsif username == "admin" && password == "12345"
return "Access granted"
else
return "Access denied"
end
end
def hows_the_weather(temperature)
if temperature.to_i < 40
return "It\'s brisk out there!"
elsif temperature.to_i >=40 && temperature.to_i < 66
return "It's a little chilly out there!"
elsif temperature.to_i > 85
return "It's too dang hot out there!"
else return "It's perfect out there!"
end
end
def fizzbuzz(num)
if num.to_i % 3 == 0 && num.to_i % 5 == 0
return "FizzBuzz"
elsif num.to_i % 3 == 0
return "Fizz"
elsif num.to_i % 5 ==0
return "Buzz"
else
return num
end
end
def calculator(operation, num1, num2)
if operation == "+"
return num1 + num2
elsif operation == "-"
return num1 - num2
elsif operation == "*"
return num1 * num2
elsif operation == "/"
return num1 / num2
else
puts "Invalid operation!"
end
end
|
C
|
UTF-8
| 525
| 2.90625
| 3
|
[] |
no_license
|
// gcc -o tlink -g -W -Wall tlink.c
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
static void
die(const char *str)
{
perror(str);
exit(2);
}
int
main(int argc, char *argv[])
{
assert(argc == 3);
#if 1
{
int fd;
if ((fd = creat(argv[1], 0666)) == -1)
die(argv[1]);
write(fd, "stuff\n", 6);
close(fd);
}
#endif
if (link(argv[1], argv[2]))
die(argv[2]);
return 0;
}
|
Java
|
UTF-8
| 3,027
| 3.46875
| 3
|
[] |
no_license
|
import java.util.Scanner;
import java.io.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.stage.Stage;
/**
* The Life Time LineChart class extends the JavaFX LineChart Application Class.
*
* Produce a line chart plotting the data from MyWorld after the evolution has
* been inducted. Plot the life time of creatures over generations.
*
* Note: Must delete old fitnessdata.txt everytime you want to run a new round
*
* @author Mika Smith
* @version 5.0
* @since 2017-04-05
*/
public class LifeTimeLineChart extends Application {
private static final String FILENAME = "fitnessdata.txt";
/*Add a data point to the chart*/
public void addToChart(Series<Number, Number> series, int generation, float fitness){
series.getData().add(new XYChart.Data<Number, Number>(generation, fitness));
}
@Override public void start(Stage stage) {
stage.setTitle("Change in Average Life Time");
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Generation");
yAxis.setLabel("Average Life Time");
//Manually set lower and upper bounds for fitness on the y axis
yAxis.setLowerBound(20);
yAxis.setUpperBound(60);
yAxis.setAutoRanging(false);
//Create the line chart
final LineChart<Number,Number> lineChart = new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setCreateSymbols(false); //creates more of a trend
//Create window with line chart
Scene scene = new Scene(lineChart,800,600);
//Create data series for lifetime over generations
Series<Number, Number> series2 = new XYChart.Series<Number, Number>();
series2.setName("Average Lifetime");
//Read in input from our file generated from MyWorld containing values of average fitness
int gen=0;
try {
BufferedReader in = new BufferedReader(new FileReader(FILENAME));
String str;
while ((str = in.readLine()) != null){
str= in.readLine();
Scanner sc = new Scanner(str);
gen = sc.nextInt();
float fitness = sc.nextFloat();
float life = sc.nextFloat();
addToChart(series2, gen, life);
sc.close();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
lineChart.setTitle("Average Life Time over " + gen + " Generations");
//Add our series data to the linechart
lineChart.getData().add(series2); //Average lifetime
//Add linechart to window
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
JavaScript
|
UTF-8
| 4,398
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import React, { Component, PropTypes as T } from 'react'
import shadowEqual from 'react-addons-shallow-compare'
import cNames from 'classnames'
import validator from 'validator'
import any from 'lodash/collection/any'
import all from 'lodash/collection/all'
import reduce from 'lodash/collection/reduce'
import forEach from 'lodash/collection/forEach'
import Input from './Input'
class Form extends Component {
static propTypes = {
className: T.string,
invalidClassName: T.string,
children: T.any,
validator: T.object,
onValidated: T.func
}
static defaultProps = {
invalidClassName: 'invalid',
validator,
onValidated: () => {}
}
constructor (props) {
super(props)
this.inputs = {}
this.initValue = {}
this.state = {
isValid: true
}
}
shouldComponentUpdate (nextProps, nextState) {
// improvement
return shadowEqual(this, nextProps, nextState)
}
render () {
return (
<form className={cNames([
this.props.className,
{ [this.props.invalidClassName]: !this.state.isValid }
])}>
{React.Children.map(this.props.children, (child) => {
// take the component which has the name props as the input component
if (child.props.name) {
return React.cloneElement(child, {
attach: ::this._attachInput,
detach: ::this._detachInput,
validate: ::this._validateInput,
onValidated: ::this._validateForm // private invoked
})
}
else return child
})}
</form>
)
}
get body () {
return reduce(this.inputs, (ret, component, key) => {
ret[key] = component.state.value
return ret
}, {})
}
get isDirty () {
return any(this.inputs, (component) => {
return component.state.isDirty
})
}
get isValid () {
return all(this.inputs, (component) => {
return component.state.isValid
})
}
get errors () {
return reduce(this.inputs, (ret, component, key) => {
if (!component.isValid) ret[key] = component.state.errMsg
return ret
}, {})
}
// actually, this method just set all input to dirty to make
// sure the invalid message showed
validate () {
forEach(this.inputs, (component) => {
if (!component.state.isDirty) component.setState({ isDirty: true })
})
}
reset () {
forEach(this.inputs, (component) => {
component.setState({
value: this.initValue[component.props.name],
isDirty: false
}, () => {
component.props.validate(component)
})
})
}
_attachInput (component) {
this.inputs[component.props.name] = component
this.initValue[component.props.name] = component.state.value
}
_detachInput (component) {
delete this.inputs[component.props.name]
}
_validateInput (component) {
const { validation } = component.props
if (validation) {
const { value } = component.state
forEach(validation, (opt, validatorKey) => {
let isValid
// "isLength:1:6": "Your lenght should be 1 to 6."
if (typeof opt === 'string') {
const [ method, ...args ] = validatorKey.split(/\s*:\s*/)
const fn = this.props.validator[method]
if (typeof fn === 'function') {
// check form validation after input state change
isValid = !!fn.apply(this.props.validator, [ value, ...args ])
this._setComponentValid(component, !!isValid, opt)
}
}
// "isEqualToAnother": {
// msg: "Should equal to another input",
// validator: (val) => {
//
// }
// }
else {
const { validator, msg } = opt
if (typeof validator === 'function') {
isValid = !!validator.call(component, value)
this._setComponentValid(component, !!isValid, msg)
}
}
// stop validate if one of validator has already failed
if (isValid === false) return false
})
}
}
_setComponentValid (component, isValid, errMsg) {
component.setState({
isValid, errMsg
}, ::this._validateForm)
}
_validateForm () {
this.setState({ isValid: this.isValid }, () => {
this.props.onValidated(this.isValid)
})
}
}
Form.Input = Input
export default Form
|
SQL
|
UTF-8
| 1,858
| 3.625
| 4
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
permissive
|
DROP TABLE IF EXISTS indexed_table;
CREATE TABLE indexed_table
( `tm` DateTime,
`log_message` String,
INDEX log_message log_message TYPE tokenbf_v1(4096, 2, 0) GRANULARITY 1
) ENGINE = CnchMergeTree ORDER BY (tm) SETTINGS index_granularity_bytes = 50, min_index_granularity_bytes = 40;
SYSTEM START MERGES indexed_table;
INSERT INTO indexed_table SELECT toDateTime('2019-05-27 10:00:00') + number % 100, 'h' FROM numbers(1000);
INSERT INTO indexed_table
SELECT
toDateTime('2019-05-27 10:00:00') + number % 100,
concat('hhhhhhhhhhhhhhhhhhhhhhhhh', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyyy', toString(rand()))
FROM numbers(1000);
OPTIMIZE TABLE indexed_table SETTINGS mutations_sync = 1;
SELECT COUNT() FROM indexed_table WHERE log_message like '%x%';
DROP TABLE IF EXISTS indexed_table;
DROP TABLE IF EXISTS another_indexed_table;
CREATE TABLE another_indexed_table
( `tm` DateTime,
`log_message` String,
INDEX log_message log_message TYPE tokenbf_v1(4096, 2, 0) GRANULARITY 1
) ENGINE = CnchMergeTree ORDER BY (tm) SETTINGS
vertical_merge_algorithm_min_rows_to_activate = 0,
vertical_merge_algorithm_min_columns_to_activate = 0,
index_granularity_bytes = 50,
min_index_granularity_bytes = 40;
SYSTEM START MERGES another_indexed_table;
INSERT INTO another_indexed_table SELECT toDateTime('2019-05-27 10:00:00') + number % 100, 'h' FROM numbers(1000);
INSERT INTO another_indexed_table
SELECT
toDateTime('2019-05-27 10:00:00') + number % 100,
concat('hhhhhhhhhhhhhhhhhhhhhhhhh', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyyy', toString(rand()))
FROM numbers(1000);
OPTIMIZE TABLE another_indexed_table SETTINGS mutations_sync = 1;
SELECT COUNT() FROM another_indexed_table WHERE log_message like '%x%';
DROP TABLE IF EXISTS another_indexed_table;
|
Java
|
UTF-8
| 4,878
| 2.359375
| 2
|
[] |
no_license
|
/**
*
*/
package com.googlecode.brainfuck4j;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import com.google.code.brainfuck4j.model.brainfuck.BrainfuckFactory;
import com.google.code.brainfuck4j.model.brainfuck.Instruction;
import com.google.code.brainfuck4j.model.brainfuck.Program;
/**
* @author a108600
*
*/
public class ModelTransformVisitor implements BrainfuckVisitor {
private static BrainfuckFactory factory = BrainfuckFactory.eINSTANCE;
private static Map<String, Instruction> instructionMap = new HashMap<String, Instruction>();
private Map<Node, EObject> nodes = new HashMap<Node, EObject>();
private Program root;
static {
instructionMap.put("+", Instruction.INC_VALUE);
instructionMap.put("-", Instruction.DEC_VALUE);
instructionMap.put(">", Instruction.INC_POINTER);
instructionMap.put("<", Instruction.DEC_POINTER);
instructionMap.put(".", Instruction.OUTPUT);
instructionMap.put(",", Instruction.INPUT);
}
/**
*
*/
public ModelTransformVisitor() {
super();
}
/**
* @return the root
*/
public Program getRoot() {
return root;
}
@Override
public Object visit(SimpleNode node, Object data) {
throw new IllegalArgumentException(
"Invalid node type encountered. Is there no subclass accessor?:"
+ node.getClass().getCanonicalName());
}
@Override
public Object visit(ASTStart node, Object data) {
Program program = factory.createProgram();
nodes.put(node, program);
this.root = program;
data = node.childrenAccept(this, data);
return data;
}
@Override
public Object visit(Header node, Object data) {
com.google.code.brainfuck4j.model.brainfuck.ProgramHeader header = factory
.createProgramHeader();
Program program = getParent(node, Program.class);
program.setHeader(header);
nodes.put(node, header);
data = node.childrenAccept(this, data);
return data;
}
@Override
public Object visit(ProgramHeader node, Object data) {
com.google.code.brainfuck4j.model.brainfuck.ProgramHeader header = getParent(
node,
com.google.code.brainfuck4j.model.brainfuck.ProgramHeader.class);
header.setName(node.getName());
data = node.childrenAccept(this, data);
return data;
}
@Override
public Object visit(HeapHeader node, Object data) {
com.google.code.brainfuck4j.model.brainfuck.ProgramHeader header = getParent(
node,
com.google.code.brainfuck4j.model.brainfuck.ProgramHeader.class);
header.setHeap(Integer.parseInt(node.getSize()));
data = node.childrenAccept(this, data);
return data;
}
@Override
public Object visit(Expression node, Object data) {
data = node.childrenAccept(this, data);
return data;
}
@Override
public Object visit(UnaryExpression node, Object data) {
com.google.code.brainfuck4j.model.brainfuck.UnaryExpression expr = factory
.createUnaryExpression();
String instrStr = node.getInstruction();
Instruction instr = instructionMap.get(instrStr);
if (instr == null) {
throw new IllegalArgumentException("Unknown instruction type encountered:" + instrStr);
}
expr.setInstruction(instr);
addToParentExpressionList(node, expr);
data = node.childrenAccept(this, data);
return data;
}
@Override
public Object visit(BlockExpression node, Object data) {
com.google.code.brainfuck4j.model.brainfuck.BlockExpression expr = factory
.createBlockExpression();
addToParentExpressionList(node, expr);
nodes.put(node, expr);
data = node.childrenAccept(this, data);
return data;
}
private void addToParentExpressionList(Node node,
com.google.code.brainfuck4j.model.brainfuck.Expression expr) {
EObject parent = getParent(node.jjtGetParent(), EObject.class);
EList<com.google.code.brainfuck4j.model.brainfuck.Expression> exprList;
if (parent instanceof Program) {
Program program = (Program) parent;
exprList = program.getExpressions();
} else if (parent instanceof com.google.code.brainfuck4j.model.brainfuck.BlockExpression) {
com.google.code.brainfuck4j.model.brainfuck.BlockExpression block = (com.google.code.brainfuck4j.model.brainfuck.BlockExpression) parent;
exprList = block.getExpressions();
} else {
throw new IllegalArgumentException(
"Invalid parent type encountered for a expression node:"
+ parent.getClass().getCanonicalName());
}
exprList.add(expr);
}
private <T extends EObject> T getParent(Node node, Class<T> type) {
EObject parent = nodes.get(node.jjtGetParent());
if (parent == null) {
throw new IllegalArgumentException("The parent could not be found");
}
if (!type.isInstance(parent)) {
throw new IllegalArgumentException("The parent "
+ parent.getClass().getCanonicalName()
+ "is not of the expected type:" + type.getCanonicalName());
}
return (T) parent;
}
}
|
Go
|
UTF-8
| 848
| 3.46875
| 3
|
[] |
no_license
|
package day06
import "fmt"
type banks []int
func (b banks) max() (int, int) {
maxIdx := 0
max := b[0]
for i := 1; i < len(b); i++ {
if b[i] > max {
max = b[i]
maxIdx = i
}
}
return maxIdx, max
}
func (b banks) redistribute() {
idx, val := b.max()
b[idx] = 0
idx = (idx + 1) % len(b)
for ; val > 0; val-- {
b[idx]++
idx = (idx + 1) % len(b)
}
}
func (b banks) String() string {
return fmt.Sprintf("%v", []int(b))
}
func solve(b banks) {
steps := 0
set := make(map[string]int)
seen := func(s string) bool {
_, ok := set[s]
return ok
}
for !seen(b.String()) {
set[b.String()] = steps
b.redistribute()
steps++
}
fmt.Println("Part A", steps)
fmt.Println("Part B", steps-set[b.String()])
}
func Solve() {
input := []int{10, 3, 15, 10, 5, 15, 5, 15, 9, 2, 5, 8, 5, 2, 3, 6}
solve(banks(input))
}
|
Markdown
|
UTF-8
| 1,148
| 3.640625
| 4
|
[] |
no_license
|
---
title: leetCode-7-整数反转
date: 2021-04-29 19:45:18
tags:
- 算法
---
*原题链接:👉:[整数反转](https://leetcode-cn.com/problems/reverse-integer/)*
题目描述:
1. 给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
2. 如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
3. 假设环境不允许存储 64 位整数(有符号或无符号)
示例:
```
输入:x = 123
输出:321
```
示例:
```
输入:x = -123
输出:-321
```
示例:
```
输入:x = 120
输出:21
```
<!--more-->
思路
> 取一个数,加一个数,并且判断是否小于限制值,大于最大最小?
- 解答
根据题意解即可,注意大小的判断
```
var reverse = function(x) {
let res = 0;
while(x) {
let unitNum = x % 10;
res = res * 10 + unitNum;
if(res > Math.pow(2, 31) - 1 || res < Math.pow(-2, 31)) {
return 0;
}
if(x <= 0) {
x = Math.ceil(x / 10);
} else {
x = Math.floor(x / 10);
}
}
return res;
}
```
|
Ruby
|
UTF-8
| 825
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
t = gets.to_i
i = 0
while i < t do
g = gets.to_i
j = 1
while j <= g do
inp = gets.chomp
inps = inp.split()
i = inps[0].to_i # 1 means all head 2 tail
n = inps[1].to_i # number of rounds
q = inps[2].to_i # 1 head 2 tail
if q == 1
if i == 1
puts (n/2)
else
if n % 2 == 0
puts (n/2)
else
puts n-(n/2)
end
end
else
if i == 1
if n % 2 == 0
puts (n/2)
else
puts n-(n/2)
end
else
puts (n/2)
end
end
j += 1
end
i += 1
end
|
Java
|
UTF-8
| 958
| 1.914063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.kestra.core.models.listeners;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.micronaut.core.annotation.Introspected;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.kestra.core.models.executions.Execution;
import org.kestra.core.models.flows.Flow;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.function.BiPredicate;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type", visible = true, include = JsonTypeInfo.As.EXISTING_PROPERTY)
@SuperBuilder
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Introspected
public abstract class Condition implements BiPredicate<Flow, Execution> {
@NotNull
@Pattern(regexp="\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*(\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)*")
protected String type;
}
|
Python
|
UTF-8
| 29,338
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
"""
Particular class of two intersections traffic network
@author: Romain Michelucci
"""
import configparser
import logging
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
import seaborn as sns
import time
from envs.env import PhaseMap, PhaseSet, TrafficSimulator
import math
import matplotlib.pyplot as plt
import scipy.stats
sns.set_color_codes()
SMALL_GRID_NEIGHBOR_MAP = {'TL': ['2_TL'],
'2_TL': ['TL']}
STATE_NAMES = ['wave', 'wait']
STATE_PHASE_MAP = {'TL': [0], '2_TL': [0]}
PHASE_NUM = 4
class TwoGridPhase(PhaseMap):
def __init__(self):
phases = ['GGGGrrrrrrGGGGrrrrrr',
'rrrrGrrrrrrrrrGrrrrr',
'rrrrrGGGGrrrrrrGGGGr',
'rrrrrrrrrGrrrrrrrrrG',
]
self.phases = {PHASE_NUM: PhaseSet(phases)}
class TwoGridController:
def __init__(self, node_names):
self.name = 'greedy'
self.node_names = node_names
def forward(self, obs):
actions = []
for ob, node_name in zip(obs, self.node_names):
actions.append(self.greedy(ob, node_name))
return actions
def greedy(self, ob, node_name):
# hard code the mapping from state to number of cars
phases = STATE_PHASE_MAP[node_name]
flows = ob[:len(phases)]
return phases[np.argmax(flows)]
class TwoGridEnv(TrafficSimulator):
def __init__(self, config, port=0, output_path='', is_record=False, record_stat=False):
self.num_car_hourly = config.getint('num_extra_car_per_hour')
self._TrafficGen = TrafficGenerator(
3600,
self.num_car_hourly
)
super().__init__(config, output_path, is_record, record_stat, port=port)
def _get_node_phase_id(self, node_name):
return PHASE_NUM
def _init_map(self):
self.neighbor_map = SMALL_GRID_NEIGHBOR_MAP
self.phase_map = TwoGridPhase()
self.state_names = STATE_NAMES
def _init_sim_config(self, seed):
# return gen_rou_file(seed=seed,
# thread=self.sim_thread,
# path=self.data_path,
# num_car_hourly=self.num_car_hourly)
##GENERATE TRAFFIC HERE
self._TrafficGen.generate_routefile(seed=seed)
return self.data_path + 'exp.sumocfg'
def plot_stat(self, rewards):
self.state_stat['reward'] = rewards
for name, data in self.state_stat.items():
fig = plt.figure(figsize=(8, 6))
plot_cdf(data)
plt.ylabel(name)
fig.savefig(self.output_path + self.name + '_' + name + '.png')
class TrafficGenerator:
def __init__(self, max_steps, n_cars_generated, scenario=None):
self._n_cars_generated = n_cars_generated # how many cars per episode
self._max_steps = max_steps
self._scenario = scenario
def generate_routefile(self, seed):
"""
Generation of the route of every car for one episode
"""
np.random.seed(seed) # make tests reproducible
# the generation of cars is distributed according to a weibull distribution
timings = np.random.weibull(2, self._n_cars_generated)
timings = np.sort(timings)
# reshape the distribution to fit the interval 0:max_steps
car_gen_steps = []
min_old = math.floor(timings[1])
max_old = math.ceil(timings[-1])
min_new = 0
max_new = self._max_steps
for value in timings:
car_gen_steps = np.append(car_gen_steps, ((max_new - min_new) / (max_old - min_old)) * (value - max_old) + max_new)
car_gen_steps = np.rint(car_gen_steps) # round every value to int -> effective steps when a car will be generated
mean = 2000
standard_deviation = 1500
#x_values = np.arange(0, 5400, 1)
y_values = scipy.stats.norm(mean, standard_deviation)
#print(y_values)
#plt.plot(car_gen_steps, y_values.pdf(car_gen_steps)*100000)
# produce the file for cars generation, one car per line
with open("two_grid/data/exp.rou.xml", "w") as routes:
print("""<routes>
<vType accel="1.0" decel="4.5" id="standard_car" length="5.0" minGap="2.5" maxSpeed="25" sigma="0.5" />
<route id="W_N" edges="W2TL TL2N"/>
<route id="W_2_N" edges="W2TL TL2E 2_TL2N"/>
<route id="W_E" edges="W2TL TL2E 2_TL2E"/>
<route id="W_S" edges="W2TL TL2S"/>
<route id="W_2_S" edges ="W2TL TL2E 2_TL2S"/>
<route id="N_W" edges="N2TL TL2W"/>
<route id="N_E" edges="N2TL TL2E 2_TL2E"/>
<route id="N_S" edges="N2TL TL2S"/>
<route id="N_2_S" edges="N2TL TL2E 2_TL2S" />
<route id="N_2_N" edges="N2TL TL2E 2_TL2N" />
<route id="S_W" edges="S2TL TL2W"/>
<route id="S_N" edges="S2TL TL2N"/>
<route id="S_2_N" edges="S2TL TL2E 2_TL2N" />
<route id="S_E" edges="S2TL TL2E 2_TL2E"/>
<route id="S_2_S" edges="S2TL TL2E 2_TL2S" />
<route id="E_W" edges="2_E2TL 2_TL2W TL2W"/>
<route id="E_N" edges="2_E2TL 2_TL2W TL2N"/>
<route id="E_S" edges="2_E2TL 2_TL2W TL2S"/>
<route id="E_2_N" edges="2_E2TL 2_TL2N" />
<route id="E_2_S" edges="2_E2TL 2_TL2S" />
<route id="2_N_E" edges="2_N2TL 2_TL2E" />
<route id="2_N_2_S" edges="2_N2TL 2_TL2S" />
<route id="2_N_W" edges="2_N2TL 2_TL2W TL2W" />
<route id="2_N_N" edges="2_N2TL 2_TL2W TL2N" />
<route id="2_N_S" edges="2_N2TL 2_TL2W TL2S" />
<route id="2_S_E" edges="2_S2TL 2_TL2E" />
<route id="2_S_2_N" edges="2_S2TL 2_TL2N" />
<route id="2_S_W" edges="2_S2TL 2_TL2W TL2W" />
<route id="2_S_N" edges="2_S2TL 2_TL2W TL2N" />
<route id="2_S_S" edges="2_S2TL 2_TL2W TL2S" />
""", file=routes)
#Determine the coming percentage depending on the scenario -> EW 90% - 10% (inverse of NS)
#And calibrate the percentage of artificial queues
if (self._scenario == 'EW'):
coming_from_percentage = 0.90
factor_artificial_queue_ew = 0.5
factor_artificial_queue_ns = 1
elif (self._scenario== 'NS'):
coming_from_percentage = 0.10
factor_artificial_queue_ew = 1
factor_artificial_queue_ns = 0.5
else:
factor_artificial_queue_ew = 0.5
factor_artificial_queue_ns = 0.5
for car_counter, step in enumerate(car_gen_steps):
#Random output lane
random_out_lane = np.random.randint(0,4)
artificial_queue_ew = factor_artificial_queue_ew * y_values.pdf(car_gen_steps)[car_counter]*100000
artificial_queue_ns = factor_artificial_queue_ns * y_values.pdf(car_gen_steps)[car_counter]*100000
#EW or NS scenario
if(self._scenario == 'EW' or self._scenario == 'NS'): #EW or NS traffic scenario
#NS or EW
axis_direction = np.random.uniform()
#Straight or turn
straight_or_turn = np.random.uniform()
### The idea whith this new scenario is turn or straight *AT FIRST JUNCTION*
#90% coming from the North or South arm for NS scenario or 10% from the North or South for EW scenario
#E-W
if axis_direction < coming_from_percentage :
#Vehicles through central lane
if straight_or_turn < 0.75:
route_straight = np.random.randint(1, 7)
if route_straight == 1:
print(' <vehicle id="W_E_%i" type="standard_car" route="W_E" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_straight == 2:
print(' <vehicle id="E_W_%i" type="standard_car" route="E_W" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_straight == 3:
print(' <vehicle id="E_N_%i" type="standard_car" route="E_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 4:
print(' <vehicle id="E_S_%i" type="standard_car" route="E_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 5:
print(' <vehicle id="W_2_N_%i" type="standard_car" route="W_2_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 6:
print(' <vehicle id="W_2_S_%i" type="standard_car" route="W_2_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
#Vehicles not through central lane
else:
route_turn = np.random.randint(1, 5)
if route_turn == 1:
print(' <vehicle id="W_N_%i" type="standard_car" route="W_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 2:
print(' <vehicle id="W_S_%i" type="standard_car" route="W_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 3:
print(' <vehicle id="E_2_N_%i" type="standard_car" route="E_2_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 4:
print(' <vehicle id="E_2_S_%i" type="standard_car" route="E_2_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
#N-S
else:
if straight_or_turn < 0.75:
route_straight = np.random.randint(1, 5)
if route_straight == 1:
print(' <vehicle id="N_S_%i" type="standard_car" route="N_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 2:
print(' <vehicle id="S_N_%i" type="standard_car" route="S_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 3:
print(' <vehicle id="2_N_2_S_%i" type="standard_car" route="2_N_2_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 4:
print(' <vehicle id="2_S_2_N_%i" type="standard_car" route="2_S_2_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
else:
route_turn = np.random.randint(1, 17)
if route_turn == 1:
print(' <vehicle id="S_W_%i" type="standard_car" route="S_W" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 2:
print(' <vehicle id="S_E_%i" type="standard_car" route="S_E" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 3:
print(' <vehicle id="S_2_N_%i" type="standard_car" route="S_2_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 4:
print(' <vehicle id="S_2_S_%i" type="standard_car" route="S_2_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 5:
print(' <vehicle id="N_W_%i" type="standard_car" route="N_W" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 6:
print(' <vehicle id="N_E_%i" type="standard_car" route="N_E" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 7:
print(' <vehicle id="N_2_N_%i" type="standard_car" route="N_2_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 8:
print(' <vehicle id="N_2_S_%i" type="standard_car" route="N_2_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 9:
print(' <vehicle id="2_S_W_%i" type="standard_car" route="2_S_W" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 10:
print(' <vehicle id="2_S_E_%i" type="standard_car" route="2_S_E" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 11:
print(' <vehicle id="2_S_N_%i" type="standard_car" route="2_S_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 12:
print(' <vehicle id="2_S_S_%i" type="standard_car" route="2_S_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 13:
print(' <vehicle id="2_N_W_%i" type="standard_car" route="2_N_W" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 14:
print(' <vehicle id="2_N_E_%i" type="standard_car" route="2_N_E" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 15:
print(' <vehicle id="2_N_N_%i" type="standard_car" route="2_N_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 16:
print(' <vehicle id="2_N_S_%i" type="standard_car" route="2_N_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
# Low or High scenario
else :
straight_or_turn = np.random.uniform()
if straight_or_turn < 0.75: # choose direction: straight or turn - 75% of times the car goes straight
route_straight = np.random.randint(1, 11) # choose a random source & destination
if route_straight == 1:
print(' <vehicle id="W_E_%i" type="standard_car" route="W_E" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_straight == 2:
print(' <vehicle id="W_2_N_%i" type="standard_car" route="W_2_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 3:
print(' <vehicle id="W_2_S_%i" type="standard_car" route="W_2_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 4:
print(' <vehicle id="E_W_%i" type="standard_car" route="E_W" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_straight == 5:
print(' <vehicle id="E_N_%i" type="standard_car" route="E_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 6:
print(' <vehicle id="E_S_%i" type="standard_car" route="E_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 7:
print(' <vehicle id="N_S_%i" type="standard_car" route="N_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 8:
print(' <vehicle id="S_N_%i" type="standard_car" route="S_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 9:
print(' <vehicle id="2_N_2_S_%i" type="standard_car" route="2_N_2_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_straight == 10:
print(' <vehicle id="2_S_2_N_%i" type="standard_car" route="2_S_2_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
else: # car that turn -25% of the time the car turns
route_turn = np.random.randint(1, 21) # choose a random source & destination
if route_turn == 1:
print(' <vehicle id="W_N_%i" type="standard_car" route="W_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 2:
print(' <vehicle id="W_S_%i" type="standard_car" route="W_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 3:
print(' <vehicle id="N_W_%i" type="standard_car" route="N_W" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 4:
print(' <vehicle id="N_E_%i" type="standard_car" route="N_E" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 5:
print(' <vehicle id="N_2_N_%i" type="standard_car" route="N_2_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 6:
print(' <vehicle id="N_2_S_%i" type="standard_car" route="N_2_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 7:
print(' <vehicle id="E_2_N_%i" type="standard_car" route="E_2_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 8:
print(' <vehicle id="E_2_S_%i" type="standard_car" route="E_2_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 9:
print(' <vehicle id="S_W_%i" type="standard_car" route="S_W" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 10:
print(' <vehicle id="S_E_%i" type="standard_car" route="S_E" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 11:
print(' <vehicle id="S_2_N_%i" type="standard_car" route="S_2_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 12:
print(' <vehicle id="S_2_S_%i" type="standard_car" route="S_2_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 13:
print(' <vehicle id="2_N_W_%i" type="standard_car" route="2_N_W" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 14:
print(' <vehicle id="2_N_E_%i" type="standard_car" route="2_N_E" depart="%s" departLane="random" departSpeed="10" > <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 15:
print(' <vehicle id="2_N_N_%i" type="standard_car" route="2_N_N" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 16:
print(' <vehicle id="2_N_S_%i" type="standard_car" route="2_N_S" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 17:
print(' <vehicle id="2_S_W_%i" type="standard_car" route="2_S_W" depart="%s" departLane="random" departSpeed="10"> <stop lane="TL2W_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 18:
print(' <vehicle id="2_S_E_%i" type="standard_car" route="2_S_E" depart="%s" departLane="random" departSpeed="10"> <stop lane="2_TL2E_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ew), file=routes)
elif route_turn == 19:
print(' <vehicle id="2_S_N_%i" type="standard_car" route="2_S_N" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2N_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
elif route_turn == 20:
print(' <vehicle id="2_S_S_%i" type="standard_car" route="2_S_S" depart="%s" departLane="random" departSpeed="10" > <stop lane="TL2S_%i" endPos="750" duration="%i"/> </vehicle>' % (car_counter, step, random_out_lane, artificial_queue_ns), file=routes)
print("</routes>", file=routes)
|
C#
|
UTF-8
| 824
| 3.046875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WFSample1
{
/// <summary>
/// Базовый класс космических объектов
/// </summary>
class SpaseObject
{
protected Point Pos;
protected Point Dir;
public SpaseObject(Point pos, Point dir)
{
Pos = pos;
Dir = dir;
}
/// <summary>
/// Метод отрисовки объекта
/// </summary>
public virtual void Draw()
{
}
/// <summary>
/// Метод обновления положения объекта
/// </summary>
public virtual void Update()
{
}
}
}
|
Java
|
UTF-8
| 8,426
| 2.453125
| 2
|
[] |
no_license
|
package com.implemica.CurrencyConverter.controller;
import com.implemica.CurrencyConverter.model.ConvertStep;
import com.implemica.CurrencyConverter.model.State;
import com.implemica.CurrencyConverter.model.User;
import com.implemica.CurrencyConverter.service.BotService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.*;
import static com.implemica.CurrencyConverter.model.ConvertStep.*;
import static java.lang.Math.toIntExact;
/**
* This class gets Users input from telegram bot and processes it via Converter class
*
* @author Daria S.
* @version 31.01.2019 16:32
* @see BotService
*/
@Component
public class BotController extends TelegramLongPollingBot {
/**
* Bot name in Telegram.
*/
@Value("${telegram.botName}")
private String BOT_NAME;
/**
* It uses for getting and sending messages via Bot API
*/
@Value("${telegram.botToken}")
private String BOT_TOKEN;
/**
* Logger for this class
*/
private Logger logger = LoggerFactory.getLogger(BotController.class.getName());
/**
* Unique string, which uses for identification messages, which has non-text content.
*/
private static final String UNIQUE = BotService.WRONG_CONTENT;
/**
* Logic of bot, how it processes user's input.
*/
private final BotService bot;
/**
* Sender messages to user
*/
private SendMessage sendMessage;
/**
* Id of chat
*/
private long chatId;
/**
* Stores users and id chats, where they communicate with bot
*/
private static Map<User, Long> listOfChats = State.listOfChats;
/**
* Stores users states
*/
private static Map<Integer, State> usersStates = State.statesOfUsers;
/**
* Creates new telegram bot's controller
*
* @param bot stores bot's logic
*/
@Autowired
public BotController(BotService bot) {
this.bot = bot;
sendMessage = new SendMessage();
}
/**
* Gets Users input and processes it. Writes conversation to storage
*
* @param update represents an incoming update from Telegram
*/
@Override
public void onUpdateReceived(Update update) {
Message message;
User user;
String command;
boolean isBot = false;
if (update.hasMessage()) {
message = update.getMessage();
command = getCommand(message);
} else {
CallbackQuery callbackQuery = update.getCallbackQuery();
command = callbackQuery.getData();
message = callbackQuery.getMessage();
long message_id = message.getMessageId();
chatId = message.getChatId();
isBot = true;
String answer = "You chose " + command;
sendEditMessage(message_id, answer);
}
user = getInformationAboutUser(message);
if (isBot) {
user = chooseUser(user);
}
String response = bot.processCommand(command, user);
sendMessage(message, response);
int userId = user.getUserId();
ConvertStep step = getStep(userId);
if (step.equals(FIRST) || step.equals(SECOND)) {
SendMessage s = new SendMessage().setChatId(chatId).setText("You can choose popular currencies: ");
createKeyboard(s);
}
listOfChats.put(user, chatId);
}
/**
* Returns command to processing
*
* @param message incoming message
* @return String command, which has to be obtained by BotService
*/
private String getCommand(Message message) {
String command;
chatId = message.getChatId();
if (message.hasText()) {
command = message.getText();
} else {
command = UNIQUE;
}
return command;
}
/**
* @return bot's name in Telegram
*/
@Override
public String getBotUsername() {
return BOT_NAME;
}
/**
* @return bot's token in Telegram
*/
@Override
public String getBotToken() {
return BOT_TOKEN;
}
/**
* Sends message to user in Telegram
*
* @param request represents an incoming message from Telegram
* @param response message, which has to be sent to user
*/
private void sendMessage(Message request, String response) {
sendMessage.setText(response);
sendMessage.setChatId(request.getChatId());
try {
execute(sendMessage);
} catch (TelegramApiException e) {
logger.error(e.getMessage());
}
}
/**
* Changes message's text to specified
*
* @param messageId id if message, which has to be changed
* @param text new text of message
*/
private void sendEditMessage(long messageId, String text) {
EditMessageText new_message = new EditMessageText()
.setChatId(chatId)
.setMessageId(toIntExact(messageId))
.setText(text);
try {
execute(new_message);
} catch (TelegramApiException e) {
logger.error(e.getMessage());
}
}
/**
* User initialisation: id, name, last name, userName.
*
* @param message represents an incoming message from Telegram
* @return new User
*/
User getInformationAboutUser(Message message) {
org.telegram.telegrambots.meta.api.objects.User telegramUser = message.getFrom();
int userId = telegramUser.getId();
String userFirstName = telegramUser.getFirstName();
String userLastName = telegramUser.getLastName();
String userName = telegramUser.getUserName();
User user;
if (userName == null || userLastName == null) {
user = new User(userId, userFirstName);
if (userName != null) {
user.setUserName(userName);
}
if (userLastName != null) {
user.setUserLastName(userLastName);
}
} else {
user = new User(userId, userFirstName, userLastName, userName);
}
return user;
}
/**
* Create inline keyboard with popular currencies
*
* @param sendMessage new sender messages to user
*/
private void createKeyboard(SendMessage sendMessage) {
List<List<InlineKeyboardButton>> buttons = new ArrayList<>();
List<InlineKeyboardButton> row = new ArrayList<>();
row.add(new InlineKeyboardButton().setText("USD").setCallbackData("USD"));
row.add(new InlineKeyboardButton().setText("EUR").setCallbackData("EUR"));
row.add(new InlineKeyboardButton().setText("BTC").setCallbackData("BTC"));
row.add(new InlineKeyboardButton().setText("UAH").setCallbackData("UAH"));
buttons.add(row);
InlineKeyboardMarkup markupKeyboard = new InlineKeyboardMarkup();
markupKeyboard.setKeyboard(buttons);
sendMessage.setReplyMarkup(markupKeyboard);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
logger.error(e.getMessage());
}
}
/**
* Finds user, who talk to bot
*
* @param user bot user
* @return the user who is in the same chat
*/
private User chooseUser(User user) {
Set<Map.Entry<User, Long>> entrySet = listOfChats.entrySet();
for (Map.Entry<User, Long> pair : entrySet) {
long id = pair.getValue();
if (chatId == id) {
user = pair.getKey();
}
}
return user;
}
/**
* Finds User by their key and gets their conversion step
*
* @param id users id
* @return step of conversion for given user
*/
private ConvertStep getStep(int id) {
State state = usersStates.get(id);
return state.getConvertStep();
}
}
|
Python
|
UTF-8
| 1,796
| 2.984375
| 3
|
[] |
no_license
|
_users = {
'paul': {
'name': 'Pavel Okopnyi',
'fav_categories': 'Ужасы',
'own_books': 'book184637'
},
'igor': {
'name': 'Igor Novikov',
'fav_categories': 'Научная фантастика',
'own_books': 'book407836'
},
'boris': {
'name': 'Boris Ivanov',
'fav_categories': 'Триллер',
'own_books': 'book846339'
},
'alena': {
'name': 'Alena Popova',
'fav_categories': 'Научная литература',
'own_books': 'book899111',
},
'tom': {
'name': 'Tom Riddle',
'fav_categories': 'Драма',
'own_books': 'book189007'
},
' alex': {
'name': 'Alex Smith',
'fav_categories': 'Биография',
'own_books': 'book503255'
},
'ivan': {
'name': 'Ivan Borisov',
'fav_categories': 'Детектив',
'own_books': 'book846009'
},
'anna': {
'name': 'Anna Karenina',
'fav_categories': 'Драма',
'own_books': 'book9346613'
},
'jack': {
'name': 'Jack Potter',
'fav_categories': ['Фантастика', 'Поэзия'],
'own_books': 'book870839'
},
'alexander': {
'name': 'Alexander Petrov',
'fav_categories': 'Любовный роман',
'own_books': 'book992303',
}
}
_user_list = []
for login, user_data in _users.items():
_new_element = {'login': login}
_new_element.update(user_data)
_user_list.append(_new_element)
# Get users filtered by name
def get_users_by_name(q):
results = []
# SEARCH
for user in _user_list:
if q.lower() in user['name'].lower():
results.append(user)
return results
def get_user(username):
return _users.get(username)
|
Python
|
UTF-8
| 538
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import discord
import json
bot = discord.Bot()
with open("conf.json", "r") as conf:
data = json.load(conf)
token = data["token"]
pref = data["pref"]
# Slash Commands
@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")
# Message Commands
@bot.user_command(name="Come here boi!")
async def cu(ctx, user):
await ctx.respond(f"Yes?")
# Normal Commands
@bot.command()
async def ping(ctx):
await ctx.send("pong")
bot.run(token)
|
PHP
|
UTF-8
| 200
| 2.59375
| 3
|
[] |
no_license
|
<?php
if (!isset ($_GET['suc'])) {
$suc = 0;
} else {
$suc = $_GET['suc'];
}
if ($suc == 1) {
echo "Thank you for your message!</br> Your message was send on: ", date("F j, Y, g:i a");
}
|
JavaScript
|
UTF-8
| 2,441
| 2.5625
| 3
|
[] |
no_license
|
const { prompt } = require('inquirer')
require('console.table')
const mysql = require('mysql2')
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '621120?Jfjjfz',
database: 'employee_db'
})
const Questions = require('../index')
const Managers = () => {
const viewManagers = () => {
db.query('SELECT * FROM manager', (err, managers) => {
if (err) { console.log(err) }
console.table(managers)
})
}
viewManagers()
const Add = () => {
prompt([
{
type: 'input',
name: 'name',
message: "What is the name of the manager ?"
}
])
.then(res => {
db.query('INSERT INTO manager SET ?', res, err => {
if (err) { console.log(err) }
console.log('Manager Created!')
Managers()
})
})
.catch(err => { console.log(err) })
}
const Delete = () => {
db.query('SELECT * FROM manager', (err, managers) => {
if (err) { console.log(err) }
managers = managers.map(manager => ({
name: manager.name,
value: manager.id
}))
prompt([
{
type: 'list',
name: 'name',
message: "Which manager would you like to delete ?",
choices: managers
},
{
type: 'list',
name: 'final',
message: "Please confirm to delete.",
choices: ["Yes, please delete", "No, please go back"]
}
])
.then(res => {
switch (res.final) {
case "Yes, please delete":
db.query('DELETE FROM manager WHERE id = ?', res.name, err => {
if (err) { console.log(err) }
Managers()
})
break
case "No, please go back":
Managers()
break
}
})
.catch(err => console.log(err))
})
}
prompt([
{
type: 'list',
name: 'action',
message: "What would you like to do ?",
choices: ["Add", "Delete", "Main Menu"]
}
])
.then(({ action }) => {
switch (action) {
case 'Add':
Add()
break;
case 'Delete':
Delete()
break;
case 'Main Menu':
Questions()
break;
}
})
.catch(err => { console.log(err) })
}
module.exports = Managers
|
Java
|
UTF-8
| 10,355
| 2.109375
| 2
|
[] |
no_license
|
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.testutils;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.openstreetmap.josm.JOSMFixture;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.projection.Projections;
import org.openstreetmap.josm.gui.util.GuiHelper;
import org.openstreetmap.josm.io.OsmApi;
import org.openstreetmap.josm.io.OsmApiInitializationException;
import org.openstreetmap.josm.io.OsmTransferCanceledException;
import org.openstreetmap.josm.tools.I18n;
import org.openstreetmap.josm.tools.Logging;
import org.openstreetmap.josm.tools.date.DateUtils;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.TimeZone;
/**
* This class runs a test in an environment that resembles the one used by the JOSM main application.
* <p>
* The environment is reset before every test. You can specify the components to which you need access using the methods of this class.
* For example, invoking {@link #preferences()} gives you access to the (default) preferences.
*
* @author Michael Zangl
*/
public class JOSMTestRules implements TestRule {
private int timeout = 10 * 1000;
private TemporaryFolder josmHome;
private boolean usePreferences = false;
private APIType useAPI = APIType.NONE;
private String i18n = null;
private boolean platform;
private boolean useProjection;
private boolean commands;
private boolean allowMemoryManagerLeaks;
/**
* Disable the default timeout for this test. Use with care.
* @return this instance, for easy chaining
*/
public JOSMTestRules noTimeout() {
timeout = -1;
return this;
}
/**
* Set a timeout for all tests in this class. Local method timeouts may only reduce this timeout.
* @param millis The timeout duration in milliseconds.
* @return this instance, for easy chaining
*/
public JOSMTestRules timeout(int millis) {
timeout = millis;
return this;
}
/**
* Enable the use of default preferences.
* @return this instance, for easy chaining
*/
public JOSMTestRules preferences() {
josmHome();
usePreferences = true;
return this;
}
/**
* Set JOSM home to a valid, empty directory.
* @return this instance, for easy chaining
*/
private JOSMTestRules josmHome() {
josmHome = new TemporaryFolder();
return this;
}
/**
* Enables the i18n module for this test in english.
* @return this instance, for easy chaining
*/
public JOSMTestRules i18n() {
return i18n("en");
}
/**
* Enables the i18n module for this test.
* @param language The language to use.
* @return this instance, for easy chaining
*/
public JOSMTestRules i18n(String language) {
i18n = language;
return this;
}
/**
* Enable {@link Main#platform} global variable.
* @return this instance, for easy chaining
*/
public JOSMTestRules platform() {
platform = true;
return this;
}
/**
* Enable the dev.openstreetmap.org API for this test.
* @return this instance, for easy chaining
*/
public JOSMTestRules devAPI() {
preferences();
useAPI = APIType.DEV;
return this;
}
/**
* Use the {@link FakeOsmApi} for testing.
* @return this instance, for easy chaining
*/
public JOSMTestRules fakeAPI() {
useAPI = APIType.FAKE;
return this;
}
/**
* Set up default projection (Mercator)
* @return this instance, for easy chaining
*/
public JOSMTestRules projection() {
useProjection = true;
return this;
}
/**
* Allow the execution of commands using {@link Main#undoRedo}
* @return this instance, for easy chaining
*/
public JOSMTestRules commands() {
commands = true;
return this;
}
/**
* Allow the memory manager to contain items after execution of the test cases.
* @return this instance, for easy chaining
*/
public JOSMTestRules memoryManagerLeaks() {
allowMemoryManagerLeaks = true;
return this;
}
@Override
public Statement apply(Statement base, Description description) {
Statement statement = base;
if (timeout > 0) {
// TODO: new DisableOnDebug(timeout)
statement = new FailOnTimeoutStatement(statement, timeout);
}
statement = new CreateJosmEnvironment(statement);
if (josmHome != null) {
statement = josmHome.apply(statement, description);
}
return statement;
}
/**
* Set up before running a test
* @throws InitializationError If an error occured while creating the required environment.
*/
protected void before() throws InitializationError {
// Tests are running headless by default.
System.setProperty("java.awt.headless", "true");
cleanUpFromJosmFixture();
// All tests use the same timezone.
TimeZone.setDefault(DateUtils.UTC);
// Set log level to info
Logging.setLogLevel(Logging.LEVEL_INFO);
// Set up i18n
if (i18n != null) {
I18n.set(i18n);
}
// Add JOSM home
if (josmHome != null) {
try {
File home = josmHome.newFolder();
System.setProperty("josm.home", home.getAbsolutePath());
} catch (IOException e) {
throw new InitializationError(e);
}
}
// Add preferences
if (usePreferences) {
Main.pref.resetToInitialState();
Main.pref.enableSaveOnPut(false);
// No pref init -> that would only create the preferences file.
// We force the use of a wrong API server, just in case anyone attempts an upload
Main.pref.put("osm-server.url", "http://invalid");
}
if (useProjection) {
Main.setProjection(Projections.getProjectionByCode("EPSG:3857")); // Mercator
}
// Set API
if (useAPI == APIType.DEV) {
Main.pref.put("osm-server.url", "http://api06.dev.openstreetmap.org/api");
} else if (useAPI == APIType.FAKE) {
FakeOsmApi api = FakeOsmApi.getInstance();
Main.pref.put("osm-server.url", api.getServerUrl());
}
// Initialize API
if (useAPI != APIType.NONE) {
try {
OsmApi.getOsmApi().initialize(null);
} catch (OsmTransferCanceledException | OsmApiInitializationException e) {
throw new InitializationError(e);
}
}
// Set Platform
if (platform) {
Main.determinePlatformHook();
}
if (commands) {
// TODO: Implement a more selective version of this once Main is restructured.
JOSMFixture.createUnitTestFixture().init(true);
}
}
/**
* Clean up what test not using these test rules may have broken.
*/
private void cleanUpFromJosmFixture() {
// MemoryManagerTest.resetState(true);
Main.getLayerManager().resetState();
Main.pref.resetToInitialState();
Main.platform = null;
System.gc();
}
/**
* Clean up after running a test
*/
protected void after() {
// Sync AWT Thread
GuiHelper.runInEDTAndWait(new Runnable() {
@Override
public void run() {
}
});
// Remove all layers
Main.getLayerManager().resetState();
// MemoryManagerTest.resetState(allowMemoryManagerLeaks);
// TODO: Remove global listeners and other global state.
Main.pref.resetToInitialState();;
Main.platform = null;
// Parts of JOSM uses weak references - destroy them.
System.gc();
}
private final class CreateJosmEnvironment extends Statement {
private final Statement base;
private CreateJosmEnvironment(Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} finally {
after();
}
}
}
enum APIType {
NONE, FAKE, DEV
}
/**
* The junit timeout statement has problems when switchting timezones. This one does not.
* @author Michael Zangl
*/
private static class FailOnTimeoutStatement extends Statement {
private int timeout;
private Statement original;
FailOnTimeoutStatement(Statement original, int timeout) {
this.original = original;
this.timeout = timeout;
}
@Override
public void evaluate() throws Throwable {
TimeoutThread thread = new TimeoutThread(original);
thread.setDaemon(true);
thread.start();
thread.join(timeout);
thread.interrupt();
if (!thread.isDone) {
Throwable exception = thread.getExecutionException();
if (exception != null) {
throw exception;
} else {
throw new Exception(MessageFormat.format("Test timed out after {0}ms", timeout));
}
}
}
}
private static final class TimeoutThread extends Thread {
public boolean isDone;
private Statement original;
private Throwable exceptionCaught;
private TimeoutThread(Statement original) {
super("Timeout runner");
this.original = original;
}
public Throwable getExecutionException() {
return exceptionCaught;
}
@Override
public void run() {
try {
original.evaluate();
isDone = true;
} catch (Throwable e) {
exceptionCaught = e;
}
}
}
}
|
Python
|
UTF-8
| 1,486
| 3.078125
| 3
|
[] |
no_license
|
from uwimg import (
clamp_image,
copy_image,
copy_image_bounds,
hsv_to_rgb,
load_image,
rgb_to_grayscale,
rgb_to_hsv,
save_image,
scale_image,
set_pixel,
shift_image,
)
# 1. Getting and setting pixels
im = load_image("data/dog.jpg")
for row in range(im.h):
for col in range(im.w):
set_pixel(im, col, row, 0, 0)
save_image(im, "dog_no_red")
# 1.1 Showing the clamp padding strategy
im = load_image("data/dog.jpg")
copy_im_exbounds = copy_image_bounds(im, int(im.w * 2), int(im.h * 2))
save_image(copy_im_exbounds, "dog_copy_exbounds")
copy_im_shrink = copy_image_bounds(im, int(im.w * 0.5), int(im.h * 0.5))
save_image(copy_im_shrink, "dog_copy_shrink")
# 2. Copy image
im = load_image("data/dog.jpg")
copy_im = copy_image(im)
save_image(copy_im, "dog_copy")
# 3. Grayscale image
im = load_image("data/colorbar.png")
graybar = rgb_to_grayscale(im)
save_image(graybar, "graybar")
# 4. Shift Image
im = load_image("data/dog.jpg")
shift_image(im, 0, 0.4)
shift_image(im, 1, 0.4)
shift_image(im, 2, 0.4)
save_image(im, "overflow")
# 5. Clamp Image
clamp_image(im)
save_image(im, "doglight_fixed")
# 6-7. Colorspace and saturation
im = load_image("data/dog.jpg")
rgb_to_hsv(im)
shift_image(im, 1, 0.2)
clamp_image(im)
hsv_to_rgb(im)
save_image(im, "dog_saturated")
# 8. Better saturation
im = load_image("data/dog.jpg")
rgb_to_hsv(im)
scale_image(im, 1, 2)
clamp_image(im)
hsv_to_rgb(im)
save_image(im, "dog_scale_saturated")
|
Java
|
UTF-8
| 395
| 1.765625
| 2
|
[] |
no_license
|
package com.eximbay.okr.dto.division;
import com.eximbay.okr.entity.*;
import lombok.*;
import javax.validation.constraints.*;
@Data
public class RemoveDivisionMemberFormDto {
@NotNull
private Division division;
@NotNull
private Member member;
@NotBlank
private String applyBeginDate;
@NotBlank
private String applyEndDate;
private String justification;
}
|
C++
|
UTF-8
| 915
| 3.71875
| 4
|
[] |
no_license
|
/**
* Two threads chopping vegetables
*/
#include <iostream>
#include <thread>
#include <chrono>
#include <stdio.h>
using namespace std;
bool chopping = true;
void vegetable_chopper(const char *name)
{
uint32_t vegetable_count = 0;
while (chopping) {
vegetable_count++;
}
/* "cout" gives mixed output on screen in multithread environment.
* Ex: BarronOlivia chopped chopped 747683860752112619 vegetables vegetables */
// cout << name << " chopped " << vegetable_count << " vegetables" << endl;
printf("%s chopped %u vegetables.\n", name, vegetable_count);
}
int main()
{
std::thread olivia(vegetable_chopper, "Olivia");
std::thread barron(vegetable_chopper, "Barron");
cout << "Barron and Olivia are chopping vegetables..." << endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
chopping = false;
barron.join();
olivia.join();
}
|
C#
|
UTF-8
| 1,686
| 2.8125
| 3
|
[] |
no_license
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Barfood : MonoBehaviour {
public Queue<GameObject> foodQ = new Queue<GameObject>(); //holds food that cant fit on bar
public List<GameObject> foodSpawn;
public List<GameObject> barfood = new List<GameObject>();
public List<Collider> triggers;
GameObject tmp;
void Start(){
}
//add to queue
public void order(GameObject foodOrdered){
foodQ.Enqueue (foodOrdered);
checkBar ();
}
//check if there is an empty spot on the bar
public void checkBar(){
if (foodQ.Count > 0) {
for (int i=0; i<barfood.Count; i++) {
if (barfood [i] == null) {
tmp = foodQ.Dequeue ();
barfood[i] = (GameObject)Instantiate(tmp, foodSpawn[i].transform.position, Quaternion.identity);
//Instantiate (tmp, foodSpawn [i].transform.position, Quaternion.identity);
break;
}
}
}
}
//for when food is picked up by the waitress
public GameObject pickup(Collider other){
for (int i=0; i<triggers.Count; i++) {
if (other == triggers[i]) { //if triggers are equal
tmp = barfood [i]; //tmp var gets reference before food is set to null
barfood [i] = null;
checkBar (); //check bar queue
Debug.Log(tmp == null);
return tmp;
}
}
return null;
}
//for when food is picked up by the waitress
public GameObject pickup(Collider other, GameObject inHand){
for (int i=0; i<triggers.Count; i++) {
if (other == triggers[i]) { //if triggers are equal
tmp = barfood [i]; //tmp var gets reference before food is set to whats in the hand
barfood [i] = inHand;
return tmp;
}
}
return null;
}
}
|
Markdown
|
UTF-8
| 2,008
| 2.578125
| 3
|
[] |
no_license
|
# Madrid NLP Meetup Session: Challenges in Transfer Learning for NLP
This repository contains the material about "Challenges in Transfer Learning for NLP" event. In this Meetup we are going to experiment different sentences representation related with Transfer Learning in NLP models for the task of **Semantic Textual Similarity** (STS).
In an simple example and tutorial, after pre-processing the official STS Benchmark from SemEval 2017, we obtain pairs of similar sentences (each phrase token list) and a similarity puntuation. Later we use different models to represent final sentence: pre-trained word embedding from FastText and Universal Sentence Encoder. Cosine function is used to see word and sentences similarity and Pearson coefficient to compare the similarities obtained with the gold standard.
## Dependencies to install
It is enough to work with Windows and Python 3 installed. With pip, install Jupyter and the following packages: nltk, codecs, numpy, matplotlib, seaborn, scipy, tensorflow and tensorflow_hub.
## Datasets to download
Dataset STSBenchmark: http://ixa2.si.ehu.es/stswiki/images/4/48/Stsbenchmark.tar.gz
FastText English pre-trained word embeddings: https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip
## References and further reading
T. Mikolov, E. Grave, P. Bojanowski, C. Puhrsch, A. Joulin. Advances in Pre-Training Distributed Word Representations
Cer, D., Yang, Y., Kong, S. Y., Hua, N., Limtiaco, N., John, R. S., ... & Sung, Y. H. (2018). Universal sentence encoder. arXiv preprint arXiv:1803.11175. See in arXiv
Cer, D., Diab, M., Agirre, E., Lopez-Gazpio, I., & Specia, L. (2017). Semeval-2017 task 1: Semantic textual similarity-multilingual and cross-lingual focused evaluation. arXiv preprint arXiv:1708.00055. https://arxiv.org/pdf/1708.00055.pdf
SentEval: evaluation toolkit for sentence embeddings. https://github.com/facebookresearch/SentEval
Advances in Semantic Textual Similarity. https://ai.googleblog.com/2018/05/advances-in-semantic-textual-similarity.html
|
JavaScript
|
UTF-8
| 520
| 3.90625
| 4
|
[] |
no_license
|
var list = [
'sun',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat'
];
var length = list.length;
//traversing
console.log('traversing : ');
for (let i = 0; i < length; i++) {
console.log('Element of '+i+' is '+ list[i]);
}
//reversing
console.log('reversing : ');
for (let i = length-1; i > 0; i--) {
console.log('Element of '+i+' is '+ list[i]);
}
//traversing another way
console.log('traversing another way : ');
for (i in list) {
console.log('Element of '+i+' is '+ list[i]);
}
|
Markdown
|
UTF-8
| 4,053
| 3.0625
| 3
|
[] |
no_license
|
## Following is explanation regarding the implementation of each item.
**1) Demonstrates the usage of ngOnChanges, @Ouput() and @Input()**
@Input and @Output are used throughout the application. E.g. a _DataListComponent_ that shows all registrations and rates lists has _cols_ and _data_ inputs. Also, in _NavbarComponent_ the navigation link in emitted on navigation link click which is used in parent for updating text _TopContainerComponent_ text. There are many other usages throughout the application.
For ngOnChanges, The _DataListComponent_ on "Navigation Link Three"which shows registration data takes data as input and performs some pre-processing i.e. calculate footer values. When the data input changes by clicking on "Delete Recent" button, the ngOnChanges is used for pre preprocessing the data again.
**2) Lazy load modules**
The application has three feature module i.e. NavOneModule, NavTwoModule and NavThreeModule. All three are lazy load modules which are loaded or main route change i.e. localhost:4200/navone, localhost:4200/navtwo, localhost:4200/navthree.
**3) Demonstrates the usages of route guards**
[http://localhost:4200/admin-panel](http://localhost:4200/admin-panel) is route guarded. It checks through AuthService if user is admin(key stored in local storage). User is navigated to [http://localhost:4200/not-authorized](http://localhost:4200/not-authorized) component if he/she is not admin. On this component, user can click "I Am Admin" button to go back to the admin-panel route as admin.
**4) Passes data between pages. Have an input field in one page of which contents is displayed in the second page.**
The _RegisterFormComponent_ on "Navigation Link Two" has a registration form. Upon filling this form and clicking on "Continue", as confirmation page is shown which displays the information entered by the user on registration form page. Moreover, once the user clicks on "Submit" button on the confirmation page, the data is saved to a dummy _DataAccessService_ and is show in a list on "Navigation Link Three".
**5) Has page transition animations. Here please make 2 examples, one with angular- animations and one that uses just css classes with animations for things like fading in an element.**
The main route as well as nested routes transitions are animated using angular animations. _TopContainerComponent_ text under the Nav bar is animated using css animations on main navigation change.
**6) Has one route that demonstrates how nested \<router-outlet\> works.**
"Navigation Link Two" has three nested routes i.e. register, register-instructions and register-confirm. Interacting with "Nav Link Two" i.e. clicking on "Instructions" button or clicking on "Continue" after filling the form, these routes are navigated.
**7) Have 2 inputs with some simple validation (like an email validation) without the require of angular-forms and ngModel**
The _RegistrationFormComponent_ has Email and Password validation fields created without using angular forms or ngModel.
**8) Demonstrates the usage of ng-content.**
The _LoadingComponent_ that shows loading while submitting registration data, and loading registration list uses ng-content to render dynamic content and shows loading spinner in the center while decreasing the opacity of the dynamic content.
**9) Have an input directive that restricts the input to numbers only and auto formats the input into currency, ex: $1,234. The field must change its format as user types. **
_RegisterFormComponent_ has an Amount input on which an Attribute directive i.e. Currency directive is applied.
**10) Demonstrates various ways to bind component properties to an associated template**
Used throughout the application.
**11) Has unit tests.**
NA
## Notes:
Project folder is provided with the Email.
The app is hosted on [https://slice-test-b4ef4.firebaseapp.com/](https://slice-test-b4ef4.firebaseapp.com/).
|
Java
|
UTF-8
| 2,919
| 3.625
| 4
|
[
"Apache-2.0"
] |
permissive
|
package com.github.max0961.model.util;
import java.util.*;
public class BinaryHeap<T extends Comparable<T>> {
protected static final int DEFAULT_CAPACITY = 10;
protected T[] items;
protected int size;
@SuppressWarnings("unchecked")
public BinaryHeap() {
items = (T[]) new Comparable[DEFAULT_CAPACITY];
this.size = 0;
}
public int size(){
return size;
}
public BinaryHeap(Collection<T> collection) {
this();
for (T item : collection) {
items[size++] = item;
if (size >= items.length - 1) {
items = resize();
}
}
for (int i = (size - 1) / 2; i >= 0; i--) {
bubbleDown(i);
}
}
public boolean isEmpty() {
return size == 0;
}
public T peek() {
if (this.isEmpty()) {
throw new IllegalStateException("The heap is empty.");
}
return items[0];
}
@SuppressWarnings("unchecked")
public void add(T value) {
if (size == items.length - 1) {
items = resize();
}
items[size++] = value;
bubbleUp();
}
public T remove() {
T result = peek();
items[0] = items[size - 1];
items[size] = null;
size--;
bubbleDown(0);
return result;
}
private void bubbleDown(int index) {
int smallerChild = index;
if (hasLeftChild(index)
&& items[leftChildIndex(index)].compareTo(items[smallerChild]) < 0) {
smallerChild = leftChildIndex(index);
}
if (hasRightChild(index)
&& items[rightChildIndex(index)].compareTo(items[smallerChild]) < 0) {
smallerChild = rightChildIndex(index);
}
if (index != smallerChild) {
swap(index, smallerChild);
bubbleDown(smallerChild);
}
}
private void bubbleUp() {
int index = this.size - 1;
while (index > 0 && parent(index).compareTo(items[index]) > 0) {
swap(index, parentIndex(index));
index = parentIndex(index);
}
}
protected int leftChildIndex(int i) {
return i * 2 + 1;
}
protected int rightChildIndex(int i) {
return i * 2 + 2;
}
protected boolean hasLeftChild(int i) {
return leftChildIndex(i) < size;
}
protected boolean hasRightChild(int i) {
return rightChildIndex(i) < size;
}
protected T parent(int i) {
return items[parentIndex(i)];
}
protected int parentIndex(int i) {
return (i - 1) / 2;
}
private T[] resize() {
return Arrays.copyOf(items, items.length * 2);
}
private T tmp;
private void swap(int index1, int index2) {
tmp = items[index1];
items[index1] = items[index2];
items[index2] = tmp;
}
}
|
Python
|
UTF-8
| 1,325
| 4.40625
| 4
|
[] |
no_license
|
# [Problem1] Calc 계산기
# 클래스 Calc는 method로 두 수를 더해주는 add, 두 수를 빼주는 sub,
# 두 수를 곱해주는 mul, 두 수를 나눠주는 div를 가지고 있습니다.
# method는 값을 반환합니다.
# 기본값이 0일 때 div을 실행하면 error가 발생하므로 "0은 분모로 올수 없습니다"를 print해주세요.
# 또한, div에서 값이 반환되어지는 값이 정수(Integer)일 때는 int 타입으로 반환해주세요
# 편의상 예시는 표시하지 않고,
# 결과는 앞에 >>>표시로 하겠습니다.
class Calc :
num = 0
def add(self,num) :
self.num += num
return self.num
def sub(self,num) :
self.num -= num
return self.num
def mul(self,num) :
self.num *= num
return self.num
def div(self,num) :
try :
self.num /= num
result = self.num
if result%1 == 0 :
result = int(self.num)
else :
result
except ZeroDivisionError :
result = "0은 분모로 올수 없습니다"
finally:
return result
calc = Calc()
print(calc.add(7))
print(calc.add(2))
print(calc.sub(5))
print(calc.mul(3))
print(calc.div(6))
print(calc.div(4))
calc = Calc()
print(calc.div(0))
|
Markdown
|
UTF-8
| 2,539
| 2.84375
| 3
|
[] |
no_license
|
# cifra-de-cesar
Segundo o Wikipedia, criptografia ou criptologia (em grego: kryptós, “escondido”, e gráphein, “escrita”) é o estudo e prática de princípios e técnicas para comunicação segura na presença de terceiros, chamados “adversários”. Mas geralmente, a criptografia refere-se à construção e análise de protocolos que impedem terceiros, ou o público, de lerem mensagens privadas. Muitos aspectos em segurança da informação, como confidencialidade, integridade de dados, autenticação e não-repúdio são centrais à criptografia moderna. Aplicações de criptografia incluem comércio eletrônico, cartões de pagamento baseados em chip, moedas digitais, senhas de computadores e comunicações militares. Das Criptografias mais curiosas na história da humanidade podemos citar a criptografia utilizada pelo grande líder militar romano Júlio César para comunicar com os seus generais. Essa criptografia se baseia na substituição da letra do alfabeto avançado um determinado número de casas. Por exemplo, considerando o número de casas = 3:
Normal: a ligeira raposa marrom saltou sobre o cachorro cansado
Cifrado: d oljhlud udsrvd pduurp vdowrx vreuh r fdfkruur fdqvdgr
--------------------------
# Pré-requisitos
Todas as bobliotecas utilizadas no projeto, normalmente já vem incluída no python, mas caso sua instalação seja "anormal", instale as seguintes bibliotecas:
- hashlib
- requests
- json
Detalhe, esse código não vai funcionar porque é necessario o endereço correto da API do Codenation
# Sobre
Esse script simples em Python decifra uma criptografia de Cesar com base na quantidade de casas passadas. Esse script foi utilizado em um desafio da codenation "http://codenation.dev/", onde é passado um Json por API com o seguinte formato:
{
"numero_casas": 10,
"token":"token_do_usuario",
"cifrado": "texto criptografado",
"decifrado": "aqui vai o texto decifrado",
"resumo_criptografico": "aqui vai o resumo"
}
e com base nessas informações, é necessario decifrar o texto e gerar uma Hash sha1, em seguida, atualizar o Json e enviar para API do Codenation, a partir dai é gerado uma nota com base nesse trabalho.
Só para constar, fiquei com 100% hehe
Foi um trabalho que não será muito útil no dia a dia, mas serve para documentar meu aprendizado. Outra coisa que é importante ressaultar, é a primeira vez que utilizo o GitHub, então se não estiver bem organizado, documentado ou algo do tipo, peço que relevem, irem melhorar com a pratica!
Ate mais!
|
JavaScript
|
UTF-8
| 705
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//show the spinner
function showSpiner(clicked_btn) {
clicked_btn.prop('disabled', true);
clicked_btn.find('img').removeClass('hide_spinner');
}
//hide the spinner by adding hide_spinner class
function hideSpinner(clicked_btn) {
clicked_btn.prop('disabled', false);
clicked_btn.find('img').addClass('hide_spinner')
}
function showMessage(message, color = 'text-success') {
$('#notification_text').html('<h1 class="' + color + ' ">' + message + '</h1>');
$('#notification').slideDown();
hideMessage();
}
function hideMessage() {
$('#notification').delay(2000).slideUp();
}
function formatNumber(number, length) {
return ("0000000" + number).slice(-1 * length);
}
|
Java
|
UTF-8
| 125
| 1.828125
| 2
|
[] |
no_license
|
package zooproject.abstraction;
import zooproject.abstraction.Eatable;
public abstract class Animal implements Eatable{
}
|
C#
|
UTF-8
| 2,294
| 2.984375
| 3
|
[] |
no_license
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpReadJSON
{
class Program
{
static void Main(string[] args)
{
var path = @"C:\Users\bilge.adam\Desktop\CagatayBoost\okuyombenya.txt";
string[] lines = File.ReadAllLines(path, Encoding.UTF8);
foreach (string line in lines)
{
Console.WriteLine(line);
}
using (StreamReader file = File.OpenText(@"C:\Users\bilge.adam\source\repos\CSharpReadJSON\CSharpReadJSON\firms.json"))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
JToken firms = o2["firm"];
List<Student> students = new List<Student>();
foreach (var item in firms)
{
var data = item["students"];
foreach (var item2 in data)
{
Student student = new Student();
student.Name = item2["name"].ToString();
student.Surname= item2["surname"].ToString();
students.Add(student);
}
}
//List<User> csharpusers = new List<User>();
//foreach (var item in kullanicilar)
//{
// User newuser = new User();
// newuser.Name = item["name"].ToString();
// newuser.City = item["city"].ToString();
// newuser.EMail = item["email"].ToString();
// newuser.Phone = item["phone"].ToString();
// newuser.RegisterDate = DateTime.ParseExact(item["registerdate"].ToString(), "dd/mm/yy", null);
// csharpusers.Add(newuser);
//}
}
}
Console.ReadLine();
}
}
}
|
Markdown
|
UTF-8
| 393
| 2.734375
| 3
|
[] |
no_license
|
# `%nin%`: The "Not In" Operator %nin%, negation of [`match`](match.html)
## Usage
```r
... %nin% NA
```
## Arguments
Argument |Description
------------- |----------------
```...``` | see %in% details in [`match`](match.html)
## Value
a logical vector
## Seealso
[`match`](match.html)
## Examples
```r
c(1,2,3) %nin% c(1,2)
c("a","b") %nin% c("a","b")
```
|
C#
|
UTF-8
| 455
| 2.640625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DP_composite
{
public abstract class Binaire : Expression
{
protected Expression op1;
protected Expression op2;
public Binaire(Expression _op1, Expression _op2)
{
this.op1 = _op1;
this.op2 = _op2;
}
abstract override public double SEvaluer();
}
}
|
Java
|
UTF-8
| 755
| 1.90625
| 2
|
[] |
no_license
|
package xyz.hhjian.lib.entity.domain;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.hhjian.lib.entity.enums.BookStatusEnum;
/**
* <p>图书类</p>
*
* @author <a href="mailto:hhjian.top@qq.com">hhjian</a>
* @since 2017.10.19
*/
@Data
@NoArgsConstructor
@TableName("book")
public class Book {
@TableId("book_id")
private Long bookId;
private String isbn;
private String title;
private String publisher;
private String pubdate;
private String author;
private String coverUrl;
private BookStatusEnum status;
private String bookrackId;
private String classify;
private String category;
}
|
Java
|
UTF-8
| 3,419
| 1.984375
| 2
|
[] |
no_license
|
package com.fsquare.shopping.service;
import com.liferay.portal.service.ServiceWrapper;
/**
* Provides a wrapper for {@link ShoppingOrderService}.
*
* @author Brian Wing Shun Chan
* @see ShoppingOrderService
* @generated
*/
public class ShoppingOrderServiceWrapper implements ShoppingOrderService,
ServiceWrapper<ShoppingOrderService> {
private ShoppingOrderService _shoppingOrderService;
public ShoppingOrderServiceWrapper(
ShoppingOrderService shoppingOrderService) {
_shoppingOrderService = shoppingOrderService;
}
/**
* Returns the Spring bean ID for this bean.
*
* @return the Spring bean ID for this bean
*/
@Override
public java.lang.String getBeanIdentifier() {
return _shoppingOrderService.getBeanIdentifier();
}
/**
* Sets the Spring bean ID for this bean.
*
* @param beanIdentifier the Spring bean ID for this bean
*/
@Override
public void setBeanIdentifier(java.lang.String beanIdentifier) {
_shoppingOrderService.setBeanIdentifier(beanIdentifier);
}
@Override
public java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable {
return _shoppingOrderService.invokeMethod(name, parameterTypes,
arguments);
}
@Override
public java.util.List<com.fsquare.shopping.model.ShoppingOrder> findByCompanyId(
long companyId)
throws com.liferay.portal.kernel.exception.SystemException {
return _shoppingOrderService.findByCompanyId(companyId);
}
@Override
public java.util.List<com.fsquare.shopping.model.ShoppingOrder> findByCompanyIdAndUserId(
long companyId, long userId)
throws com.liferay.portal.kernel.exception.SystemException {
return _shoppingOrderService.findByCompanyIdAndUserId(companyId, userId);
}
@Override
public java.util.List<com.fsquare.shopping.model.ShoppingOrder> findBygroupIdAndEmail(
long companyId, java.lang.String email)
throws com.liferay.portal.kernel.exception.SystemException {
return _shoppingOrderService.findBygroupIdAndEmail(companyId, email);
}
@Override
public double getOrderTotal(
java.util.Collection<com.fsquare.shopping.model.ShoppingOrderItem> shoppingOrderItemList) {
return _shoppingOrderService.getOrderTotal(shoppingOrderItemList);
}
@Override
public int getOrderItemsCount(
java.util.Collection<com.fsquare.shopping.model.ShoppingOrderItem> shoppingOrderItemList) {
return _shoppingOrderService.getOrderItemsCount(shoppingOrderItemList);
}
/**
* @deprecated As of 6.1.0, replaced by {@link #getWrappedService}
*/
public ShoppingOrderService getWrappedShoppingOrderService() {
return _shoppingOrderService;
}
/**
* @deprecated As of 6.1.0, replaced by {@link #setWrappedService}
*/
public void setWrappedShoppingOrderService(
ShoppingOrderService shoppingOrderService) {
_shoppingOrderService = shoppingOrderService;
}
@Override
public ShoppingOrderService getWrappedService() {
return _shoppingOrderService;
}
@Override
public void setWrappedService(ShoppingOrderService shoppingOrderService) {
_shoppingOrderService = shoppingOrderService;
}
}
|
Markdown
|
UTF-8
| 1,083
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
django-nomnom
=============
A generic importing tool for the Django admin site.
Developed with
--------------
* Python 2.7.x
* Django 1.4.x
Installation & Setup
--------------------
pip install django-nomnom
After installation add 'nomnom' to your INSTALLED_APPS setting:
INSTALLED_APPS = (
...
'nomnom', # before the admin app
'django.contrib.admin',
...
)
Set up the project URLConf like so:
urlpatterns = patterns('',
...
url(r'^admin/', include('nomnom.urls')), # before admin url patterns
url(r'^admin/', include(admin.site.urls)),
...
)
Settings
--------
NomNom has the following settings available. You can set them in your project `settings.py`. If you don't set them it will assume the default values:
### NOMNOM\_DATA\_DIR
Saved files will be stored on this directory.
**Default:** `settings.MEDIA_ROOT + 'nomnom'`
Configure Export
----------------
from nomnom.actions import export_as_csv
class MyAdmin(admin.ModelAdmin):
actions = [export_as_csv_action()]
|
Java
|
UTF-8
| 108
| 2.125
| 2
|
[] |
no_license
|
package org.strategy.staticproxy;
/**
* 抽象接口
*/
public interface IPlayGame {
void play();
}
|
JavaScript
|
UTF-8
| 553
| 3.1875
| 3
|
[] |
no_license
|
console.log(document)
function pestPrice(goo, bob, cheep) {
var goo = document.getElementById("goombas").value;
var bob = document.getElementById("bob-ombs").value;
var cheep = document.getElementById("cheep-cheeps").value;
gooPrice = parseInt(goo) * 5;
bobPrice = parseInt(bob) * 7;
cheepPrice = parseInt(cheep) * 11;
price = gooPrice + bobPrice + cheepPrice;
document.getElementById("totalPrice").value = price
}
var addButton = document.getElementById("priceButton")
addButton.addEventListener("click", pestPrice)
|
Markdown
|
UTF-8
| 2,973
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# fluent-plugin-events
Use the [Fluentd](https://fluentd.org/) input plugin to watch Kubernetes events from the Kubernetes API Server.
### Events
To customize fields for events edit the provided (`fluentd-sumologic.yaml`) file by specifying the fields in the `events` plugin `@type` parameter. The following example has specified the `type_selector`, `deploy_namespace`, and `configmap_update_interval_seconds` fields,
```json
<source>
@type events
deploy_namespace sumologic
type_selector ["ADDED", "MODIFIED", "DELETED"]
configmap_update_interval_seconds 5
</source>
```
#### Configurable fields for events
Parameter Name | Default |Description |
------------ | ------------- | -------------
resource_name | "events" | Collect events for a specific resource type, such as pods, deployments, or services.
api_version | v1 | Version of the Kubernetes Events API.
tag | "kubernetes.*" | Tag collected events.
namespace | nil | Collect events from a specific namespace.
label_selector | nil | Collect events for resources matching a specific label.
field_selector | nil | Collect events for resources matching a specific field.
type_selector | ["ADDED", "MODIFIED"] | Collect specific event types. Currently supports "ADDED", "MODIFIED", and "DELETED".
configmap_update_interval_seconds | 10 | Resource version is used to resume events collection from where it left off after a container/pod/node restart. The latest resource version of your events is kept in memory and backed up to a ConfigMap at an interval. By default, we back up the resource version by making a ConfigMap API call every 10 seconds. If you want to back up more frequently, reduce the interval. If you want to reduce the number of API calls, increase the interval.
watch_interval_seconds | 300 | Interval at which the watch thread gets recreated.
deploy_namespace | "sumologic" | Namespace that the events plugin resources will be created in.
kubernetes_url | nil | URL of the Kubernetes API.
client_cert | nil | Path to the certificate file for the client.
client_key | nil | Path to the private key file for the client.
ca_file | nil | Path to the CA file.
secret_dir | "/var/run/secrets/kubernetes.io/serviceaccount" | Path of the location where the service account credentials for the pod are stored.
bearer_token_file | nil | Path to the file containing the API token. By default it reads from the file "token" in the `secret_dir`.
verify_ssl | true | Whether to verify the API server certificate.
ssl_partial_chain | false | If `ca_file` is for an intermediate CA, or otherwise we do not have the root CA and want to trust the intermediate CA certs we do have, set this to `true` - this corresponds to the openssl s_client -partial_chain flag and X509_V_FLAG_PARTIAL_CHAIN
## Installation
### RubyGems
```
$ gem install fluent-plugin-events
```
### Bundler
Add following line to your Gemfile:
```ruby
gem "fluent-plugin-events"
```
And then execute:
```
$ bundle
```
|
Java
|
UTF-8
| 2,465
| 2.84375
| 3
|
[] |
no_license
|
package com.lwhtarena.netty.groupchat;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Scanner;
/**
* @author liwh
* @Title: GroupChatClient
* @Package com.lwhtarena.netty.groupchat
* @Description:
* @Version 1.0.0
* @date 2020/6/13 08:33
*/
public class GroupChatClient {
private String host;
private final int port;
public GroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run(){
EventLoopGroup group =new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
ChannelPipeline pipeline = sc.pipeline();
/**向pipeline加入解码器**/
pipeline.addLast("decoder",new StringDecoder());
/**向pipeline加入编码器**/
pipeline.addLast("encoder",new StringEncoder());
/**自定义handler业务**/
pipeline.addLast("myhandler",new GroupChatClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
/**得到channel**/
Channel channel =channelFuture.channel();
System.out.println("~~~~~~~~"+channel.localAddress()+"~~~~~~~~");
/**客户端需要输入信息,创建一个扫描器**/
Scanner scanner =new Scanner(System.in);
while (scanner.hasNextLine()){
String msg =scanner.nextLine();
channel.writeAndFlush(msg+"\r\n");
}
}catch (Exception e){
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) {
new GroupChatClient("127.0.0.1",7000).run();
}
}
|
Python
|
UTF-8
| 1,761
| 4
| 4
|
[] |
no_license
|
#-----------------------------------------
#Playing with statistics in dataframes and testing out predictions with Linear Regression
#v.1 2020/2/7
#Armani Chien
#------------------------------------------
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import math
import numpy as np
from sklearn.linear_model import LinearRegression
def plot():
df.plot(kind='scatter', x='nx', y='ny', title='Statistics')
plt.show()
def descriptives():
print(df)
print("sum")
print("sum-" + str(df.sum()))
print("min-" + str(df.min()))
print("max-" + str(df.max()))
print("mean-" + str(df.mean()))
print("mode-" + str(df.mode()))
print("median-" + str(df.median()))
print("range-" + str(df.max() - df.min()))
print(len(df))
def linearRegressionModel():
# Converting df to an numpy array
X = df.iloc[:, 0].values.reshape(-1, 1)
Y = df.iloc[:, 1].values.reshape(-1, 1)
linearRegressor = LinearRegression()
linearRegressor.fit(X, Y)
Y_pred = linearRegressor.predict(X) # Make Prediction
plt.scatter(X, Y) # Drawing scatter plot
plt.plot(X, Y_pred, color='red') # Placing red line prediction on plot
plt.title("Linear Regression with Predicted y")
plt.show()
r_squared = linearRegressor.score(X, Y) # Obtain R Squared
print('Coeff of determination:', r_squared)
print('intercept:', linearRegressor.intercept_)
print('slope:', linearRegressor.coef_)
print('correlation:', df.corr(method='pearson'))
#Creating a dictionary for the linear Regression plot
d = {'nx': [5, 15, 25, 35, 45, 55], 'ny': [5, 20, 14, 32, 22, 38]}
df = pd.DataFrame(data=d)
linearRegressionModel()
|
Python
|
UTF-8
| 5,040
| 3.234375
| 3
|
[] |
no_license
|
import pprint as pp
import dataretrieving as dr
import PartOne as po
import os
# TODO: remember to remove all the prints except for the printing of the results!
dataset_dir = "../datasets/"
"""
MAIN IDEA:
I can calculate the pagerank for each category and then linearly sum their weighted values.
Each of the elements of the sum must be weighted with the category preference of the user.
"""
category_file_prefix = "category-"
none_file_path = dataset_dir + category_file_prefix + "Base"
def create_datasets():
categories = dr.extract_categories()
for cat_num, category in enumerate(categories):
cat_file_path = dataset_dir + category_file_prefix + str(cat_num)
if os.path.isfile(cat_file_path):
continue
cat_file = open(cat_file_path, 'w')
cat_personalization = {0: 0., 1: 0., 2: 0., 3: 0., 4: 0., cat_num: 1.}
category_pagerank = po.calculate_page_rank_categories(category_interest=cat_personalization)
for movie_id, movie_pagerank in category_pagerank.items():
cat_file.write(str(movie_id) + ": " + str(movie_pagerank) + "\n")
cat_file.close()
"""
if not os.path.isfile(none_file_path):
none_file = open(none_file_path, 'w')
none_pagerank = po.calculate_page_rank(teleporting=False)
for movie_id, movie_pagerank in none_pagerank.items():
none_file.write(str(movie_id) + ": " + str(movie_pagerank) + "\n")
none_file.close()
"""
def get_category_pagerank(category_id):
"""
:param int | None category_id: the id of the category, must be one of the following values: 0, 1, 2, 3, 4
:return: the pagerank for the choosen category
:rtype: dict[int, float]
"""
assert type(category_id) == int, category_id in range(0, 5, step=1)
cat_file_path = dataset_dir + category_file_prefix + str(category_id)
cat_file = open(cat_file_path, 'r')
pagerank = {}
for line in cat_file:
splits = line.split(": ")
movie_id = int(splits[0])
movie_pagerank = float(splits[1])
pagerank[movie_id] = movie_pagerank
return pagerank
def are_category_pagerank_generated():
"""
Checks if there exists the files with the pagerank for the categories
:return: True iff all the files category-X (with X in {0, ..., 4}) exists
:rtype: bool
"""
for category_id in xrange(0, 5):
if not os.path.isfile(dataset_dir + category_file_prefix + str(category_id)):
return False
return os.path.isfile(none_file_path)
if __name__ == '__main__':
if not are_category_pagerank_generated():
create_datasets()
categories_interests = {0: 1., 1: 1., 2: 1., 3: .0, 4: .0}
# normalize categories_interest
interest_sum = float(sum(categories_interests.values()))
for cat_id in categories_interests.keys():
categories_interests[cat_id] /= interest_sum
# print "Calculating composite pagerank"
num_pagerank_entries = len(get_category_pagerank(0).keys())
composite_pagerank = dict((x, 0.) for x in xrange(1, num_pagerank_entries + 1))
for cat_id, interest in categories_interests.items():
if interest > 0.:
cat_pagerank = get_category_pagerank(cat_id)
for comp_cat_id, comp_interest in composite_pagerank.items():
composite_pagerank[comp_cat_id] += cat_pagerank[comp_cat_id] * interest
"""
print "Calculating direct pagerank"
direct_pagerank = po.calculate_page_rank_categories(category_interest=categories_interests)
print "Comparing direct and composite pageranks"
counter = 0
differents = False
import PartOne as po
for comp_interest, dir_interest in zip(composite_pagerank.values(), direct_pagerank.values()):
if not po.is_close(comp_interest, dir_interest):
print "Elements at index ", str(counter), " differs:\tc: ", str(comp_interest), "\td: ", str(dir_interest)
else:
print "Elements at index ", str(counter), " are EQUALS:\tc: ", str(comp_interest), "\td: ", str(
dir_interest)
differents = True
counter += 1
print
print
import operator
nx_pagerank_sorted = sorted(direct_pagerank.items(), key=operator.itemgetter(1), reverse=True)
pagerank_sorted = sorted(composite_pagerank.items(), key=operator.itemgetter(1), reverse=True)
count_equals_ordered = 0
count_equals_positions = 0
stop = False
for nx_pg, my_pg in zip(nx_pagerank_sorted, pagerank_sorted):
print "nx: (", str(nx_pg[0]), ", ", str(nx_pg[1]), ")\tmy: (", str(my_pg[0]), ", ", str(my_pg[1]), ")"
if nx_pg[0] == my_pg[0]:
count_equals_positions += 1
if not stop:
count_equals_ordered += 1
elif not stop:
stop = True
print "The firsts ", str(count_equals_ordered), " are equally ranked!"
print "Among all, ", str(count_equals_positions), " are ranked in the same position!"
"""
|
C
|
UTF-8
| 12,375
| 3.453125
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMELEN 64
#define BUFSIZE 100
struct play{
int user_id;
int artist_id;
int playcount;
struct play *next;
};
void print_play(struct play *p);
void print_plays(struct play *p);
struct play *create_play(int id, int artist_id, int playcount);
struct play *parse_play(char *line);
struct play *read_plays(char *file_name);
struct play *add_play(struct play *head, struct play *newp);
struct play *filter_user(int user_id, struct play *head);
int count_plays(struct play *head);
void free_plays(struct play *p);
void free_play(struct play *p);
void print_play(struct play *p){
if(p != NULL){
printf("User: %d\t Artist: %d\t Count: %d\n", p->user_id, p->artist_id, p->playcount); //prints all the information about a struct provided its not NULL
} else {
printf("NULL\n");
};
}
struct play *create_play(int id, int artist_id, int playcount){
struct play *a =
(struct play *)malloc(sizeof(struct play)); //allocates the right amount of memory for a new struct
if( a != NULL ) {
a->user_id = id; //sets user id
a->artist_id = artist_id; //sets artist id
a->playcount = playcount; //sets playcount
a->next = NULL; //sets next to NULL by default
}
return a; //returns our nice new struct
}
struct play *parse_play(char *line){ //honestly no idea what this is meant to do
printf("Function play *parse_play is not yet defined.\n");
return NULL;
}
void free_play(struct play *p){
free(p); //frees memory allocated to the struct p
}
struct play *add_play(struct play *head, struct play *newp){
if(newp != NULL){ //provided newp's not nothing
newp->next = head; //set its next to be the current head
return newp;
} else {
return head;
}
}
void print_plays(struct play *p){
while(p != NULL){
print_play(p); //prints everything about p
p = p->next; //steps to the next struct in the list until that struct is NULL
};
}
struct play *read_plays(char *file_name){
int user_id, artist_id, playcount; //declaring variables for storage of these things
FILE *playdata = fopen(file_name, "r"); //opening textfile read-only
struct play *tmp = create_play(0,0,0); //creating an empty struct to act as the head of the list
if(playdata != NULL){ //assuming the file isn't just NULL
while(fscanf(playdata, "%d %d %d\n", &user_id, &artist_id, &playcount) != EOF){ //while not at end of file
struct play *new = create_play(user_id, artist_id, playcount); //creating new struct
new->next = tmp;
tmp = new; //walking through list
}
fclose(playdata); //Close the file
return tmp;
} else {
fclose(playdata);
printf("File error\n");
exit(1);
};
}
int count_plays(struct play *head){
struct play *p = head;
int plays = 0;
while(p != NULL){
plays = plays + p->playcount;
p = p->next;
};
return plays;
}
struct play *filter_user(int user_id, struct play *head){ //creating a new linked list, so this will be largely similar to read_plays
struct play *root = create_play(0,0,0); //creating an empty struct to act as the head of the list
struct play *walker = root; //creating a struct that will walk through the list, creating each new struct as the loop loops
if(head != NULL){ //assuming the file isn't just NULL
struct play *p = head;
while(p != NULL){ //while not on a NULL pointer
if(p->user_id == user_id){
struct play *new = create_play(p->user_id, p->artist_id, p->playcount); //creating new struct
walker = add_play(new, walker); //adding new struct to new linked list
walker = new; //walking through list
}
p = p->next;
}
walker->next = NULL; //so we have a NULL pointer at the end of the list for our other functions
root = root->next; //so the head doesn't just point to an all-zero struct
return root;
} else {
printf("Error: Empty list provided for filtering\n");
exit(1);
};
}
void free_plays(struct play *p){
while(p != NULL){
free_play(p);
p = p->next;
}
}
void exit_usage() {
printf("\nUSAGE: query_plays file command\n"
"\n"
"where command is one of\n"
"\n"
" p <userid> prints plays, optionally limited to user.\n"
" c <userid> counts plays, optionally limited to user.\n\n");
exit(1);
}
/**
*
*
*
* HERE BEGINS THE CODE WRITTEN FOR CW-B2
*
*
*
*/
#define PLAYCOUNT 0
#define ARTISTID 1
struct artist { //TASK 1)a)
int artist_id;
char artist_name[NAMELEN];
int playcount;
int alt_artist_id;
struct artist *next;
};
struct artist *create_artist(int artist_id, char artist_name[NAMELEN], int playcount){
struct artist *a = (struct artist *)malloc(sizeof(struct artist)); //allocates the right amount of memory for a new struct
if( a != NULL ) {
a->artist_id = artist_id; //sets artist id
strcpy(a->artist_name, artist_name);
a->playcount = playcount; //sets playcount
a->next = NULL; //sets next to NULL by default
}
return a; //returns our nice new struct
}
struct artist *read_artists(char *fname){ //TASK 1)b)
int artist_id; //declaring variables for storage of these things
char artist_name[NAMELEN];
FILE *playdata = fopen(fname, "r"); //opening textfile read-only
struct artist *tmp = create_artist(0," ",0); //creating an empty struct to act as the head of the list
char lines[BUFSIZE];
if(playdata != NULL){ //assuming the file isn't just NULL
while(fgets(lines,BUFSIZE,playdata) != NULL){ //while not at end of file
sscanf(lines, "%d\t%64[^\t\n]\n", &artist_id, artist_name);
struct artist *new = create_artist(artist_id, artist_name, 0); //creating new struct
new->next = tmp;
tmp = new; //walking through list
}
fclose(playdata); //Close the file
return tmp;;
} else {
fclose(playdata);
printf("File error\n");
exit(1);
};
}
void print_artist(struct artist *a){ //TASK 1)c)
if(a != NULL){
printf("%s (%d) [%d]\n", a->artist_name, a->artist_id, a->playcount);
} else {
printf("NULL\n");
}
}
void print_artists(struct artist *a){ //TASK 1)d)
while(a != NULL){
print_artist(a);
a = a->next;
}
}
void free_artists(struct artist *a){ //TASK 1)e)
while(a != NULL){
free(a);
a = a->next;
}
}
struct play *find_middle_play(struct play *head){
struct play *slow = head;
struct play *fast = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
};
return slow;
}
struct play *merge_plays(struct play *x, struct play *y){
struct play *tmp = NULL;
struct play *head = NULL;
struct play *curr = NULL;
if(x == NULL){
return y;
} else if(y == NULL){
return x;
};
while(x != NULL && y!= NULL){
if(x->artist_id > y->artist_id){
tmp = x;
x = y;
y = tmp;
}
if(head == NULL){
head = x;
curr = x;
} else {
curr->next = x;
curr = curr->next;
}
x = x->next;
}
if(x == NULL){
curr->next = y;
} else {
curr->next = x;
}
return head;
}
struct play *sort_plays(struct play *head){ //TASK 2)a)
struct play *m = NULL;
struct play *x = NULL;
struct play *y = NULL;
if(head == NULL || head->next == NULL){
return head;
}
x = head;
m = find_middle_play(head);
y = m->next;
m->next = NULL;
return merge_plays(sort_plays(x), sort_plays(y));
}
struct artist *find_middle_artist(struct artist *head){
struct artist *slow = head;
struct artist *fast = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
};
return slow;
}
struct artist *merge_artists(struct artist *x, struct artist *y, int criterion){
struct artist *tmp = NULL;
struct artist *head = NULL;
struct artist *curr = NULL;
if(x == NULL){
return y;
} else if(y == NULL){
return x;
};
while(x != NULL && y!= NULL){
if(criterion == PLAYCOUNT){ //Sort By Playcount
if(x->playcount < y->playcount){
tmp = x;
x = y;
y = tmp;
}
} else if(criterion == ARTISTID){ //Sort By Artist ID
if(x->artist_id > y->artist_id){
tmp = x;
x = y;
y = tmp;
}
}
if(head == NULL){
head = x;
curr = x;
} else {
curr->next = x;
curr = curr->next;
}
x = x->next;
}
if(x == NULL){
curr->next = y;
} else {
curr->next = x;
}
return head;
}
struct artist *sort_artists(struct artist *artists, int criterion){ //TASK 2)b)
if(criterion != PLAYCOUNT && criterion != ARTISTID){
printf("Error: invalid comparison criteria\n");
return artists;
};
struct artist *m = NULL;
struct artist *x = NULL;
struct artist *y = NULL;
if(artists == NULL || artists->next == NULL){
return artists;
}
x = artists;
m = find_middle_artist(artists);
y = m->next;
m->next = NULL;
return merge_artists(sort_artists(x, criterion), sort_artists(y, criterion), criterion);
}
struct artist *update_counts(struct artist *a, struct play *p){ //TASK 2)c)
if(a != NULL && p != NULL){
struct artist *sorted_artists = sort_artists(a, ARTISTID);
struct play *sorted_plays = sort_plays(p);
struct artist *head = create_artist(0," ",0);
head->next = sorted_artists;
while(sorted_artists != NULL && sorted_plays != NULL){
if(sorted_artists->artist_id > sorted_plays->artist_id){
sorted_plays = sorted_plays->next;
} else if(sorted_artists->artist_id < sorted_plays->artist_id){
sorted_artists = sorted_artists->next;
} else {
sorted_artists->playcount = sorted_artists->playcount + sorted_plays->playcount;
sorted_plays = sorted_plays->next;
}
};
head = head->next;
return head;
} else {
return NULL;
}
}
struct artist *shorten_list(struct artist *list, int howmany){
struct artist *head = create_artist(0," ",0);
head->next = list;
for(int i = 1; i < howmany && list->next != NULL; i++){
list = list->next;
}
free_artists(list->next->next);
list->next = NULL;
return head->next;
}
int main(int argc, char **argv){
if(argc == 4){ //If we've actually been given arguments, then do the printing/counting
char artist_file[80];
strcpy(artist_file, argv[2]);
char play_file[80];
strcpy(play_file, argv[3]);
printf("Reading artist file:\t%s\n", artist_file);
struct artist *artists = read_artists(artist_file);
printf("Artists read\n");
printf("Reading play file:\t%s\n", play_file);
struct play *plays = read_plays(play_file);
printf("Plays read\n");
struct artist *updated = update_counts(artists, plays);
printf("Counts updated\n");
print_artists(shorten_list(sort_artists(updated, PLAYCOUNT), atoi(argv[1])));
} else {
printf("Error: expected 3 arguments after the program name: the number of plays to print, the file containing the artist data and play data, respectively.\n");
}
}
|
Go
|
UTF-8
| 2,712
| 2.859375
| 3
|
[] |
no_license
|
package log
import (
"fmt"
"os"
"strings"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
Levels = []string{"debug", "info", "warn", "error"}
)
func fileLevels(level string) (levels []string) {
for i, l := range Levels {
if l == level {
return Levels[i:]
}
}
panic(fmt.Sprintf("level %s not support", level))
}
func zapLevel(level string) zapcore.Level {
levelMap := map[string]zapcore.Level{
"debug": zap.DebugLevel,
"info": zap.InfoLevel,
"warn": zap.WarnLevel,
"error": zap.ErrorLevel,
}
return levelMap[level]
}
type ZapLogger struct {
zapLogger []*zap.SugaredLogger
}
func NewLogger(opt *Option) Log {
opt.apply()
if _, err := os.Stat(opt.DirPath); os.IsNotExist(err) {
if err = os.Mkdir(opt.DirPath, os.ModePerm); err != nil {
panic(err)
}
}
config := zap.NewProductionEncoderConfig()
config.EncodeTime = zapcore.ISO8601TimeEncoder
dirOpen(opt.DirPath)
logger := &ZapLogger{}
for _, level := range fileLevels(opt.Level) {
core := zapcore.NewCore(
zapcore.NewJSONEncoder(config),
zapcore.AddSync(NewRotateFile(
fmt.Sprintf("%v%v.log", opt.DirPath, level),
WithRotateTime(parseDuration(opt.RotateDuration)),
WithBackTime(parseDuration(opt.BackTime)))),
zapLevel(level))
logger.zapLogger = append(logger.zapLogger, zap.New(core, zap.AddCaller(), zap.AddCallerSkip(2)).Sugar())
}
return logger
}
func parseDuration(s string) (duration time.Duration) {
if s == "" {
return
}
hour := 1
if strings.Contains(s, "d") {
hour = 24
s = strings.Replace(s, "d", "h", -1)
}
duration, err := time.ParseDuration(s)
if err != nil {
panic(err)
}
return duration * time.Duration(hour)
}
func (wl *ZapLogger) Debug(msg string) {
for _, l := range wl.zapLogger {
l.Debugw(msg)
}
}
func (wl *ZapLogger) Debugf(format string, v ...interface{}) {
for _, l := range wl.zapLogger {
l.Debugf(format, v...)
}
}
func (wl *ZapLogger) Infof(format string, v ...interface{}) {
for _, l := range wl.zapLogger {
l.Infof(format, v...)
}
}
func (wl *ZapLogger) Info(msg string) {
for _, l := range wl.zapLogger {
l.Infow(msg)
}
}
func (wl *ZapLogger) Warnf(format string, v ...interface{}) {
for _, l := range wl.zapLogger {
l.Warnf(format, v...)
}
}
func (wl *ZapLogger) Warn(msg string) {
for _, l := range wl.zapLogger {
l.Warnw(msg)
}
}
func (wl *ZapLogger) Errorf(format string, v ...interface{}) {
for _, l := range wl.zapLogger {
l.Errorf(format, v...)
}
}
func (wl *ZapLogger) Error(msg string) {
for _, l := range wl.zapLogger {
l.Errorw(msg)
}
}
func dirOpen(path string) {
if fileExist(path) {
return
}
if err := os.MkdirAll(path, 766); err != nil {
panic(err)
}
}
|
C
|
UTF-8
| 1,554
| 2.546875
| 3
|
[] |
no_license
|
inherit "/std/room";
#include "mail.h"
void create()
{
set_short("the post office");
set_long("You're in the local post office.\n"+
"Commands are: read, mail and from.\n" );
add_property("silence_please");
}
void send_mail(string to,string subject,string body)
{
object o,oo;
string from;
mixed *mail,*tmp;
mail=({this_player()->query_real_name(),to,time(),subject,body});
to=lower_case(to);
to=replace(to,","," ");
to=replace(to,"&"," ");
foreach((to/" ")-({" "}),to)
{
if(!stringp(db_get("/save/players",to))
{
write("No player called "+to+".\n");
}else{
write("Sending mail to "+to+".\n");
if(o=find_player(to))
{
o->catch_tell("You have new mail.\n");
if((oo=present("mail_reader",o)) && file_name(oo)=="obj/mail_reader")
{
oo->put_mail(mail);
continue;
}
}
if(stringp(tmp=db_get(SAVEFILE,to)))
{
tmp=decode_value(tmp);
}else{
tmp=({0});
}
tmp[0]++; /* you have unread mail now */
tmp+=({mail});
db_set(SAVEFILE,to,code_value(tmp));
}
}
}
int check_for_new_mail(string name)
{
mixed tmp;
if(stringp(tmp=db_get(SAVEFILE,name)))
{
tmp=decode_value(tmp);
if(sizeof(tmp)>1) if(tmp[0]) return tmp[0];
}
}
void init()
{
::init();
move_object(clone_object("/obj/mail_reader"),this_player());
}
void exit()
{
object o;
/* I'm not root for nothing you know... */
if(o=present("mail_reader",this_player()) efun::destruct(o);
}
|
C++
|
UTF-8
| 1,075
| 2.625
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include "Sentence.h"
#include "Global.h"
#include "Util.h"
#include "Search/Manager.h"
using namespace std;
void temp();
int main(int argc, char** argv)
{
//temp();
Fix(cerr, 3);
Global &global = Global::InstanceNonConst();
global.timer.start("Starting...");
global.Init(argc, argv);
global.timer.check("Ready for input:");
string line;
while (getline(global.GetInputStream(), line)) {
if (line == "EXIT") {
break;
}
Sentence *input = Sentence::CreateFromString(line);
cerr << "input=" << input->Debug() << endl;
Manager manager(*input);
const Hypothesis *hypo = manager.GetHypothesis();
if (hypo) {
cerr << "TRANSLATION FOUND" << hypo->Debug() << endl;
hypo->Output(cout);
} else {
cerr << "NO BEST TRANSLATION" << endl;
}
cout << endl;
cerr << "Ready for input:" << endl;
}
cerr << "Shutting down" << endl;
cerr << "hypotheses created=" << Hypothesis::GetNumHypothesesCreated() << endl;
global.timer.check("Finished");
}
|
Markdown
|
UTF-8
| 30,735
| 3.109375
| 3
|
[] |
no_license
|
# 2019-09-16 Meeting with J. Casey Hammond
### J. Casey Hammond:
Your [prayer](https://twitter.com/audreyt/status/767953441746411524) was very touching.
### Audrey Tang:
It’s also my job description.
### J. Casey Hammond:
Your job description?
### Audrey Tang:
That’s right.
### J. Casey Hammond:
Did you write this yourself?
### Audrey Tang:
Yes.
### J. Casey Hammond:
It’s beautiful.
### Audrey Tang:
Thank you.
### J. Casey Hammond:
I’ve shared it with a colleague. I said, “we should create a course based on this job description to counter the predominant mentality.”
### Audrey Tang:
…which is a perversion of categories. We say “human resource”, and we say “incentivize companies”. It’s a perversion of categories.
### J. Casey Hammond:
Yes.
### Audrey Tang:
Same for “Smart cities” and “Dumb citizens”.
> (laughter)
### J. Casey Hammond:
Smart cities is one of the areas that the Singapore Government has targeted for Singapore’s future growth. Singapore hopes to become a center of innovation for smart cities. They want our university then to develop research focuses on smart cities
### Audrey Tang:
I like their new slogan, “Smart nation”. At least it’s referring to a group of people.
> (laughter)
### J. Casey Hammond:
Yes. Let me share with you that I was at the Oslo Freedom Forum last year. I was invited to a human rights roundtable, a group of maybe 10 or 12 people.
### J. Casey Hammond:
Each of us had to talk about our work and we would see whether anything came out of that. The people at the table were from different parts of Asia and represented different nationalities. Most all of them were working with refugees, and indeed…
### Audrey Tang:
That’s one of the OFF’s distinguishing characteristics.
### J. Casey Hammond:
Indeed, they have big challenges in protecting the human rights of refugees, not only in their countries of origin, but also in relocation camps. Everyone at the table had to speak. I do some work with the Indonesian migrant workers here, so I mentioned them.
### J. Casey Hammond:
The Indonesian migrant workers with whom I work in Taiwan are all formal sector employees. They aren’t housemaids. They aren’t fishermen. They’re mostly factory workers or they work in hospitals or nursing homes.
### J. Casey Hammond:
I said, “Taiwan’s formal sector has pretty good labor regulations that protect the human rights of these migrant workers from being violated.” Every once in a while, one of them might get tricked or something like that…
### Audrey Tang:
We do have room for improvement, and some of this happens to local domestic workers too.
### J. Casey Hammond:
Yes. I said, “Listening to all of you express your interest in protecting the human rights of particular groups, I realize, more basically, that we also have to protect human rights themselves.”
### J. Casey Hammond:
I’ve been in this region about half the time since 1981, much of which time I’ve spent in Taiwan and also in Indonesia, and the last eight years in Singapore.
### J. Casey Hammond:
I said, “I’ve noticed that in recent years democracy seems to be backsliding in the region. If you want to protect human rights, you have to protect democracy. I think democracy is increasingly threatened.”
### J. Casey Hammond:
I said, “Two bright spots for democracy in this region are Taiwan and Indonesia.” I often travel between these two countries. Exchanges between them have multiplied very rapidly in recent years, but such exchanges are still at an early stage.
### J. Casey Hammond:
I said, “Most people in these two countries do not yet share a great deal of mutual understanding nor speak each other’s language. I think they ought to become more aware that they are the two leading democracies in this region. I have my own historical argument for why Taiwan is part of Southeast Asia. It may not be politically correct, but it has a historical basis.”
### Audrey Tang:
We’re a Pacific island, too.
### J. Casey Hammond:
Yes, Taiwan is also a Pacific island. And the indigenous people of Taiwan are Austronesian, the same as…
### Audrey Tang:
…all the way to Māori, culturally.
### J. Casey Hammond:
Yes. The indigenous people are Austronesian. Also, the Hoklo population…. Hoklos were in Java before they were in Taiwan.
### J. Casey Hammond:
Some Hoklos came to Taiwan directly from Fujian, but some of the earliest Hoklos also came from Java. When the Dutch set up in Tainan, these Hoklos were already in Batavia, and so some of the Hokkien speakers already in Batavia came to Taiwan with the Dutch.
### J. Casey Hammond:
Also for many years, Taiwan shared a similar sociological experience of single Hoklo men coming here and marrying local women and creating a new mixed-race culture.
### Audrey Tang:
Yeah, basically being assimilated biologically with the Pingpu peoples.
### J. Casey Hammond:
It’s very similar in some ways to the Peranakan in Java.
### Audrey Tang:
I totally agree.
### J. Casey Hammond:
So, I have a historical argument for why Taiwan is part of Southeast Asia.
### Audrey Tang:
Indeed. We’re starting to see it in some implementations of our curriculum, which I helped develop.
### J. Casey Hammond:
Thank you for helping to develop that curriculum.
> (laughter)
### J. Casey Hammond:
In order to change the way people think, you need to reframe their understanding of connections.
### J. Casey Hammond:
At the OFF last year I said, “You know, Taiwan and Indonesia are the two brightest spots for democracy in Southeast Asia, so they are where human rights will probably be best protected, and this commmonality could be better recognized.”
### J. Casey Hammond:
I said, “In April of 2019, Indonesia will have a presidential election. In January of 2020, Taiwan will have a presidential election.
### J. Casey Hammond:
“This is all going to come up in the next 15, 16 months, and I know from being in Indonesia in 2014, during the last presidential election, that so-called ‘fake news’ was already a problem.
### J. Casey Hammond:
“In 2019, for sure, it will become a bigger problem.” I said the same thing about Taiwan. I said, “During the last presidential election in Taiwan” – it was in 2016 – “disinformation was a problem. It will become a bigger problem in 2020. This problem is going to grow. It’s not going to go away.”
### Audrey Tang:
Sure, and it’s going to be automated now, because the advances in picture generation now, you cannot really tell the difference when it’s synthetic.
### J. Casey Hammond:
I said, “These fact-checking agencies were recently set up in Taiwan and in Indonesia.” You probably know…
### Audrey Tang:
I am aware of that.
### J. Casey Hammond:
There’s an equivalent that was set up in 2016 in Indonesia. It goes by the acronym MAFINDO. It stands for Masyarakat Anti-Fitnah Indonesia, which means The Association of Anti-Slander Indonesia.
### Audrey Tang:
Does the administration like it?
### J. Casey Hammond:
These are good people whom I believe are respected by the Jokowi administration.
### Audrey Tang:
OK, that’s good. In Taiwan’s case, they’re, an arm’s length or two away from the DPP, and so it’s seen as more neutral.
### J. Casey Hammond:
Officially, it’s neutral. It’s nonpolitical. It’s a nonprofit group of largely volunteers. It’s not connected to a political party, but the people who run it or the people who volunteer are supporters of freedom and democracy.
### Audrey Tang:
That’s good enough. If it has, as I think they have, the Poynter IFCN criteria, they have to at least be transparent, or they’ll cease to be \[laughs\] neutral, or we’ll discover that they’re not neutral. It’s the same covenant that the TFCC here have signed.
### J. Casey Hammond:
I thought, “There are these new fact-checking agencies in both places. There could be an established channel of communication between them to share ideas and experiences, they could learn from each other, their dialogue could be focused on preventing disinformation in multiparty democratic elections that should be just and fair.”
### J. Casey Hammond:
Earlier this year, I went back and forth, and both sides said, “Yes, we would like to do this,” so it’s getting underway now.
### Audrey Tang:
Good.
### J. Casey Hammond:
The better educated people in Indonesia who know what’s going on in the world are aware of sensitivities that are attached to dealing with Taiwan.
### J. Casey Hammond:
They have to be careful. They’re interested in doing things with Taiwan, but they want to be sure that this relationship is set up properly.
### Audrey Tang:
Of course, but the TFCC, as you described, they are entirely social sector. It’s not like we are signing MOUs of any sort. It’s the academic exchange between social sector organizations, which happens all the time.
### Audrey Tang:
I personally taught, through virtual reality, students from the Academy of Art in Hangzhou, even after becoming a digital minister. It’s not seen as a big deal.
### J. Casey Hammond:
These fact-checking agencies are nongovernmental agencies, so…
### Audrey Tang:
Not at all.
### J. Casey Hammond:
…this can be done. I think in terms of disinformation, Taiwan is a particularly important place, because it’s at the forefront of new methods that China is developing. Taiwan will become the expert on China’s methods.
### J. Casey Hammond:
Once they perfect these methods in Taiwan, or believe that they have made them effective, sooner or later, they’ll use them elsewhere. I think Taiwan has something to teach.
### Audrey Tang:
To export.
### J. Casey Hammond:
To export, yes, but to say that their dialogue is motivated by such a future export may be sensitive.
### Audrey Tang:
Yeah, and we don’t even need to highlight the PRC part. Taiwan’s cybersecurity infrastructure is top notch anyway, even before the Great Firewall. In fact, we built much of the personal computers, the Internet, even on the hardware level, when the Internet first came to place.
### Audrey Tang:
I don’t think it’s a problem to say that Taiwan has had a long history down from its semiconductors to their routers and hubs, to the Internet connection ISPs.
### Audrey Tang:
We have some of the most affordable unlimited 4G connection now at $16 per month, and a very good digital opportunity plan that gives more than 98 percent of people in rural and indigenous places 10 megabits per second Internet access, and all this needs to happen for the Taiwan model of counter-disinformation to work.
### Audrey Tang:
My point being we can also share this background instead of the generative adversarial one.
### J. Casey Hammond:
Absolutely. This is something very practical versus something that’s more strategic. Let me tell you what’s on the short-term horizon. Here in Taiwan next month, October fifth and sixth, there’s going to be an international forum held in Taipei.
### J. Casey Hammond:
I received an invitation from Professor Hu to come and make a presentation. This is going to be a gathering of fact-checking agencies from the other democracies in Asia. There will be representatives from South Korea, Japan, Taiwan and Indonesia…
### Audrey Tang:
The Philippines?
### J. Casey Hammond:
…the Philippines and India.
### Audrey Tang:
Right, because Bangkok has not yet set up one.
### J. Casey Hammond:
At this gathering next month, Professor Hu has asked me to make a presentation for about 20 minutes. There’ll be numerous presentations. Mine will be just one of many.
### J. Casey Hammond:
My presentation will be relatively short and cover a relatively general topic. It will not be a terribly scholarly presentation.
### Audrey Tang:
This is a way for people in Taiwan to learn more about Indonesia, as you have described.
### J. Casey Hammond:
I wanted to ask for your advice, to speak to an audience of people who are very intelligent, but not scholars. They’re doing practical work with setting up these fact-checking agencies in the Asian democracies.
### J. Casey Hammond:
I’m not an expert on South Korea, Japan, Philippines, or India. I can say something about Taiwan and Indonesia. I’m wondering, in a 20-minute presentation, what can I say?
### J. Casey Hammond:
What basic message can I get across to these people to help them understand a little bit more about Taiwan and Indonesia and the importance of having a channel of communication between their fact-checking agencies.
### J. Casey Hammond:
I wanted to ask you for your advice. In order for these fact-checking agencies to have credibility, they do have to be neutral. They do need to have a critical stance domestically, as well as internationally.
### Audrey Tang:
Sure, as any news workers is.
### J. Casey Hammond:
A 20-minute presentation goes quickly. It’s not a whole lot of time. I’m wondering…
> (pause)
### J. Casey Hammond:
This channel between the fact-checking agencies in Taiwan and Indonesia is intended to defend their democratic elections. Is there any problem in Taiwan about which I might learn more in terms of…
### J. Casey Hammond:
I’m thinking about what’s going on in the United States right now with President Donald Trump doing certain things that aren’t illegal, but nevertheless undermining the ethos of democracy.
### J. Casey Hammond:
I’m wondering, are there domestic problems like this in Taiwan?
### Audrey Tang:
Not so much. The main challenge we have is mostly that fact-checkers are seen as part of the Internet governance community that mostly concerns the platforms that have signed on the counter-disinformation manifesto, that is to say Facebook, Google, Line, PTT, the usual suspects.
### Audrey Tang:
The involvement of institutional media is weaker than in Indonesia. In Indonesia, I understand the fact-checkers in the Cekfakta…Is that how you phrase it?
### J. Casey Hammond:
Yes.
### Audrey Tang:
In the Cekfakta, more like a cross-check initiative strives for neutrality, not through one or two well respected figures, but by the nature of international institutional media such as the AFP, as well as the domestic media of all sorts joining together to share their internal fact-checking procedures, if not materials, to build the legitimacy together. That’s from what I understand.
### Audrey Tang:
In Taiwan, maybe the CTS Television have partnered with the TFCC. Maybe the Public TV to some degree, but that’s about it. We don’t have a broader institutional media coalition that reaffirms the value of fact-checking.
### Audrey Tang:
“The Liberty Times,” for example, runs its own rumor dispelling service as part of their website’s service, but that is siloed and not at all connected to this IFCN network and extended networks.
### Audrey Tang:
That is a problem because The Liberty Times is oftentimes seen as “partisan,” but if they’re willing to share their methodologies and investigations, and the folks on “UDN,” for example, is willing to do the same, together they will surely reach a larger population.
### Audrey Tang:
It will not only be on the LINE system or the Facebook system. Also, it will give rise to a renewed set of expectations of journalism standards on institutional media similar to Japan. That’s not quickly happening in Taiwan. We have a coalition of newer media that doesn’t publish on paper that agrees to fact-check all the presidential candidates during the election season already using crowdsource.
### Audrey Tang:
It’s laudable, but the fact that they are mostly Internet-only media further confirms this modality shift between the traditional institutional and the social media.
### J. Casey Hammond:
This might be an interesting thing to talk about because it is a fundamental starting point. This basic work must be done before other things can proceed. How can I find out more about this situation so I could just give a 10-minute talk on it?
### Audrey Tang:
I can send you the joint statement of the major platforms, for one, in English, as well…
### J. Casey Hammond:
Thank you.
### Audrey Tang:
Yeah, as well as the coalition that I just mentioned that agrees to fact-check every presidential candidate. From there, you can probably reach all the important stakeholders on the IFCN and extended networks side to learn the whole picture.
### Audrey Tang:
For the institutional media, there’s no formal way to ask, “What’s your take on fact-checking?” They often are not very clear about their contribution to the Internet governance versus their more traditional audience who rely less on the social media. They have two audiences to please, so to speak.
### Audrey Tang:
I think the most I can do is to paint the picture of the coalition on this part. I cannot speak for institutional media. The most I can do is to introduce you to CNA, which is the media sponsored by the administration.
### Audrey Tang:
They have their own take on this issue. They are transitioning to a new media as well and every other institutional media copy from their text anyway. They may have some views on this matter. The traditional institutional media, they all have different thoughts and they’re not extremely loud about their thoughts about this matter.
### J. Casey Hammond:
That might be a good place to start. I can look at the equivalent situation on the Indonesian side. Maybe that will fill up 20 minutes and give people in the audience a basic understanding about these…
### Audrey Tang:
The greatest thing is that you can compare all these different models maybe with the French model and so on and UK model and so on without even mentioning the PRC. That makes a really good workshop material to start with if we’re going to hold more workshops, as you mentioned, across the two jurisdictions.
### J. Casey Hammond:
Yes, that might be a good place to start. I’d be really grateful for any information.
### Audrey Tang:
Sure. Joel will collect…
### J. Casey Hammond:
This event will be on the fifth and sixth of October, which is only about three weeks away or so, so I’ve got to get busy with this.
### Audrey Tang:
I’m sure that you can crowdsource part of your presentation to the coalition to describe the Taiwan situation. I think Cekfakta, just looking at their media partners, they may each contribute some statements to you about how participating in Cekfakta have improved their horizontal relationships and so on, similar to the coalition that we have here.
### Audrey Tang:
Putting those two pictures together and analyze it a little bit, like what is lip service and what is substantial, and then you have a presentation.
### J. Casey Hammond:
Yes, that’s a good idea.
### Audrey Tang:
Thank you.
### J. Casey Hammond:
Thanks. Joel, can I stay in touch with you and…?
> (off-mic speech)
### J. Casey Hammond:
OK, thanks. Let me ask you, just to learn a little bit more about your work, what do you see as your biggest challenges?
### Audrey Tang:
At the moment, it’s the remaining authoritarian culture in Taiwan. You were around here when I was born.
### J. Casey Hammond:
I was here under martial law.
### Audrey Tang:
That’s right. I was born into martial law. The martial law got lifted when I was six or seven. I remember the martial law. People younger than me don’t. It is a problem, actually.
### J. Casey Hammond:
Still?
### Audrey Tang:
Yeah. The thing is that people who were born before the martial law have a certain worldview that is compatible with authoritarianism. Authoritarianism, at that point in time in the ‘80s is already not a dictatorship. It’s more of a benevolent authoritarianism strain of things under Chiang Ching-kuo.
### Audrey Tang:
It actually gives it a bit more legitimacy compared to the Chiang Kai-shek, right? That is a problem, because there is people who are maybe my parents’ age in their 60s and the 70s.
### Audrey Tang:
They sometimes miss the era of Chiang Ching-kuo where Taiwan was growing very quickly economically, and the regional re-cultivation of culture, the community building movement and so on were not only allowed but gradually encouraged by the authoritarian regime.
### Audrey Tang:
That went for 10 years before we even got a presidential election in 1996, which is the same year as the World Wide Web becoming ubiquitous in Taiwan. After that, the society kind of went beyond their comprehension.
### J. Casey Hammond:
There’s something similar in Indonesia, where some people now miss Suharto.
### Audrey Tang:
It is. Like the World Wide Web, it’s intertwined with the red presidential election. It’s the same year. The first ever presidential election we have propaganda and disinformation on the web. It seems as chaotic. The people would reminisce about the earlier era that I still remember but people younger than me don’t.
### Audrey Tang:
The people younger than me don’t even have the vocabulary to describe in their vision in a way that’s compatible with that era, because none of those era’s documents is Googleable. The most you can Google is some scholarly article. It’s not very accessible.
### Audrey Tang:
There is a linguistic and cultural generational gap that is our focus to heal. It is shown very clearly in the referenda of the last year.
### J. Casey Hammond:
The referenda of the last year being…
### Audrey Tang:
Being for example, when the older generation see marriage, they don’t think it’s an administrative registration by a democratic state. They think it is a social tie amongst kinships and rituals.
### Audrey Tang:
Indeed, the law was that. If you get wed in a public ceremony, register or not, you’re married as specified by law. People who marry after 2008 only need to do a registration. It doesn’t really care whether you do a ceremony or not. It becomes something of the public sector rather than the social sector term.
### Audrey Tang:
That’s very confusing, because when you say we want to give marriage “equality,” what exactly do you mean? That is being interpreted wildly differently by people of different generational groups.
### J. Casey Hammond:
Do you think that the younger generation, say, those born in the 1990s, are they as susceptible to the sentiment attached to this reminiscence about authoritarianism as, say, people in their 60s and 70s who might think, “Ah, those were the good, old days?”
### Audrey Tang:
No, I don’t think they even have words for it.
### J. Casey Hammond:
They don’t even have words for it.
### Audrey Tang:
Yeah. They can reminisce about, for example, four thousand years of the great Sino culture. They can also reminisce about the Austronesian culture, which lives in Taiwan for a considerably longer time. That’s not authoritarianism, it’s just cultural lineage.
### J. Casey Hammond:
That’s interesting. I’ve noticed in Indonesia that some younger people who have no memory of the New Order regime of Suharto are susceptible to what some older people are saying about that regime, that order was kept in those days. That there was predictability in those days. There’s a longing for that.
### J. Casey Hammond:
Some of the younger people who didn’t experience any of the suppression that occurred then are susceptible to thinking, “Yeah, maybe…”
### Audrey Tang:
“Maybe it was rosy after all.”
### J. Casey Hammond:
Yes.
### Audrey Tang:
We were in that point in 2013, as recent. After 2014, everything changed.
### J. Casey Hammond:
With the Sunflower Movement?
### Audrey Tang:
Yeah, the Occupy Movement, the focus on transitional justice afterwards, the sheer creativity of young people’s ways of communicating, what really happened during the White Terror and so on it captured the imagination.
### Audrey Tang:
It’s considered hip then to talk about politics. Before, there’s a certain apathy that resonates with the rosy view of the authoritarian regime as you just described. It may be a little bit like Hong Kong.
### Audrey Tang:
Now, Hong Kong people, no matter which age group, is affected by the creativity of the young generation, that they cannot actually unsee the brutality of the police.
### J. Casey Hammond:
It’s interesting to know this. Tell you what, I don’t want to take up too much of your time.
### Audrey Tang:
No, it’s fine.
### J. Casey Hammond:
The suggestion that you just made, I would like to have it sink in so that I can begin thinking more about it. One of the issues here in Taiwan is that the traditional media may be doing some fact-checking on their own, like Liberty Times, but it’s not connected to…
### Audrey Tang:
To the IFCN and extended networks.
### J. Casey Hammond:
That’s what really should be happening.
### Audrey Tang:
I’m not in a place where I say the media should do something. It’s not democratic. What I’m saying is that for the institutional media readers, they are not getting the benefit of having a robust fact-checking network. That’s just an objective observation. They would mostly rely if they used the Line software, their clarification messages online today.
### Audrey Tang:
Frankly, it’s not a very super visible part of the Line app. Line is doing what they could and we’re grateful of it. I’m just saying most of them still spend much more time talking about the news on institutional media, whether it’s through television or through printed papers.
### J. Casey Hammond:
The traditional media might be doing its own fact-checking, but it’s not tied into a larger network of fact-checking, whereas online media is more…
### Audrey Tang:
Quickly forming a coalition.
### J. Casey Hammond:
Forming a coalition. The challenge is how to bring the traditional media into this coalition so that they might benefit from it.
### Audrey Tang:
Also, to be very honest, there is only a handful of institutional media that successfully completed the digital transformation, like the Commonwealth Group and so on. They themselves are seeing the Internet as something that they’re very busily trying to solve to please two audiences and so on.
### Audrey Tang:
This digital transformation takes up a lot of their energy. Maybe fact-checking and protection of democracy is not on the super-high priority while they are trying to reinvent themselves in the digital age.
### J. Casey Hammond:
They have their hands full just transitioning to digital media…
### Audrey Tang:
To find a new revenue model to make sure there’s a relationship between their authors and the readers, and now everybody demands a one-hour response, but how do we not sacrifice the journalistic standard.
### J. Casey Hammond:
When you say they demand a one-hour response, what does that mean?
### Audrey Tang:
It means the news cycle has drastically shortened.
### J. Casey Hammond:
OK.
### Audrey Tang:
C’est la vie.
### J. Casey Hammond:
I understand. I won’t take up too much more of your time. I really wanted to meet you and make this introduction. I hope that we can stay in touch.
### Audrey Tang:
Yeah, certainly. On October fourth, I’ll be in Buenos Aires and so I will miss the conference.
### J. Casey Hammond:
I’m sorry.
### Audrey Tang:
I’m sure there will be more to come. We’re actually organizing a very similar workshop in Bangkok. Joel has the details. Maybe our lectures and so on could be also your resource when you try to build something in Indonesia.
### J. Casey Hammond:
Right. May I ask, who in Taiwan will be involved in running a workshop in Bangkok?
### Audrey Tang:
Joel has all the details. I think one of the co-founders of CoFacts and the people…
### J. Casey Hammond:
Open Culture?
### Audrey Tang:
Yeah, the Open Culture Foundation folks. There is also the head of the Open Data Alliance, himself a renowned weather forecaster, which is important, because they reach a very large audience through a weather broadcasting service.
### Audrey Tang:
He is generally seen as reputable – that’s very important – and currently makes that open data around air pollution, water pollution, earthquake prevention, and so on, public or even open as in open license, especially just to promote such independent broadcasters to give a more understandable framing rhetoric to the local people in a more precision targeting way.
### Audrey Tang:
Our Central Weather Bureau can only issue one press release, but Taiwan actually \[laughs\] have a lot of different islands and altitudes. A micro-targeted weather service is a large market. This actually can be seen as analogue to disarming this information thing.
### Audrey Tang:
Dr. Peng Chi-min has always been very helpful in advising Taiwan's open data strategies, especially around open government data. Here in Taiwan, when we say open data, we also have citizen science data, private sector data. Open data by its own means data collaboratives across sectors. He is a real expert and has run many Asia-Pacific open data hackathons and activities.
### Audrey Tang:
We also have the National Development Council Deputy Director, Chuang Ming-Fen, in charge of running our open data and our open government platforms and our e-participation platforms.
### Audrey Tang:
That’s important, because the Join platform has 10 million unique visitors out of 23 million of Taiwanese. That’s like our own community where people can raise e-petitions and meet the officials face-to-face. Two years ago, a 16-year-old girl proposed that we ban plastic straws gradually so as not to harm the sea ecosystem.
### Audrey Tang:
Taiwan has 10 percent of the world’s marine biodiversity and we thinks it’s a treasure. We arranged a collaborative meeting, because she very quickly get 5,000 petitioners under a pseudonym, which is allowed, we thought that this must be a very senior environmental activist to get so many people so quickly, but then she is 16 years old.
### Audrey Tang:
We met with the producers of one-shot utensils and they said they were social enterprises. Back when you first came to Taiwan in the ‘80s, because hepatitis B is everywhere. They entered this industry not to earn profit, but to solve a public health problem. They were with a social purpose.
### Audrey Tang:
Now hepatitis B is cured. You just take a pill and everything is gone. It’s not a problem anymore. They’re very willing only if better material than plastic is available. People started developing sugarcanes. They work really well. Starting this July for indoor drinking, it’s banned.
### Audrey Tang:
I think it also helps that environmental group understand the position of the plastic producers in that they were joining these industries long ago with a social purpose, and they will respond to the new social purpose.
### Audrey Tang:
That was a pretty good success story. When you have that, there’s no room for disinformation to grow, because there is no misinformation or no misunderstanding in the first place. I think the NDC have a lot to contribute as well.
### Audrey Tang:
Finally, somebody from our office, Romulus, is going to share how we build such technological tools to encourage rough consensus rather than polarization online. Any of these might be your resource when holding an Indonesian workshop.
### Audrey Tang:
The Thai people seems to be happy with this lineup.
### J. Casey Hammond:
Thank you very much. As for your job description, may I share that with others?
### Audrey Tang:
Sure, of course. I relinquish all copyright, as will be this transcript after we edit it for 10 days. It will be in the Commons.
### J. Casey Hammond:
OK. Thank you so much.
### Audrey Tang:
Thank you.
|
Java
|
UTF-8
| 2,317
| 2.109375
| 2
|
[] |
no_license
|
package com.rjkj.cf.bbibm.kjds.product.appcategory.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
*@描述:app商品分类属性表
*@项目:
*@公司:软江科技
*@作者:crq
*@时间:2019-10-12 11:05:19
**/
@Data
@TableName("bbibm_app_category")
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "app商品分类属性表")
public class AppCategory extends Model<AppCategory> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(value = "id",type = IdType.INPUT)
@ApiModelProperty(value="id")
private String id;
/**
* 类别名称
*/
@ApiModelProperty(value="类别名称")
private String name;
/**
* 是否有子类,0否
*/
@ApiModelProperty(value="是否有子类,0否")
private Integer isParent;
/**
* 父ID
*/
@ApiModelProperty(value="父ID")
private Integer parentId;
/**
* 所属层级
*/
@ApiModelProperty(value="所属层级")
private Integer level;
/**
* 各层级ID
*/
@ApiModelProperty(value="各层级ID")
private String pathid;
/**
* 路径名称
*/
@ApiModelProperty(value="路径名称")
private String path;
/**
* 主ID对应的Shopee商城的id
*/
@ApiModelProperty(value="主ID对应的Shopee商城的id")
private String shopee;
/**
* 主ID对应的Ebay商城的id
*/
@ApiModelProperty(value="主ID对应的Ebay商城的id")
private String ebay;
/**
* 主ID对应的Amazon商城的id
*/
@ApiModelProperty(value="主ID对应的Amazon商城的id")
private String amazon;
/**
* 当前分类的下级分类
*/
@ApiModelProperty(value="当前分类的下级分类")
@TableField(exist = false)
private List<AppCategory> listCateGory;
}
|
Java
|
UTF-8
| 6,177
| 2.34375
| 2
|
[] |
no_license
|
package com.taedison.helmy;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/***
* Service that sends registries of alerts that were launched. We send data that can be usedful such as:
* Alert sent or cancelled
* Alert sent to the police (not yet implemented in the business model)
* Alert sent to the ambulate (not yet implemented in the business model)
*
* This service is executed when the app opens and uploads all pending registries
*/
public class ServiceAlerts extends Service {
public static boolean running = false;
private String TAG = "ServiceAlerts";
private SingletonSharedPreferences preferences;
private RequestQueue requestQueue;
public ServiceAlerts() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Log.d(TAG, "onStartCommand");
running = true;
preferences = SingletonSharedPreferences.getInstance(getApplicationContext());
//volley
requestQueue = SingletonVolley.getInstance(getApplicationContext()).getRequestQueue();
uploadNextAlert();
// If we get killed because of insuficient memory, START STICKY will restart when memory is released
return START_STICKY;
}
private void uploadNextAlert(){
String mostRecentAlert = preferences.getMostRecentAlert();
if( !TextUtils.isEmpty(mostRecentAlert) ){
prepareToSendToServer(mostRecentAlert);
} else {
ArrayList<String> listAlerts = new ArrayList<>( preferences.getSetAlertsPendingToUpload() );
if(listAlerts.size() > 0){
String alertInPrefs = listAlerts.get(0);
prepareToSendToServer(alertInPrefs);
} else {
stopSelf();
}
}
}
private void prepareToSendToServer(String alert2send){
String[] segments = alert2send.split(";");
if(segments.length == 4){
// ServiceEmergency was killed before cancelling or sending the alert, e.g., phone died or low memory
// thus it will be sent as a canceled alert
String date = segments[0];
String txtFile = segments[1];
String userId = segments[2];
String mac = segments[3];
StringRequest joRequest = request(alert2send, date, txtFile, userId, mac, "-1", "-1"); //-1 indicates the phone was shut off before even trying to send the alert
requestQueue.add(joRequest);
} else if(segments.length == 6){
String date = segments[0];
String txtFile = segments[1];
String userId = segments[2];
String mac = segments[3];
String dateCanceled = segments[4];
String dateSMS = segments[5];
StringRequest joRequest = request(alert2send, date, txtFile, userId, mac, dateCanceled, dateSMS);
requestQueue.add(joRequest);
} else {
// something wrong with prefs
stopSelf();
}
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
private StringRequest request(final String alertInPrefs, final String date, final String txtFile,
final String userId, final String mac, final String wasCanceled, final String alertSMS){
String url;
if(preferences.get_isPrimaryServerDown()){
// primary server is down, so we will use the secondary
url = Static_AppVariables.url_impact2;
} else {
url = Static_AppVariables.url_impact;
}
return new StringRequest(Request.Method.POST, url,
new com.android.volley.Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
if( !TextUtils.isEmpty(response) ) {
// Log.d(TAG, "Response: " + response + "\nname= " + alertInPrefs
// + "\nalertSMS= " + alertSMS + "\nwasCanceled= " + wasCanceled);
preferences.removeAlertRegistryAlreadyUploaded(alertInPrefs);
uploadNextAlert();
} else {
// most likely the user has mobile data on but without internet service
stopSelf();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
// Log.e(TAG, "error: " + error.toString() + "\nname= " + alertInPrefs
// + "\nalertSMS= " + alertSMS + "\nwasCanceled= " + wasCanceled);
Static_AppMethods.checkResponseCode(error, preferences);
stopSelf();
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("impact", date);
params.put("txt", txtFile);
params.put("userId", userId);
params.put("mac", mac);
params.put("canceled", wasCanceled);
params.put("alertSMS", alertSMS);
params.put("alertPolice","0");
params.put("alertAmbulance","0");
return params;
}
};
}
@Override
public void onDestroy() {
// Log.d(TAG, "Service Alert destroyed");
running = false;
super.onDestroy();
}
}
|
C++
|
UTF-8
| 2,658
| 3.46875
| 3
|
[] |
no_license
|
/*!
Custom exceptions for the bship engine
*/
#ifndef EXCEPTIONS_HPP
#define EXCEPTIONS_HPP
#include <iostream>
#include <exception>
#include <string>
namespace bship{
class bship_exception;
class index_exception;
class illegal_move_exception;
}
/*!
@class bship_exception
@brief Custom exceptions for bship engine
The base class to all exceptions related to battleship engine
*/
class bship::bship_exception : public std::exception{
public:
/*!
@brief Base class what()
Returns a generic error message ("Battleship exception"),
is overrided in its children bship exceptions
@return Message of the exception
*/
virtual const char *what() const noexcept {
return "Battleship exception";
}
};
/*!
@class index_exception
@brief Grid index exceptions
This exception is thrown in case an invalid operation
is carried out with indices of bs_grid
*/
class bship::index_exception : public bship_exception{
int _row_idx; //< row index
int _col_idx; //< column index
std::string _msg; //< message of the exception
public:
/*!
@brief Index exception constructor
Constructs an index_exception given indices and a message
@param row Row index
@param col Column index
@param msg Custom message (default: "Error at index")
*/
index_exception(int row, int col, const char* msg = "Error at index")
: _row_idx(row), _col_idx(col)
{
_msg = std::string("Index exception: ") + std::string(msg) + " (" + std::to_string(_row_idx) + ", " + std::to_string(_col_idx) + ")";
}
/*!
@brief Overridden what()
@return User-supplied message or default "Error at index (i, j)"
*/
const char *what(){
return _msg.c_str();
}
};
/*!
@class illegal_move_exception
@brief Illegal move exception
This exception is thrown in case an invalid game move is attempted
*/
class bship::illegal_move_exception : public bship_exception{
std::string _msg; //< message of the exception
public:
/*!
@brief Illegal move exception constructor
Constructs an illegal_move_exception given a message
@param msg Custom message (default: "Illegal move")
*/
explicit illegal_move_exception(const char* msg = "Illegal move")
: _msg(std::string("Illegal move exception: ") + msg)
{}
/*!
@brief Overridden what()
@return User-supplied message or default "Illegal move"
*/
const char *what(){
return _msg.c_str();
}
};
#endif
|
C++
|
UTF-8
| 473
| 2.890625
| 3
|
[] |
no_license
|
#include <iostream>
#include <stdio.h>
int getch();
void ungetch(int);
static int stack [1000];
static int *top = NULL;
int getch()
{
int ch;
if(top == NULL)
{
ch = getchar ();
return ch;
}
if(top == stack)
{
ch = *top;
top = NULL;
}
else
{
ch = *top;
--top;
}
return ch;
}
void ungetch (int ch)
{
if(top == NULL)
{
top = stack;
*top = ch;
}
else
{
top++;
*top = ch;
}
//*top = ch;
//printf("unreading ch %c", ch);
//++top;
}
|
Java
|
UTF-8
| 9,602
| 2.5
| 2
|
[] |
no_license
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JOptionPane;
import netgame.common.Client;
public class PenteClientController implements ActionListener, MouseListener, WindowListener {
private static final int DEFAULT_PORT = 45017;
PenteClientView view;
PenteClientModel model;
PenteClientConnection connection;
public PenteClientController(PenteClientView view, PenteClientModel model) {
String host = JOptionPane.showInputDialog("Enter the server address that you wish to connect to: ");
if (host == null) {
return;
}
try {
connection = new PenteClientConnection(host, DEFAULT_PORT);
connection.setAutoreset(true);
} catch (IOException ex) {
ex.printStackTrace();
}
this.view = view;
this.model = model;
this.view.addActionListener(this);
this.view.addWindowListener(this);
this.view.addMouseListener(this);
this.view.setGrid(model.getGrid());
}
@Override
public void mouseClicked(MouseEvent e) {
if (model.isWinner()) {
return;
}
if (!model.isYourTurn()) {
JOptionPane.showMessageDialog(null, "You must wait your turn!");
return;
}
if (model.getLastMove()[0] != -1) {
JOptionPane.showMessageDialog(null, "You can only place one tile per turn!");
return;
}
int x = Math.round((float)(e.getX() - view.getOffSetX()) / 28);
if (x < 0)
x = 0;
if (x > 18) {
x = 18;
}
int y = Math.round((float)(e.getY() - view.getOffSetY()) / 28);
if (y < 0)
y = 0;
if (y > 18)
y = 18;
if (model.youWentFirst() && model.numTurns() == 0 && (x != 9 || y != 9)) {
JOptionPane.showMessageDialog(null, "You must place your first tile in the center square!");
return;
}
if (model.youWentFirst() && model.numTurns() == 1) {
if ((x > 6 && x < 12) && (y > 6 && y < 12)) {
JOptionPane.showMessageDialog(null, "Your second` move must be outside the inner ring!");
return;
}
}
if (model.addPlayerTile(x, y, 1)) {
model.setLastMove(x, y);
model.checkForCapturedPair(model.getLastMove()[0], model.getLastMove()[1]);
view.setGrid(model.getGrid());
view.repaint();
}
else {
JOptionPane.showMessageDialog(null, "You cannot place your tile on top of another!");
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals(PenteClientView.UNDO_COMMAND)) {
if (!model.isYourTurn()) {
JOptionPane.showMessageDialog(null, "You must wait your turn!");
return;
}
if (model.getCapturedPairs().size() != 0) {
for (int[] array : model.getCapturedPairs()) {
model.addPlayerTile(array[0], array[1], array[2]);
}
model.clearCapturedPairs();
}
if (model.getLastMove()[0] == -1) {
JOptionPane.showMessageDialog(null, "No previous move to undo");
return;
}
int[] lastMove = model.getLastMove();
model.removePlayerTile(lastMove[0], lastMove[1]);
view.setGrid(model.getGrid());
view.repaint();
model.setLastMove(-1, -1);
}
else if (command.equals(PenteClientView.QUIT_COMMAND)) {
if (model.inGame()) {
connection.send("disconnected");
}
else {
connection.send("Leave Game");
}
model.reset();
view.setYourCapturesText(0);
view.setOpponentCapturesText(0);
model.setYourTurn(false);
view.showPanel("welcomePanel");
view.showButtons();
}
else if (command.equals(PenteClientView.END_TURN_COMMAND)) {
view.hideButtons();
if (!model.isYourTurn()) {
JOptionPane.showMessageDialog(null, "It is not your turn yet!");
return;
}
if (model.isYourTurn() && model.getLastMove()[0] == -1) {
JOptionPane.showMessageDialog(null, "You must make a move before ending your turn!");
return;
}
connection.send(model.getLastMove());
connection.resetOutput();
model.updateCaptures();
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
model.checkForWinner();
if (model.isWinner()) {
model.setInGame(false);
if (model.getWinner() == 1) {
if (model.wonByCaptures()) {
view.hideButtons();
JOptionPane.showMessageDialog(null, "You win!\n You captured five of your opponent's pairs!");
}
else if (model.wonByFive()) {
view.hideButtons();
JOptionPane.showMessageDialog(null, "You win!\nYou got a five in a row!");
}
}
}
view.setYourCapturesText(model.getYourCaptures());
view.setOpponentCapturesText(model.getOpponentCaptures());
model.clearCapturedPairs();
model.setLastMove(-1, -1);
view.repaint();
model.setYourTurn(false);
model.incrementNumTurns();
view.hideButtons();
}
else if (command.equals(PenteClientView.NEW_GAME_COMMAND)) {
connection.send("New Game");
view.showPanel("waitingPanel");
}
else if (command.equals(PenteClientView.CONNECTING_BACK_COMMAND)) {
connection.send("Back");
view.showPanel("welcomePanel");
view.repaint();
}
else if (command.equals(PenteClientView.EXIT_COMMAND)) {
connection.disconnect();
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
else if (command.equals(PenteClientView.INSTRUCTIONS_COMMAND)) {
view.showPanel("rulesInstructionPanel");
}
else if (command.equals(PenteClientView.RULES_BACK_COMMAND)) {
view.showPanel("welcomePanel");
}
else if (command.equals(PenteClientView.NEXT_COMMAND)) {
view.showPanel("exampleCapturesPanel");
}
else if (command.equals(PenteClientView.PREVIOUS_COMMAND)) {
view.showPanel("rulesInstructionPanel");
}
else if (command.equals(PenteClientView.DONE_COMMAND)) {
view.showPanel("welcomePanel");
}
}
private class PenteClientConnection extends Client {
public PenteClientConnection(String host, int port) throws IOException {
super(host, port);
}
@Override
protected void messageReceived(Object message) {
if (message instanceof int[]) {
updateGame((int[]) message);
}
if (message instanceof String) {
if (message.equals("disconnected")) {
if (!model.inGame()) {
return;
}
JOptionPane.showMessageDialog(null, "Your opponent disconnected");
model.reset();
view.setGrid(model.getGrid());
view.setYourCapturesText(0);
view.setOpponentCapturesText(0);
view.repaint();
view.showPanel("welcomePanel");
}
else if (message.equals("yourTurn")) {
model.reset();
model.setInGame(true);
view.showPanel("gamePanel");
model.setYouWentFirst(true);
model.setYourTurn(true);
JOptionPane.showMessageDialog(null, "You go first. Make your move.");
view.requestFocus();
view.showButtons();
}
else if (message.equals("waitYourTurn")) {
model.reset();
model.setInGame(true);
view.setGrid(model.getGrid());
view.showPanel("gamePanel");
model.setYouWentFirst(false);
model.setYourTurn(false);
JOptionPane.showMessageDialog(null, "Your opponent gets the first move.");
view.requestFocus();
view.hideButtons();
}
}
}
}
public void updateGame(int[] playerTile) {
view.showButtons();
model.addPlayerTile(playerTile[0], playerTile[1], 2);
model.checkForCapturedPair(playerTile[0], playerTile[1]);
model.updateCaptures();
view.setYourCapturesText(model.getYourCaptures());
view.setOpponentCapturesText(model.getOpponentCaptures());
model.clearCapturedPairs();
model.checkForWinner();
model.setYourTurn(true);
view.setGrid(model.getGrid());
view.repaint();
if (model.isWinner()) {
model.setInGame(false);
if (model.getWinner() == 2) {
if (model.wonByCaptures()) {
JOptionPane.showMessageDialog(null, "You lost!\nYour opponent captured five pairs!");
view.hideButtons();
}
else if (model.wonByFive()) {
JOptionPane.showMessageDialog(null, "You lost!\nYour opponent got a five in a row!");
view.hideButtons();
}
}
}
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
if (model.inGame()) {
connection.send("disconnected");
connection.disconnect();
}
else {
view.dispose();
connection.disconnect();
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}
|
Shell
|
UTF-8
| 668
| 2.640625
| 3
|
[] |
no_license
|
#!/bin/bash
cd /opt
#java installation
wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm
#start the java
rpm -ivh jdk-8u131-linux-x64.rpm
# install tomcat
wget https://mirrors.estointernet.in/apache/tomcat/tomcat-9/v9.0.46/bin/apache-tomcat-9.0.46-windows-x64.zip
# unzip the tomcat file
unzip apache-tomcat-9.0.46-windows-x64.zip
# rename the tomcat file
mv apache-tomcat-9.0.46 tomcat
# allow the permissions 700 to tomcat folder
chmod -R 700 tomcat
# goto inside tomcat directory
cd tomcat/bin
# start up the tomcat server
./startup.sh
|
Markdown
|
UTF-8
| 972
| 3.265625
| 3
|
[] |
no_license
|
# React Native Component Viewer
This is a simple template app that lets you view a single component in isolation, centered on the phone screen. Only tested in Android, but should work for IOS. Contributions to test for IOS are welcome.
Useful for:
- People who want to test the look and feel of individual components in isolation
- People who want to test components for react native npm modules (e.g. react-native-calendar-picker) before including them first in their actual apps
- NPM module creators / contributors who wish to test the look and feel of their module component(s) in isolation
How to use:
- Clone Repo `git clone https://github.com/joeltok/react-native-component-viewer.git <new folder name>`
- Add component file(s)
- For npm modules, just `npm install --save <module name>`
- For regular components, `import <component> from <file path>` in app/index.js
- Add component to app/index.js
- run `react-native run-android` or `react-native run-ios`
|
PHP
|
UTF-8
| 13,956
| 2.65625
| 3
|
[] |
no_license
|
<?php
require_once File::build_path(array('model','Model.php'));
class ModelAccueil
{
private $idAccueil;
private $nomAccueil;
private $descAccueil;
private $url1;
private $url2;
private $url3;
public function getIdAccueil() {return $this->idAccueil;}
public function getNomAccueil() {return $this->nomAccueil;}
public function getDescAccueil() {return $this->descAccueil;}
public function getUrl1() {return $this->url1;}
public function getUrl2() {return $this->url2;}
public function getUrl3() {return $this->url3;}
public static function getAll() {
try{
$sql = Model::$pdo -> query("SELECT * FROM Accueil");
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
$tab = $sql->fetch();
return $tab;
}
public static function getDescription() {
try{
$sql = Model::$pdo -> query("SELECT * FROM Accueil");
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
$desc = $sql->fetch();
return $desc['descAccueil'];
}
public static function getImage1() {
try{
$sql = Model::$pdo -> query("SELECT * FROM Accueil");
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
$desc = $sql->fetch();
return $desc['url1'];
}
public static function getImage2() {
try{
$sql = Model::$pdo -> query("SELECT * FROM Accueil");
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
$desc = $sql->fetch();
return $desc['url2'];
}
public static function getImage3() {
try{
$sql = Model::$pdo -> query("SELECT * FROM Accueil");
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
$desc = $sql->fetch();
return $desc['url3'];
}
public static function modifIM1($texte,$id){
try {$stmt = Model::$pdo->prepare("UPDATE `Accueil` SET `url1`= :texte WHERE idAccueil=:id");}
catch (PDOException $e) {
if (Conf::getDebug()) {echo $e->getMessage();}
else { echo 'Une erreur est survenue <a href=""> retour a la page d\'accueil </a>';}
die();
}
$stmt->execute(array('texte' => $texte,
'id' => $id));
}
// Test de l'image avant modification //
public static function modifImage1($fichier,$id){
$im = ModelAccueil::getImage1();
$var = str_replace("images/","",$im);
$fichier="images/".$var;
$fichier= str_replace(" ","",$fichier);
$array = array(
"suppression" => "bar",
"edit" => "foo",
);
if (file_exists($fichier)) {
if (@unlink($fichier)) {
$array["suppression"]="Suppression de $fichier réussite </br>";
} else {
$array["suppression"]="Echec de suppression de $fichier : $php_errormsg";
}
} else {
$array["suppression"]="Le fichier $fichier n'existe pas </br>";
}
// Vérifier si le formulaire a été soumis
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Vérifie si le fichier a été uploadé sans erreur.
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0) {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Vérifie l'extension du fichier
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed)) die("Erreur : Veuillez sélectionner un format de fichier valide.");
// Vérifie la taille du fichier - 5Mo maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize) die("Error: La taille du fichier est supérieure à la limite autorisée.");
// Vérifie le type MIME du fichier
if (in_array($filetype, $allowed)) {
// Vérifie si le fichier existe avant de le télécharger.
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
$array["edit"]=$_FILES["photo"]["name"] . " existe déjà.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], "images/" . $_FILES["photo"]["name"]);
$array["edit"]= "Votre fichier a été téléchargé avec succès. ".$_FILES["photo"]["name"];
$adresse = "images/".$filename;
$adresse = str_replace(" ","",$adresse);
ModelAccueil::modifIM1($adresse,$id);
}
} else {
$array["edit"]= "Error: Il y a eu un problème de téléchargement de votre fichier. Veuillez réessayer.";
}
} else {
echo "Error: " . $_FILES["photo"]["error"];
}
}
return $array;
}
public static function modifIM2($texte,$id){
try {$stmt = Model::$pdo->prepare("UPDATE `Accueil` SET `url2`= :texte WHERE idAccueil=:id");}
catch (PDOException $e) {
if (Conf::getDebug()) {echo $e->getMessage();}
else { echo 'Une erreur est survenue <a href=""> retour a la page d\'accueil </a>';}
die();
}
$stmt->execute(array('texte' => $texte,
'id' => $id));
}
// Test de l'image avant modification //
public static function modifImage2($fichier,$id){
$im = ModelAccueil::getImage2();
$var = str_replace("images/","",$im);
$fichier="images/".$var;
$fichier= str_replace(" ","",$fichier);
$array = array(
"suppression" => "bar",
"edit" => "foo",
);
if (file_exists($fichier)) {
if (@unlink($fichier)) {
$array["suppression"]="Suppression de $fichier réussite </br>";
} else {
$array["suppression"]="Echec de suppression de $fichier : $php_errormsg";
}
} else {
$array["suppression"]="Le fichier $fichier n'existe pas </br>";
}
// Vérifier si le formulaire a été soumis
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Vérifie si le fichier a été uploadé sans erreur.
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0) {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Vérifie l'extension du fichier
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed)) die("Erreur : Veuillez sélectionner un format de fichier valide.");
// Vérifie la taille du fichier - 5Mo maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize) die("Error: La taille du fichier est supérieure à la limite autorisée.");
// Vérifie le type MIME du fichier
if (in_array($filetype, $allowed)) {
// Vérifie si le fichier existe avant de le télécharger.
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
$array["edit"]=$_FILES["photo"]["name"] . " existe déjà.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], "images/" . $_FILES["photo"]["name"]);
$array["edit"]= "Votre fichier a été téléchargé avec succès. ".$_FILES["photo"]["name"];
$adresse = "images/".$filename;
$adresse = str_replace(" ","",$adresse);
ModelAccueil::modifIM2($adresse,$id);
}
} else {
$array["edit"]= "Error: Il y a eu un problème de téléchargement de votre fichier. Veuillez réessayer.";
}
} else {
echo "Error: " . $_FILES["photo"]["error"];
}
}
return $array;
}
public static function modifIM3($texte,$id){
try {$stmt = Model::$pdo->prepare("UPDATE `Accueil` SET `url3`= :texte WHERE idAccueil=:id");}
catch (PDOException $e) {
if (Conf::getDebug()) {echo $e->getMessage();}
else { echo 'Une erreur est survenue <a href=""> retour a la page d\'accueil </a>';}
die();
}
$stmt->execute(array('texte' => $texte,
'id' => $id));
}
// Test de l'image avant modification //
public static function modifImage3($fichier,$id){
$im = ModelAccueil::getImage3();
$var = str_replace("images/","",$im);
$fichier="images/".$var;
$fichier= str_replace(" ","",$fichier);
$array = array(
"suppression" => "bar",
"edit" => "foo",
);
if (file_exists($fichier)) {
if (@unlink($fichier)) {
$array["suppression"]="Suppression de $fichier réussite </br>";
} else {
$array["suppression"]="Echec de suppression de $fichier : $php_errormsg";
}
} else {
$array["suppression"]="Le fichier $fichier n'existe pas </br>";
}
// Vérifier si le formulaire a été soumis
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Vérifie si le fichier a été uploadé sans erreur.
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0) {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Vérifie l'extension du fichier
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed)) die("Erreur : Veuillez sélectionner un format de fichier valide.");
// Vérifie la taille du fichier - 5Mo maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize) die("Error: La taille du fichier est supérieure à la limite autorisée.");
// Vérifie le type MIME du fichier
if (in_array($filetype, $allowed)) {
// Vérifie si le fichier existe avant de le télécharger.
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
$array["edit"]=$_FILES["photo"]["name"] . " existe déjà.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], "images/" . $_FILES["photo"]["name"]);
$array["edit"]= "Votre fichier a été téléchargé avec succès. ".$_FILES["photo"]["name"];
$adresse = "images/".$filename;
$adresse = str_replace(" ","",$adresse);
ModelAccueil::modifIM3($adresse,$id);
}
} else {
$array["edit"]= "Error: Il y a eu un problème de téléchargement de votre fichier. Veuillez réessayer.";
}
} else {
echo "Error: " . $_FILES["photo"]["error"];
}
}
return $array;
}
public static function getNom() {
try{
$sql = Model::$pdo -> query("SELECT * FROM Accueil ");
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
$nom = $sql->fetch();
return $nom['nomAccueil'];
}
public static function modifDesc($texte,$id){
try {$stmt = Model::$pdo->prepare("UPDATE `Accueil` SET `descAccueil`=:texte WHERE idAccueil=:id");}
catch (PDOException $e) {
if (Conf::getDebug()) {echo $e->getMessage();}
else { echo 'Une erreur est survenue <a href=""> retour a la page d\'accueil </a>';}
die();
}
$stmt->execute(array('texte' => $texte,
'id' => $id));
}
}
|
TypeScript
|
UTF-8
| 3,683
| 2.84375
| 3
|
[] |
no_license
|
import { ArHttp, Feedback } from "../services";
import { Config } from "../config/config";
import { AxiosRequestConfig } from 'axios';
import { withCookies, Cookies } from 'react-cookie';
export interface IAuthentication {
isAuth: boolean,
userName: string,
token: string,
token_type: string
};
export abstract class AuthService {
private static _cookieService;
public static Initialize() {
this._cookieService = new Cookies();
this.fillAuthData();
}
public static authentication: IAuthentication = {
isAuth: false,
userName: "",
token: "",
token_type: ""
};
//to regiser a new user
public static saveRegistration(registration) {
return ArHttp.post(`${Config.apiEndPoint}/api/Account/Register`, registration);
}
//login code.
public static login(loginData, callback: () => void) {
let data = "grant_type=password&username=" + loginData.email + "&password=" + loginData.password;
let options: AxiosRequestConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
//The apiend point is the token end point
ArHttp.post(`${Config.apiEndPoint}/token`, data, options).then((response: any) => {
var data = response.data;
//once the token obtained set the local variables
this.authentication.isAuth = true;
this.authentication.userName = data.userName;
this.authentication.token = data.access_token;
this.authentication.token_type = data.token_type;
//if the login form has remember me enabled we need to store the token in cookie with expiry data as current date + expiry of the token in seconds
if (loginData.rememberMe) {
var date = new Date();
date.setSeconds(date.getSeconds + response.expires_in);
this._cookieService.set('authorizationData', this.authentication,{ expires: date })
}
callback();
});
}
private static _logOutCallback(isSilent) {
//Once logged reset authentication, remove data from cookies and show message
//this.resetAuthentication();
//this._cookieService.remove('authorizationData');
if (!isSilent) Feedback.info("You have successfully logged off.");
}
//logout service
public static LogOut(isSilent, callback: () => void) {
ArHttp.post(`${Config.apiEndPoint}/api/Account/Logout`, null).then((response) => {
//once logged out from server clear the local data, remove from cookies and fire callback if any
this.resetAuthentication();
this._cookieService.remove('authorizationData');
this._logOutCallback(isSilent);
callback();
});
}
//reset local variables
private static resetAuthentication() {
this.authentication.isAuth = false;
this.authentication.userName = "";
this.authentication.token = "";
this.authentication.token_type = "";
}
//get data from the cookies and populate the local data
public static fillAuthData() {
var authorizationData = this._cookieService.get("authorizationData");
if (authorizationData) {
var aData = authorizationData as IAuthentication;
this.authentication.isAuth = aData.isAuth;
this.authentication.userName = aData.userName;
this.authentication.token = aData.token;
this.authentication.token_type = aData.token_type;
}
}
}
AuthService.Initialize();
|
TypeScript
|
UTF-8
| 357
| 2.703125
| 3
|
[] |
no_license
|
export class CategoryDto {
name: string;
description: string;
isActive: boolean;
id: string;
constructor(initialValues: Partial<CategoryDto> = {}) {
if (initialValues) {
for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) {
this[key] = initialValues[key];
}
}
}
}
}
|
Python
|
UTF-8
| 1,174
| 3.875
| 4
|
[] |
no_license
|
# 병합정렬
# 순서가 뒤죽박죽인 배열이 있을 때 정렬하기 위해 분할과 정복방식을 이용한다
# 1. 데이터를 절반씩 나누어 끝까지 갔다가(분할했다가)
# 2. 다시 절반씩 합치면서 그 안에서 정렬한다.(정복한다)
def merge_sort(arr):
if len(arr) <= 1:
return arr
# 재귀함수를 이용해서 끝까지 분할
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
i = 0
j = 0
k = 0
# 분할된 배열끼리 비교하기
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# 먼저 끝났을 경우
if i == len(left):
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
elif j == len(right):
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
return arr
n = int(input())
num = []
for _ in range(n):
num.append(int(input()))
num = merge_sort(num)
for i in num:
print(i)
|
C#
|
UTF-8
| 9,980
| 2.703125
| 3
|
[
"Unlicense"
] |
permissive
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace DatagenSharp
{
/// <summary>
/// Top level class for data generation
/// </summary>
public sealed class GenerateData
{
public GenerateChain chain = new GenerateChain();
public IDataOutputter output;
public object outputParameters = null;
public uint howManyStepToRun = 10;
public (bool success, string possibleError) Generate(Stream outputStream)
{
// Init output
(bool initSuccess, string possibleInitError) = this.output.Init(outputParameters, outputStream);
// Verify that init went OK
if (!initSuccess)
{
return (success: initSuccess, possibleError: possibleInitError);
}
// Write header
var names = this.chain.GetNames();
this.output.WriteHeader(names.ConvertAll(s => (object)s));
List<object> entries = null;
// Write each entry
for (int i = 0; i < howManyStepToRun; i++)
{
entries = GetCurrentLine();
(bool entryWriteSuccess, string possibleEntryWriteError) = this.output.WriteSingleEntry(entries);
if (!entryWriteSuccess)
{
return (success: entryWriteSuccess, possibleError: possibleEntryWriteError);
}
this.chain.UpdateToNextStep();
}
// Write footer
return output.WriteFooter(entries);
}
private List<object> GetCurrentLine()
{
return this.chain.RunOneStep();
}
#region Helpers
public void AddGeneratorToChain(IDataGenerator generator)
{
this.chain.DataGenerators.Add(generator);
}
public void AddGeneratorsToChain(params IDataGenerator[] generators)
{
this.chain.DataGenerators.AddRange(generators);
}
public void AddMutatorToNewChain(IMutator mutator, object parameters, Type wantedOutput)
{
MutatorChain mutatorChain = new MutatorChain();
mutatorChain.AddMutatorToChain(mutator, parameters, wantedOutput);
this.chain.MutatorChains.Add(mutatorChain);
}
public (bool success, string possibleError) AddMutatorToExistingChain(long internalChainId, IMutator mutator, object parameters, Type wantedOutput)
{
MutatorChain existingChain = this.chain.MutatorChains.Find((MutatorChain mc) => mc.GetInternalId() == internalChainId);
if (existingChain == null)
{
return (false, $"Cannot find existing chain with internal ID: {internalChainId}");
}
existingChain.AddMutatorToChain(mutator, parameters, wantedOutput);
return (true, "");
}
/// <summary>
/// Add wanted element
/// </summary>
/// <param name="name">Name of wanted element. e.g. "Id", "Name", "Email"</param>
/// <param name="generator">Generator that will be generating the content for the element</param>
/// <param name="stepParameter">Optional parameter for the generate step</param>
/// <param name="wantedOutput">Output type wanted to generate</param>
/// <param name="mutatorChain">Optional mutator chain that will mutate the output</param>
public void AddWantedElement((string name, IDataGenerator generator, object stepParameter, Type wantedOutput, MutatorChain mutatorChain) wantedElement)
{
this.chain.WantedElements.Add(wantedElement);
}
private void AddWantedElement(string name, int zeroBasedGeneratorIndex, int zeroBasedMutatorChainIndex)
{
// Since mutator chains are not mandatory, check it
this.AddWantedElement(name, this.chain.DataGenerators[zeroBasedGeneratorIndex], null, null, zeroBasedMutatorChainIndex > -1 ? this.chain.MutatorChains[zeroBasedMutatorChainIndex] : null);
}
/// <summary>
/// Add wanted element
/// </summary>
/// <param name="name">Name of wanted element. e.g. "Id", "Name", "Email"</param>
/// <param name="generator">Generator that will be generating the content for the element</param>
/// <param name="stepParameter">Optional parameter for the generate step</param>
/// <param name="wantedOutput">Output type wanted to generate</param>
/// <param name="mutatorChain">Optional mutator chain that will mutate the output</param>
public void AddWantedElement(string name, IDataGenerator generator, object stepParameter, Type wantedOutput, MutatorChain mutatorChain)
{
this.AddWantedElement((name, generator, stepParameter, wantedOutput, mutatorChain));
}
#endregion // Helpers
#region Serialization
private enum ReadMode
{
SeekingSection = 0,
ReadGenerators,
ReadMutatorChains,
ReadWantedElements,
ReadOutputter,
}
private ReadMode readMode = ReadMode.SeekingSection;
public (bool success, string possibleError) Load(string input)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] typesInAssembly = assembly.GetTypes();
Dictionary<string, Type> typesOfIDataGenerator = new Dictionary<string, Type>();
IEnumerable<Type> implementIDataGenerator = typesInAssembly.Where(t => t.GetInterfaces().Contains(typeof(IDataGenerator)));
Dictionary<string, Type> typesOfIDataOutputter = new Dictionary<string, Type>();
IEnumerable<Type> implementIDataOutputter = typesInAssembly.Where(t => t.GetInterfaces().Contains(typeof(IDataOutputter)));
//IEnumerable<Type> implementISerialization = typesInAssembly.Where(t => t.GetInterfaces().Contains(typeof(ISerialization)));
HashSet<Type> implementISerialization = new HashSet<Type>(typesInAssembly.Where(t => t.GetInterfaces().Contains(typeof(ISerialization))));
foreach (Type type in implementIDataGenerator)
{
// We only want to keep track of types that implement both IDataGenerator and ISerialization
if (implementISerialization.Contains(type))
{
var tempObj = Activator.CreateInstance(type) as IDataGenerator;
typesOfIDataGenerator[tempObj.GetNames().shortName] = type;
}
}
foreach (Type type in implementIDataOutputter)
{
// We only want to keep track of types that implement both IDataOutputter and ISerialization
if (implementISerialization.Contains(type))
{
var tempObj = Activator.CreateInstance(type) as IDataOutputter;
typesOfIDataOutputter[tempObj.GetNames().shortName] = type;
}
}
this.readMode = ReadMode.SeekingSection;
using (StringReader reader = new StringReader(input))
{
string line = reader.ReadLine();
while (line != null)
{
if (line.StartsWith(CommonSerialization.generators))
{
this.readMode = ReadMode.ReadGenerators;
}
else if (line.StartsWith(CommonSerialization.mutatorChains))
{
this.readMode = ReadMode.ReadMutatorChains;
}
else if (line.StartsWith(CommonSerialization.wantedElements))
{
this.readMode = ReadMode.ReadWantedElements;
}
else if (line.StartsWith(CommonSerialization.outputter))
{
this.readMode = ReadMode.ReadOutputter;
}
else
{
if (readMode == ReadMode.ReadGenerators)
{
int indexOfFirstSpace = line.IndexOf(' ');
string indexNumber = line.Substring(0, indexOfFirstSpace);
string generator = line.Substring(indexOfFirstSpace + 1);
if (!int.TryParse(indexNumber, out int generatorIndex))
{
return (false, $"Line: {line} has invalid generator index value");
}
string[] generatorSplitted = generator.Split(CommonSerialization.delimiter);
if (!typesOfIDataGenerator.ContainsKey(generatorSplitted[0]))
{
return (false, $"Line: {line} has unknown generator shortname {generatorSplitted[0]}");
}
if (!int.TryParse(generatorSplitted[2], out int rngSeed))
{
return (false, $"Line: {line} has invalid rng seed {generatorSplitted[2]}");
}
var generatorToAdd = Activator.CreateInstance(typesOfIDataGenerator[generatorSplitted[0]]) as IDataGenerator;
//bool shouldParameterBeNull = (string.IsNullOrEmpty(generatorSplitted[1]) || generatorSplitted[1] == CommonSerialization.nullValue);
(bool generatorLoadSuccess, string generatorLoadError) = ((ISerialization)generatorToAdd).Load($"{CommonSerialization.delimiter}{generatorSplitted[1]}{CommonSerialization.delimiter}{generatorSplitted[2]}");
if (!generatorLoadSuccess)
{
return (generatorLoadSuccess, generatorLoadError);
}
this.AddGeneratorToChain(generatorToAdd);
}
else if (readMode == ReadMode.ReadMutatorChains)
{
}
else if (readMode == ReadMode.ReadWantedElements)
{
if (!line.StartsWith("-"))
{
return (false, $"Line: {line} does not start with -");
}
string[] wantedElementsSplitted = line.Split(CommonSerialization.delimiter);
string name = wantedElementsSplitted[0].Substring(1);
if (!int.TryParse(wantedElementsSplitted[1], out int generatorIndex))
{
return (false, $"Line: {line} has invalid generator index value");
}
int mutatorChainIndex = -1;
if (wantedElementsSplitted[2].StartsWith(CommonSerialization.missingElementChar.ToString()))
{
}
else if (!int.TryParse(wantedElementsSplitted[2], out mutatorChainIndex))
{
return (false, $"Line: {line} has invalid mutator chain index value");
}
this.AddWantedElement(name, generatorIndex - 1, mutatorChainIndex - 1);
}
else if (readMode == ReadMode.ReadOutputter)
{
string[] outputterSplitted = line.Split(CommonSerialization.delimiter);
var outputterToAdd = Activator.CreateInstance(typesOfIDataOutputter[outputterSplitted[0]]) as IDataOutputter;
this.output = outputterToAdd;
}
}
line = reader.ReadLine();
}
}
return (true, "");
}
public string Save()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(CommonSerialization.header);
sb.Append(this.chain.Save());
sb.AppendLine(CommonSerialization.outputter);
sb.AppendLine($"{this.output.GetNames().shortName}{((ISerialization)this.output).Save()}");
return sb.ToString();
}
#endregion // Serialization
}
}
|
Java
|
UTF-8
| 227
| 2.546875
| 3
|
[] |
no_license
|
package pkg;
public class PublicClass1 {
public static void hello() {
System.out.println("Hello from PublicClass1");
}
public static void bye() {
System.out.println("Bye from PublicClass1");
}
}
|
Java
|
UTF-8
| 40,957
| 1.585938
| 2
|
[] |
no_license
|
package fr.vivicoubar.onyxffa;
import fr.vivicoubar.onyxffa.commands.*;
import fr.vivicoubar.onyxffa.duels.ArenaManager;
import fr.vivicoubar.onyxffa.duels.DuelListener;
import fr.vivicoubar.onyxffa.duels.DuelManager;
import fr.vivicoubar.onyxffa.events.sumo.CommandsSumo;
import fr.vivicoubar.onyxffa.events.sumo.SumoEvent;
import fr.vivicoubar.onyxffa.events.sumo.SumoListener;
import fr.vivicoubar.onyxffa.events.sumo.SumoSpawnManager;
import fr.vivicoubar.onyxffa.events.wanted.CommandsWanted;
import fr.vivicoubar.onyxffa.events.wanted.WantedEvent;
import fr.vivicoubar.onyxffa.listeners.*;
import fr.vivicoubar.onyxffa.managers.*;
import fr.vivicoubar.onyxffa.managers.KitsManager;
import fr.vivicoubar.onyxffa.utils.Messages;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class OnyxFFaMain extends JavaPlugin {
private File configFile;
private FileConfiguration configConfiguration;
private File statsFile;
private FileConfiguration statsConfiguration;
private File ranksFile;
private FileConfiguration ranksConfiguration;
private File spawnsFile;
private FileConfiguration spawnsConfiguration;
private File messagesFile;
private FileConfiguration messagesConfiguration;
private File kitsFile;
private FileConfiguration kitsConfiguration;
private File blockFile;
private FileConfiguration blockFileConfiguration;
private File arenaFile;
private FileConfiguration arenaFileConfiguration;
private File kitsPlayerDataFile;
private FileConfiguration kitsPlayerDataConfiguration;
private RanksManager ranksManager;
private SpawnManager spawnManager;
private FFaPlayerManager fFaPlayerManager;
private LocationBuilder locationBuilder;
private ItemBuilder itemBuilder;
private final List<String> commandsList = new ArrayList<>();
private final List<String> lore = new ArrayList<>();
private final List<String> SpawnInWait = new ArrayList<>();
private final List<Location> spawnsList = new ArrayList<>();
private final List<String> blockEffectList = new ArrayList<>();
private final List<String> jumpadsBlocks = new ArrayList<>();
private final List<Location> sumoSpawnList = new ArrayList<>();
private FFAAnimatedBlocksManager ffaAnimatedBlocksManager;
private KitsManager kitsManager;
private String testFFa;
public static OnyxFFaMain instance;
public Messages messages = new Messages();
public PotionEffectManager potionEffectManager = new PotionEffectManager();
public WantedEvent wantedEvent = new WantedEvent();
public SumoEvent sumoEvent = new SumoEvent(this);
public SumoSpawnManager sumoSpawnManager = new SumoSpawnManager(this);
public DuelManager duelManager = new DuelManager();
public ArenaManager arenaManager = new ArenaManager();
public static OnyxFFaMain getInstance() {
return instance;
}
@Override
public void onEnable() {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PlayerPAPIExpansion(this).register();
}
OnyxFFaMain.instance = this;
System.out.println(" ");
System.out.println("************************");
System.out.println("[NewOnyxFFA] > DEMARRAGE");
System.out.println("************************");
System.out.println(" ");
PluginManager pluginManager = Bukkit.getPluginManager();
getCommand("offa").setExecutor(new CommandOffa(this));
getCommand("stats").setExecutor(new CommandStats(this));
getCommand("spawn").setExecutor(new CommandSpawn(this));
getCommand("resetStats").setExecutor(new CommandResetStats(this));
getCommand("points").setExecutor(new CommandPoints(this));
getCommand("autorespawn").setExecutor(new CommandAutoRespawn(this));
getCommand("joinwanted").setExecutor(new CommandsWanted(this));
getCommand("startwanted").setExecutor(new CommandsWanted(this));
getCommand("spec").setExecutor(new CommandVanish(this));
getCommand("vanish").setExecutor(new CommandVanish(this));
getCommand("addeffect").setExecutor(new CommandAddEffect());
getCommand("duel").setExecutor(new CommandAskDuel(this));
getCommand("sumo").setExecutor(new CommandsSumo());
getCommand("kiteditor").setExecutor(new CommandKitEditor(this));
pluginManager.registerEvents(new FFaPlayerListener(this), this);
pluginManager.registerEvents(new BlockListener(this), this);
pluginManager.registerEvents(new ItemListener(this), this);
pluginManager.registerEvents(new DamageListener(this), this);
pluginManager.registerEvents(new GadgetsAndDiscoListener(this), this);
pluginManager.registerEvents(new PlayerJoinListener(), this);
pluginManager.registerEvents(new PlayerQuitListener(), this);
pluginManager.registerEvents(new PlayerHeldItemListener(), this);
pluginManager.registerEvents(new PlayerMoveEventListener(), this);
pluginManager.registerEvents(new DuelListener(this), this);
pluginManager.registerEvents(new CommandVanish(this), this);
pluginManager.registerEvents(new SumoListener(), this);
try {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
configFile = new File(this.getDataFolder(), "config.yml");
messagesFile = new File(this.getDataFolder(), "messages.yml");
kitsFile = new File(this.getDataFolder(), "kits.yml");
statsFile = new File(this.getDataFolder(), "stats.yml");
ranksFile = new File(this.getDataFolder(), "ranks.yml");
spawnsFile = new File(this.getDataFolder(), "spawns.yml");
blockFile = new File(this.getDataFolder(), "blocks.yml");
arenaFile = new File(this.getDataFolder(), "arenas.yml");
kitsPlayerDataFile = new File(this.getDataFolder(), "kitsplayerdata.yml");
if (!configFile.exists()) {
configFile.createNewFile();
configConfiguration = YamlConfiguration.loadConfiguration(configFile);
lore.clear();
lore.add("§aCliquer Pour");
lore.add("§aRejoindre le FFa");
configConfiguration.set("NewOnyxFFa.Config.minY", 50);
configConfiguration.set("NewOnyxFFa.Config.UseDeathByFallDamageRecognition", true);
configConfiguration.set("NewOnyxFFa.Config.Menu.Item.Material", "GOLD_AXE");
configConfiguration.set("NewOnyxFFa.Config.Menu.Item.Name", "RushFFa");
configConfiguration.set("NewOnyxFFa.Config.Menu.Item.Enchanted", true);
configConfiguration.set("NewOnyxFFa.Config.Menu.Item.Lore", lore.toArray());
configConfiguration.set("NewOnyxFFa.Config.SpawnCommand.TimerUntilTeleportation", 10);
lore.clear();
lore.add("msg %killer% test");
lore.add("msg %victim% test");
configConfiguration.set("NewOnyxFFa.Config.onKillCommands.onFight", lore.toArray());
lore.clear();
lore.add("msg %victim% test");
lore.add("msg %victim% test");
configConfiguration.set("NewOnyxFFa.Config.onKillCommands.onFallIntoVoid", lore.toArray());
configConfiguration.set("NewOnyxFFa.Config.HealthBonusAfterKill", 5);
lore.clear();
configConfiguration.save(configFile);
}
if (!kitsPlayerDataFile.exists()) {
kitsPlayerDataFile.createNewFile();
kitsPlayerDataConfiguration = YamlConfiguration.loadConfiguration(kitsPlayerDataFile);
kitsPlayerDataConfiguration.save(kitsPlayerDataFile);
}
if (!blockFile.exists()) {
blockFile.createNewFile();
blockFileConfiguration = YamlConfiguration.loadConfiguration(blockFile);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.TimerUntilBreak", 5);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockBeforeBreakState", "BRICK");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.ReplaceTime", 5);
lore.clear();
lore.add("BRICK");
lore.add("SANDSTONE");
lore.add("GRASS");
lore.add("GLOWSTONE");
lore.add("WOOL");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.AllowedBlocktoBreak", lore.toArray());
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockPlacedByPlayers", lore.toArray());
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Material", "LAPIS_BLOCK");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.EffectType", "Potion");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Effect.1.PotionEffect", "HEAL");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Effect.1.Amplifier", 1);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Effect.1.Duration", 20);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Effect.2.PotionEffect", "INCREASE_DAMAGE");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Effect.2.Amplifier", 20);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.1.Effect.2.Duration", 20);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.2.Material", "GOLD_BLOCK");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.2.EffectType", "HealthBonus");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.2.HeartBonus", 2);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Material", "DIAMOND_BLOCK");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.EffectType", "Item");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Item.1.Material", "IRON_SWORD");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Item.1.Quantity", 1);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Item.1.IsEnchanted", true);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Item.1.Enchantments.1.Type", "PROTECTION_ENVIRONMENTAL");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Item.1.Enchantments.1.Amplifier", 2);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.3.Item.1.isUnbreakable", true);
blockFileConfiguration.set("NewOnyxFFa.Config.EffectBlock.Cooldown", 20);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.4.Material", "REDSTONE_BLOCK");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.4.EffectType", "CommandBlock");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.JumpadBlock.1.Material", "EMERALD_BLOCK");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.JumpadBlock.1.VectorCoords.High", 2);
blockFileConfiguration.set("NewOnyxFFa.Config.Block.JumpadBlock.1.VectorCoords.EyeLocationDirectionMovementMultiplier", 2);
lore.clear();
lore.add("give %player% golden_apple 1");
lore.add("give %player% stick 1");
blockFileConfiguration.set("NewOnyxFFa.Config.Block.BlockWithEffects.4.Commands", lore.toArray());
lore.clear();
blockFileConfiguration.save(blockFile);
}
if (!statsFile.exists()) {
statsFile.createNewFile();
statsConfiguration = YamlConfiguration.loadConfiguration(statsFile);
statsConfiguration.set("NewOnyxFFa.Description", "You can use this file to change players stats, using their UUIDS");
statsConfiguration.save(statsFile);
}
if (!arenaFile.exists()) {
arenaFile.createNewFile();
arenaFileConfiguration = YamlConfiguration.loadConfiguration(arenaFile);
arenaFileConfiguration.set("NewOnyxFFa.Description", "You can use this file to add arenas for duels");
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Name", "Alpha");
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.X", 828.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Y", 139.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Z", 840.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Yaw", -90);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Pitch", 0);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.X", 864.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Y", 139.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Z", 840.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Yaw", 90);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Pitch", 0);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Name", "Beta");
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.X", 827.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Y", 139.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Z", 801.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Yaw", -90);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn1.Pitch", 0);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.X", 863.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Y", 139.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Z", 801.5);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Yaw", 90);
arenaFileConfiguration.set("NewOnyxFFa.Arena.Arena1.Spawn2.Pitch", 0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.1.x",654.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.1.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.1.z",902.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.1.yaw",90);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.1.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.2.x",645.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.2.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.2.z",924.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.2.yaw",135);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.2.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.3.x",623.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.3.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.3.z",933.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.3.yaw",180);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.3.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.4.x",602.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.4.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.4.z",924.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.4.yaw",-135);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.4.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.5.x",592.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.5.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.5.z",902.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.5.yaw",-90);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.5.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.6.x",601.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.6.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.6.z",880.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.6.yaw",-45);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.6.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.7.x",623.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.7.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.7.z",871.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.7.yaw",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.7.pitch",0);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.8.x",645.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.8.y",151.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.8.z",880.5);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.8.yaw",45);
arenaFileConfiguration.set("NewOnyxFFa.SumoEvent.Spawns.8.pitch",0);
arenaFileConfiguration.save(arenaFile);
}
if (!ranksFile.exists()) {
ranksFile.createNewFile();
ranksConfiguration = YamlConfiguration.loadConfiguration(ranksFile);
commandsList.add("msg %player% test");
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.Name", "Cuivre");
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.Color", "&e");
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.UpperBound", 1000);
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.LowerBound", 0);
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.RankNumber", 1);
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.CommandsOnGoToRank", commandsList.toArray());
ranksConfiguration.set("NewOnyxFFa.Ranks.Cuivre.CommandsOnLeaveRank", commandsList.toArray());
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.Name", "Argent");
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.Color", "&b");
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.UpperBound", 2000);
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.LowerBound", 1000);
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.RankNumber", 2);
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.CommandsOnGoToRank", commandsList.toArray());
ranksConfiguration.set("NewOnyxFFa.Ranks.Argent.CommandsOnLeaveRank", commandsList.toArray());
ranksConfiguration.save(ranksFile);
}
if (!spawnsFile.exists()) {
spawnsFile.createNewFile();
spawnsConfiguration = YamlConfiguration.loadConfiguration(spawnsFile);
spawnsConfiguration.set("NewOnyxFFa.Spawns.Lobby.WorldName", "world");
spawnsConfiguration.set("NewOnyxFFa.Spawns.Lobby.x", 0);
spawnsConfiguration.set("NewOnyxFFa.Spawns.Lobby.y", 100.0);
spawnsConfiguration.set("NewOnyxFFa.Spawns.Lobby.z", 0);
spawnsConfiguration.set("NewOnyxFFa.Spawns.Lobby.yaw", 0f);
spawnsConfiguration.set("NewOnyxFFa.Spawns.Lobby.pitch", 0f);
spawnsConfiguration.save(spawnsFile);
}
if (!kitsFile.exists()) {
kitsFile.createNewFile();
kitsConfiguration = YamlConfiguration.loadConfiguration(kitsFile);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Material", "ColoredLeather");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Color.R", 255);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Color.G", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Color.B", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Helmet.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Helmet.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Helmet.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Chestplate.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Chestplate.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Chestplate.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Leggings.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Leggings.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Leggings.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Boots.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Boots.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Boots.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Items.1.Type", "Enchanted");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Items.1.Enchantments.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Items.1.Enchantments.1.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Items.1.Enchantments.2.Type", "Enchantment.DAMAGE_ALL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Armor.Items.1.Enchantments.2.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Material", "GOLD_AXE");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Type", "Enchanted");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Slot.Type", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Quantity.Type", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Enchantments.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Enchantments.1.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Enchantments.2.Type", "DURABILITY");
kitsConfiguration.set("NewOnyxFFa.Ffa.Argent.Items.1.Enchantments.2.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Material", "Diamond");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Helmet.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Helmet.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Helmet.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Chestplate.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Chestplate.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Chestplate.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Leggings.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Leggings.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Leggings.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Boots.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Boots.Enchantements.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Armor.Boots.Enchantements.1.Amplifier", 2);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Material", "GOLD_AXE");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Enchantments.1.Type", "PROTECTION_ENVIRONMENTAL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Enchantments.1.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Enchantments.2.Type", "DAMAGE_ALL");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Enchantments.2.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.isDataItem", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.isUnbreakable", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Data", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Slot", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.1.Quantity", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Material", "DIAMOND_PICKAXE");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Enchanted", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Enchantments.1.Type", "DURABILITY");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Enchantments.1.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Enchantments.2.Type", "DIG_SPEED");
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Enchantments.2.Amplifier", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.isDataItem", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.isUnbreakable", true);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Data", 0);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Slot", 1);
kitsConfiguration.set("NewOnyxFFa.Ffa.Cuivre.Items.2.Quantity", 1);
kitsConfiguration.save(kitsFile);
}
if (!messagesFile.exists()) {
messagesFile.createNewFile();
messagesConfiguration = YamlConfiguration.loadConfiguration(messagesFile);
messagesConfiguration.set("NewOnyxFFa.Messages.Welcome.NewPlayer", "Bienvenue à toi %player% sur le RushFFa d'Onyxworld!");
messagesConfiguration.set("NewOnyxFFa.Messages.Welcome.Player", "%player% a rejoint la mêlée! ");
messagesConfiguration.set("NewOnyxFFa.Messages.Welcome.HiddenStaff", "Arrivée incognito sur le Rushffa! Chut...");
messagesConfiguration.set("NewOnyxFFa.Messages.SpawnCommand.Wait", "Téléportation dans %timer% secondes ... Ne bougez pas!");
messagesConfiguration.set("NewOnyxFFa.Messages.SpawnCommand.Error", "Vous avez bougé! Téléportation annulée");
messagesConfiguration.set("NewOnyxFFa.Messages.StatsCommand.Stats", "Voici vos stats: \n Rang : %rank% \n Kills: %kills% \n Morts : %deaths% \n Score: %points%");
messagesConfiguration.set("NewOnyxFFa.Messages.StatsCommand.OtherStats", "Voici les stats de %player%: \n Rang : %rank% \n Kills: %kills% \n Morts : %deaths% \n Score: %points%");
messagesConfiguration.set("NewOnyxFFa.Messages.StatsCommand.OtherNotFound", "Le joueur %player% n'a pas été trouvé...");
messagesConfiguration.set("NewOnyxFFa.Messages.Offa.Spawn.Success", "Point de Spawn ajouté en: %x%, %y%, %z%, %yaw% , %pitch%");
messagesConfiguration.set("NewOnyxFFa.Messages.Offa.Break.Success", "Le Bloc a été cassé avec succès");
messagesConfiguration.set("NewOnyxFFa.Messages.Offa.Break.Error", "Erreur, aucun bloc ciblé!");
messagesConfiguration.set("NewOnyxFFa.Messages.Points.Error", "Erreur. La commande est '/points <arg> <player> <number>");
messagesConfiguration.set("NewOnyxFFa.Messages.Points.PlayerOffline", "Erreur. Le joueur %player% n'est pas connecté.");
messagesConfiguration.set("NewOnyxFFa.Messages.Points.Success", "Le score de %player% est maintenant %score%. Son meilleur score est %highScore%");
messagesConfiguration.set("NewOnyxFFa.Messages.Kill.toKiller", "Vous avez éliminé: %player%");
messagesConfiguration.set("NewOnyxFFa.Messages.Kill.toVictim", "Vous avez été vaincu par: %player%");
messagesConfiguration.set("NewOnyxFFa.Messages.FallenIntoTheVoid.Suicide", "Vous avez essayé le saut à l'élastique... Sans élastique.");
messagesConfiguration.set("NewOnyxFFa.Messages.FallenIntoTheVoid.toVictim", "%player% vous a poussé dans le vide!");
messagesConfiguration.set("NewOnyxFFa.Messages.FallenIntoTheVoid.toKiller", "Vous avez poussé %player% dans le vide!");
messagesConfiguration.set("NewOnyxFFa.Messages.QuitWhileFighting.toKiller", "%player% a fuit le combat... Quel lâche!");
messagesConfiguration.set("NewOnyxFFa.Messages.KilledByFalling.toKiller", "%player% s'est écrasé quelques mètres plus bas.");
messagesConfiguration.set("NewOnyxFFa.Messages.KilledByFalling.toVictim", "%player% vous a fait mordre la poussière... littéralement.");
messagesConfiguration.set("NewOnyxFFa.Messages.KilledByFalling.Suicide", "Vous êtes tombés trop bas!");
messagesConfiguration.set("NewOnyxFFa.Messages.ResetStatsCommand.Success", "Vos statistiques ont été remises à zéro!");
messagesConfiguration.set("NewOnyxFFa.Messages.ResetStatsCommandOther.Error", "Erreur, le joueur %player% n'est pas connecté");
messagesConfiguration.set("NewOnyxFFa.Messages.ResetStatsCommandOther.Success", "Les statistiques de %player% ont été remises à zéro!");
messagesConfiguration.set("NewOnyxFFa.Messages.ChangeAutoRespawn.true", "Vous avez chosi d'activer l'autorespawn");
messagesConfiguration.set("NewOnyxFFa.Messages.ChangeAutoRespawn.false", "Vous avez chosi de désactiver l'autorespawn");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Demand.Sender", "Vous avez bien invité %player% à vous combattre en duel.");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Demand.Asked", "%player% vous invite à combattre en duel ! /duel accept pour accepter ce duel !");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Denied.Sender", "Vous avez refusé le duel avec %player%");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Denied.Asked", "%player% a refusé votre invitation en duel");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Accepted.Sender", "Vous avez accepté le duel avec %player%");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Accepted.Asked", "%player% a accepté votre invitation en duel");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Cancel.Sender", "Vous avez annulé le duel avec %player%");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.Invitation.Cancel.Asked", "%player% a annulé sa demande de duel");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.End.Broadcast", "%winner% a vaincu %loser% en Duel !");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.NotFinished", "Attendez que votre duel finisse !");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.AlreadyInDuel", "%player% est déjà en duel !");
messagesConfiguration.set("NewOnyxFFa.Messages.Duel.InFFAArena", "%player% est occupé à combattre dans le FFA, il doit être au lobby !");
messagesConfiguration.save(messagesFile);
}
} catch (Exception exception) {
exception.printStackTrace();
}
statsConfiguration = YamlConfiguration.loadConfiguration(statsFile);
messagesConfiguration = YamlConfiguration.loadConfiguration(messagesFile);
spawnsConfiguration = YamlConfiguration.loadConfiguration(spawnsFile);
ranksConfiguration = YamlConfiguration.loadConfiguration(ranksFile);
configConfiguration = YamlConfiguration.loadConfiguration(configFile);
kitsConfiguration = YamlConfiguration.loadConfiguration(kitsFile);
blockFileConfiguration = YamlConfiguration.loadConfiguration(blockFile);
arenaFileConfiguration = YamlConfiguration.loadConfiguration(arenaFile);
kitsPlayerDataConfiguration = YamlConfiguration.loadConfiguration(kitsPlayerDataFile);
ranksManager = new RanksManager(this);
spawnManager = new SpawnManager();
fFaPlayerManager = new FFaPlayerManager(this);
locationBuilder = new LocationBuilder(this);
itemBuilder = new ItemBuilder(this);
ffaAnimatedBlocksManager = new FFAAnimatedBlocksManager();
kitsManager = new KitsManager(this);
for (String spawnName : spawnsConfiguration.getConfigurationSection("NewOnyxFFa.Spawns").getKeys(false)) {
if (!spawnName.equalsIgnoreCase("lobby")) {
spawnsList.add(this.getLocationBuilder().getLocation("NewOnyxFFa.Spawns." + spawnName, spawnsConfiguration));
}
}
if(arenaFileConfiguration.get("NewOnyxFFa.SumoEvent.Spawns") != null) {
for (String spawnName : arenaFileConfiguration.getConfigurationSection("NewOnyxFFa.SumoEvent.Spawns").getKeys(false)) {
sumoSpawnList.add(this.getLocationBuilder().getLocation("NewOnyxFFa.SumoEvent.Spawns." + spawnName, arenaFileConfiguration));
}
}
for(String arena : arenaFileConfiguration.getConfigurationSection("NewOnyxFFa.Arena").getKeys(false)){
String arenaName = arenaFileConfiguration.getString("NewOnyxFFa.Arena." + arena + ".Name");
String world = spawnsConfiguration.getString("NewOnyxFFa.Spawns.Lobby.WorldName");
double x1 = arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn1.X");
double y1 = arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn1.Y");
double z1 = arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn1.Z");
float yaw1 = (float) arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn1.Yaw");
float pitch1 = (float) arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn1.Pitch");
double x2 = arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn2.X");
double y2 = arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn2.Y");
double z2 = arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn2.Z");
float yaw2 = (float) arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn2.Yaw");
float pitch2 = (float) arenaFileConfiguration.getDouble("NewOnyxFFa.Arena." + arena + ".Spawn2.Pitch");
Location spawn1 = new Location(Bukkit.getWorld(world), x1,y1,z1,yaw1,pitch1);
Location spawn2 = new Location(Bukkit.getWorld(world), x2,y2,z2,yaw2,pitch2);
arenaManager.addArena(spawn1, spawn2, arenaName);
}
/*
fFaBlockManager = new FFaBlockManager(this);
*/
for (String blockEffect : blockFileConfiguration.getConfigurationSection("NewOnyxFFa.Config.Block.BlockWithEffects").getKeys(false)) {
blockEffectList.add(blockFileConfiguration.getString("NewOnyxFFa.Config.Block.BlockWithEffects." + blockEffect + ".Material"));
}
for (String jumpadBlocks : blockFileConfiguration.getConfigurationSection("NewOnyxFFa.Config.Block.JumpadBlock").getKeys(false)) {
jumpadsBlocks.add(blockFileConfiguration.getString("NewOnyxFFa.Config.Block.JumpadBlock." + jumpadBlocks + ".Material"));
}
}
/*@Override
public void onDisable(){
try {
statsConfiguration.save(statsFile);
configConfiguration.save(configFile);
ranksConfiguration.save(ranksFile);
spawnsConfiguration.save(spawnsFile);
kitsConfiguration.save(kitsFile);
messagesConfiguration.save(messagesFile);
blockFileConfiguration.save(blockFile);
System.out.println(" ");
System.out.println("************************");
System.out.println("[NewOnyxFFA] > ARRET SECURISE");
System.out.println("************************");
System.out.println(" ");
} catch (IOException e) {
e.printStackTrace();
System.out.println(" ");
System.out.println("************************");
System.out.println("[NewOnyxFFA] > ERREUR DE SAUVEGARDE!");
System.out.println("************************");
System.out.println(" ");
}
}
*/
public FileConfiguration getStatsConfiguration() {
return statsConfiguration;
}
public FileConfiguration getRanksConfiguration() {
return ranksConfiguration;
}
public FileConfiguration getConfigConfiguration() {
return configConfiguration;
}
public FileConfiguration getSpawnsConfiguration() {
return spawnsConfiguration;
}
public FileConfiguration getKitsConfiguration() {
return kitsConfiguration;
}
public FileConfiguration getMessagesConfiguration() {
return messagesConfiguration;
}
public FileConfiguration getBlockFileConfiguration() {
return blockFileConfiguration;
}
public FileConfiguration getArenaFileConfiguration() {
return arenaFileConfiguration;
}
public FileConfiguration getKitsPlayerDataConfiguration() {return kitsPlayerDataConfiguration;}
public List<String> getSpawnsInWait() {
return SpawnInWait;
}
public File getStatsFile() {
return statsFile;
}
public File getSpawnsFile() {
return spawnsFile;
}
public File getArenaFile() {
return arenaFile;
}
public File getKitsPlayerDataFile() {return kitsPlayerDataFile;}
public List<String> getBlockEffectList() {
return blockEffectList;
}
public List<Location> getSpawnsList() {
return spawnsList;
}
public File getRanksFile() {
return ranksFile;
}
public RanksManager getRanksManager() {
return ranksManager;
}
public FFaPlayerManager getFFaPlayerManager() {
return fFaPlayerManager;
}
public SpawnManager getSpawnManager() {
return spawnManager;
}
public LocationBuilder getLocationBuilder() {
return locationBuilder;
}
public ItemBuilder getItemBuilder() {
return itemBuilder;
}
public DuelManager getDuelManager() {return duelManager;}
public ArenaManager getArenaManager() {return arenaManager;}
/*
public FFaBlockManager getfFaBlockManager() {
return fFaBlockManager;
}
*/
public List<String> getJumpadsBlocks() {
return jumpadsBlocks;
}
public List<Location> getSumoSpawnList() {
return sumoSpawnList;
}
public SumoSpawnManager getSumoSpawnManager(){
return sumoSpawnManager;
}
public FFAAnimatedBlocksManager getFfaAnimatedBlocksManager() {return ffaAnimatedBlocksManager;};
public KitsManager getKitsManager() {
return kitsManager;
}
/*
public ProtocolManager getProtocolManager() {
return protocolManager;
}
*/
}
|
JavaScript
|
UTF-8
| 1,127
| 3.140625
| 3
|
[] |
no_license
|
class Toolbar{
constructor(btnIds){
//btnIds must be a list of id's of existing buttons
this._btnIds = btnIds
this._buttons = []//actual domnodes will be stored here
this.init()
this._active = null
}
init(){
let len = this._btnIds.length
for (let i = 0;i<len;i++){
this._buttons.push(document.getElementById(this._btnIds[i]))
}
}
setActive(btnId){
let newBtn = document.getElementById(btnId)
if (this._active === null){
this._active = newBtn
this.activateBtn(this._active)
}else if (this._active.id === btnId){
this.deactivateBtn(this._active)
this._active = null
}else{
//there is an active btn but the btnId btn is different
this.deactivateBtn(this._active)
this.activateBtn(newBtn)
this._active = newBtn
}
}
activateBtn(btn){
btn.classList.replace("idle","active")
}
deactivateBtn(btn){
btn.classList.replace("active","idle")
}
}
|
Java
|
UTF-8
| 5,930
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.jifeihu.smartshed.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.jifeihu.smartshed.R;
import org.jifeihu.smartshed.bean.Sensor;
import org.jifeihu.smartshed.interfaces.IConstants;
import org.jifeihu.smartshed.view.activity.SensorDetailActivity;
import org.jifeihu.smartshed.view.activity.ThresholdActivity;
import java.util.List;
public class ItemSensorRecyclerViewAdapter extends RecyclerView.Adapter<ItemSensorRecyclerViewAdapter.ViewHolder> {
private List<Sensor> mSensorList;
private List<Byte> mValues;
private String mImgPrefix;
public void setValues(List<Byte> values) {
mValues = values;
notifyDataSetChanged();
}
public void setSensor(List<Sensor> sensorList) {
mSensorList = sensorList;
notifyDataSetChanged();
}
public void setImgPrefix(String prefix) {
mImgPrefix = prefix;
}
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_sensor, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Sensor sensor = mSensorList.get(position);
Glide.with(holder.typeImageView.getContext())
.load(mImgPrefix+sensor.getImgUrl()).error(R.drawable.ic_soil)
.into(holder.typeImageView);
holder.typeView.setText(sensor.getName());
if(mValues != null) {
holder.valueView.setText("实时值:" + mValues.get(position) + sensor.getUnit());
}else {
holder.valueView.setText("实时值:-- " + sensor.getUnit());
}
holder.areaView.setText(sensor.getAreaName());
holder.nodeView.setText(sensor.getNodeName());
holder.thresholdView.setText("阈值:" + sensor.getThreshold().getMin()+"~"
+sensor.getThreshold().getMax());
}
@Override
public int getItemCount() {
return mSensorList==null?0:mSensorList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView typeView, valueView, thresholdView, areaView, nodeView;
ImageView typeImageView;
ImageButton moreBtn;
ViewHolder(View view) {
super(view);
typeView = (TextView) view.findViewById(R.id.tv_sensor_name);
valueView = (TextView) view.findViewById(R.id.tv_sensor_value);
thresholdView = (TextView) view.findViewById(R.id.tv_sensor_threshold);
areaView = (TextView) view.findViewById(R.id.tv_sensor_area);
nodeView = (TextView) view.findViewById(R.id.tv_sensor_node);
typeImageView = (ImageView) view.findViewById(R.id.tv_sensor_image);
moreBtn = (ImageButton) view.findViewById(R.id.img_btn_more);
moreBtn.setOnClickListener(this);
view.setOnClickListener(this);
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Snackbar.make(v,"进入设置阈值界面?",Snackbar.LENGTH_LONG).setAction("确认",
ViewHolder.this).show();
return true;
}
});
}
@Override
public void onClick(View v) {
int position = ViewHolder.this.getAdapterPosition();
Sensor sensor = mSensorList.get(position);
int id = v.getId();
if(id == R.id.img_btn_more) {
showMenu(v, sensor);
}else if(id == this.itemView.getId()) {
startActivity(v.getContext(), SensorDetailActivity.class, sensor);
}else {
startActivity(v.getContext(), ThresholdActivity.class, sensor);
}
}
}
/**
* 弹出菜单
* @param v
* @param sensor
*/
private void showMenu(final View v, final Sensor sensor) {
PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
popupMenu.inflate(R.menu.menu_item_more);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id==R.id.menu_data_detail) {
startActivity(v.getContext(), SensorDetailActivity.class, sensor);
}else {
startActivity(v.getContext(), ThresholdActivity.class, sensor);
}
return true;
}
});
popupMenu.show();
}
/**
* 跳转到新activity
* @param context
* @param clz
* @param sensor
*/
public void startActivity(Context context, Class<? extends Activity> clz, Sensor sensor) {
Intent intent = new Intent(context, clz);
intent.putExtra(IConstants.KEY_SENSOR_NAME, sensor.getName());
intent.putExtra(IConstants.KEY_SENSOR_ID, sensor.getId());
intent.putExtra(IConstants.KEY_SENSOR_UNIT, sensor.getUnit());
intent.putExtra(IConstants.KEY_THRESHOLD_MIN, sensor.getThreshold().getMin());
intent.putExtra(IConstants.KEY_THRESHOLD_MAX, sensor.getThreshold().getMax());
context.startActivity(intent);
}
}
|
Markdown
|
UTF-8
| 1,081
| 2.703125
| 3
|
[] |
no_license
|
# Express API with Database
This app is build with **Node.js, Express.js, mongoDB and mongoose**. I am learning how to create API. This my first time in backend world. I shall update this codebase as I learn more.
---
## Contributors
_Contributors to this project :_
| username | Email | Name | Address |
| ------------------------------------------- | ----------------------- | ------------------- | ------- |
| [nrishingha](https://github.com/nrishingha) | devoloper.roy@gmail.com | Nrishinghananda Roy | India |
---
## Installation Guidance
1. First open your terminal and navigate to current working directory.
2. Run this command in your terminal $ `npm install`
3. This will create a node_module folder in the current working directory.
4. ### Production
run $ `npm run start:prod` in your terminal. This will execute **nodemon** and RUN **Production** server on _127.0.0.1:3000_
5. ### Development
run $ `npm start` in your terminal. This will execute **nodemon** and RUN **development** server on _127.0.0.1:3000_
|
Java
|
UTF-8
| 3,695
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
package com.sbk.callerid.service;
import com.sbk.callerid.model.CallerId;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
@Service
public class CallerIdService implements ICallerIdService
{
// Local store
private Map<String, Map<String, String>> store = new TreeMap<>();
/**
* Note:
* Sequence of Store Record : number, context, name
* Sequence of CallerId Class : name, number, context
*/
@Autowired
private ResourceLoader resourceLoader;
private static final String CSV_FILE_LOCATION = "data/interview-callerid-data.csv";
@PostConstruct
public void init()
{
System.out.println("Loading data from CSV file to CallerID Store...");
int totalRecords = 0;
Resource resource = resourceLoader.getResource("classpath:" + CSV_FILE_LOCATION);
try
{
InputStream inputStream = resource.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(inputStreamReader);
for (CSVRecord record : records)
{
totalRecords++;
String number = record.get(0);
String context = record.get(1);
String name = record.get(2);
number = PhoneNumberHelper.convertPhoneNumber(number);
//add only valid numbers to store
if(!number.equals(PhoneNumberHelper.INVALID_INPUT))
{
add(new CallerId(name, number, context));
}
}
}
catch (Exception e)
{
System.err.println("Can't load or parse CSV file: " + CSV_FILE_LOCATION);
}
System.out.println("Loaded total [ " + store.size() + " / " + totalRecords + " ] records.");
}
public boolean add(CallerId record)
{
if (null == store.get(record.getNumber()))
{
Map<String, String> newContext = new TreeMap<>();
newContext.put(record.getContext(), record.getName());
store.put(record.getNumber(), newContext);
}
else
{
Map<String, String> currentContext = store.get(record.getNumber());
if (currentContext.get(record.getContext()) == null)
{
currentContext.put(record.getContext(), record.getName());
}
else
{
//context already exists for the phone number, throw error
System.err.println("Context already exists for the phone number: " + record.toString());
return false;
}
}
return true;
}
public List<CallerId> get(String number)
{
List<CallerId> result = new ArrayList<>();
if (null != store.get(number))
{
Map<String, String> currentContext = store.get(number);
for (Map.Entry<String, String> entry : currentContext.entrySet())
{
CallerId record = new CallerId(entry.getValue(), number, entry.getKey());
result.add(record);
}
}
return result;
}
public boolean contains(String number)
{
return store.containsKey(number);
}
}
|
Python
|
UTF-8
| 18,257
| 3.546875
| 4
|
[] |
no_license
|
from collections import deque
#***************************
# Solution summary:
# - Create a deque representing the coords (row,col) of the route the train track takes (piece by piece). Each element in the deque is a tuple. One route-deque for each train.
# - As the train moves around the track, ROTATE the deques so the first element in the deque is the coords of the ENGINE of the train
# - There will be another, smaller deque for each train. Each represents ONLY the current coords of each engine and its carriages
# - Collisions between trains OR a train hitting itself are detected by checking if any tuple in either deque is repeated (as this means two engines/carriages are in the same spot on the route)
#***************************
def find_next_position(row, col, compass_direction, map_list):
if compass_direction == "N": # from here N is valid
if map_list[row-1][col] in ["|", "+", "/", "\\", "S"]: # valid track pieces north of here (double-backslash needed as single-backslash is an escape sequence marker!)
#print("valid track piece north of here!")
row -=1
if map_list[row][col] == "/": compass_direction = "NE"
if map_list[row][col] == "\\": compass_direction = "NW"
if map_list[row][col] in ["|", "+", "S"]: compass_direction = "N"
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "E": # from here E is valid
if map_list[row][col+1] in ["-", "+", "/", "\\", "S"]: # valid track pieces east of here
#print("valid track piece east of here!")
col +=1
if map_list[row][col] == "/": compass_direction = "NE"
if map_list[row][col] == "\\": compass_direction = "SE"
if map_list[row][col] in ["-", "+", "S"]: compass_direction = "E"
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "W": # from here W is valid
if map_list[row][col-1] in ["-", "+", "/", "\\", "S"]: # valid track pieces west of here
#print("valid track piece west of here!")
col -=1
if map_list[row][col] == "/": compass_direction = "SW"
if map_list[row][col] == "\\": compass_direction = "NW"
if map_list[row][col] in ["-", "+", "S"]: compass_direction = "W"
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "S": # from here S is valid
if map_list[row+1][col] in ["|", "+", "/", "\\", "S"]: # valid track pieces south of here
#print("valid track piece south of here!")
row +=1
if map_list[row][col] == "/": compass_direction = "SW"
if map_list[row][col] == "\\": compass_direction = "SE"
if map_list[row][col] in ["|", "+", "S"]: compass_direction = "S"
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "NE": # from here N, NE, E are valid
if map_list[row-1][col] in ["|", "+"]: # valid track pieces north of here
#print("valid track piece north of here")
compass_direction = "N"
row -=1
elif map_list[row-1][col+1] in ["/", "X", "S"]: # valid track pieces north-east of here
#print("valid track piece north-east of here!")
compass_direction = "NE"
row -=1
col +=1
elif map_list[row][col+1] in ["-", "+"]: # valid track pieces east of here
#print("valid track piece east of here!")
compass_direction = "E"
col +=1
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "SE": # from here E, SE, S are valid
if map_list[row][col+1] in ["-", "+"]: # valid track pieces east of here
#print("valid track piece east of here")
compass_direction = "E"
col +=1
elif map_list[row+1][col+1] in ["\\", "X", "S"]: # valid track pieces south-east of here
#print("valid track piece south-east of here!")
compass_direction = "SE"
row +=1
col +=1
elif map_list[row+1][col] in ["|", "+"]: # valid track pieces south of here
#print("valid track piece south of here!")
compass_direction = "S"
row +=1
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "SW": # from here S, SW, W are valid:
if map_list[row+1][col] in ["|", "+"]: # valid track pieces south of here
#print("valid track piece south of here!")
compass_direction = "S"
row +=1
elif map_list[row+1][col-1] in ["/", "X", "S"]: # valid track pieces south-west of here
#print("valid track piece south-west of here!")
compass_direction = "SW"
row +=1
col -=1
elif map_list[row][col-1] in ["-", "+"]: # valid track pieces west of here
#print("valid track piece west of here!")
compass_direction = "W"
col -=1
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
elif compass_direction == "NW": # from here W, NW, N are valid:
if map_list[row][col-1] in ["-", "+"]: # valid track pieces west of here
#print("valid track piece west of here!")
compass_direction = "W"
col -=1
elif map_list[row-1][col-1] in ["\\", "X", "S"]: # valid track pieces north-west of here
#print("valid track piece north-west of here!")
compass_direction = "NW"
row -=1
col -=1
elif map_list[row-1][col] in ["|", "+"]: # valid track pieces north of here
#print("valid track piece north of here!")
compass_direction = "N"
row -=1
else:
print("***************** WARNING - TRACK ERROR - DERAILMENT INEVITABLE!! *****************")
return row, col, compass_direction, map_list[row][col] == "S"
#*******************************************************
#
def train_crash(track, a_train, a_train_pos, b_train, b_train_pos, limit):
#print("a_train",a_train)
#print("a_train_pos",a_train_pos)
#print("b_train",b_train)
#print("b_train_pos",b_train_pos)
#print("limit",limit)
map_list = track.split("\n")
#print("last line",map_list[len(map_list)-1])
if map_list[len(map_list)-1].strip() == "": # the occasional map has a blank last line so remove it
map_list.pop()
max_string_len = 0
for i in map_list:
max_string_len = max(max_string_len,len(i.rstrip())) # find out which string is the longest - this will be our map width
# Note that the rstrip() function is needed as some lines of the map have trailing spaces which we
# do not want to count
for i in range(0, len(map_list)):
map_list[i] = "*" + map_list[i].rstrip() + (" " * (max_string_len - len(map_list[i].rstrip() ))) + "*" # place an asterisk at the start and end of each line in the map
map_list.insert(0, ("*" * (max_string_len + 2))) # add a line of ***'s to the top and bottom of the map. The map is now trimmed of all unnecessary spaces and surrounded
map_list.append("*" * (max_string_len + 2)) # by a border of ***'s. This border makes the route-finder function "find_next_position" simpler as there is no need to
# to test for index out of bounds when trying to find the next valid piece of track
#print("map:")
#for i in map_list:
# print(i)
row = 1
col = map_list[row].index("/") # "Position Zero" is always the first non-blank char on top line (row 1 once border of ***'s is added)
# The track shape in this position will ALWAYS be "/" because we know the track is a circuit, and
# that circuit must re-join the top line with a "/" track piece! Simple, and handy!
# idx is the column in which "Position Zero" is found.
dq_a_train_coords = deque([]) # Both trains have identical routes as they follow the same track. They have the potential to follow the route in a different manner,
dq_b_train_coords = deque([]) # e.g. different start points, express trains (Xxxx) don't stop at stations, any train can travel either clockwise or anti-clockwise
a_train_length = len(a_train)
b_train_length = len(b_train)
set_of_stations = set()
zero_position_coords = (row,col) # create a tuple with row,col as elements
compass_direction = "E"
track_complete = False
current_coords = tuple(zero_position_coords)
dq_a_train_coords.append(zero_position_coords) # The deque for each train route is made up of tuples of coordinates. Each tuple contains a "row" and "column" coord,
dq_b_train_coords.append(zero_position_coords) # so the tuples represent the track-route on a track-piece by track-piece basis. Each deque begins at "Position Zero"
while not track_complete:
row, col, compass_direction, at_station = find_next_position(row, col, compass_direction, map_list) # feed in current position, direction and the map, and this function will
# return the coords, direction and boolean at_station of the next track piece
if (row,col) == zero_position_coords: # if we find ourselves back at Position Zero, route is mapped!
track_complete = True
continue # "contine" command will bring us immediately back to the while loop which we will then immediately exit
tupled_coords = (row,col) # Create a tuple out of row and col returned from the find_next_position function
dq_a_train_coords.append(tupled_coords) # Add that new tuple to each deque
dq_b_train_coords.append(tupled_coords)
if at_station: # Add the coords as a tuple as we cannot add lists to sets because lists are mutable!
set_of_stations.add((row,col)) # Double-parenthesis "(())" required here to designate (row,col) as a single element (a tuple)
# rather than row,col (two integers)
#print("set_of_stations",set_of_stations)
#print("A deque",dq_a_train_coords)
# We now have 2 deques, one for the route of Train A, one for the route of Train B. They're identical for now.
# Although their contents won't change, the order of the content will as deques are rotated to reflect train position
# Depending on whether we're going clockwise or anti-clockwise, we set up a_train_direction variable. Train direction is determined by where the Engine is
# in relation to the carriages. Engine is designated by upper case letter, carriages by lower case. Engine will always be in either first or last position.
if a_train[0].upper() == a_train[0]: # e.g. Aaaaa, train is going anti-clockwise from Point Zero,
a_train_direction = 1 # we'll rotate backwards through deque (i.e. deque 1,2,3,4 becomes 4,1,2,3 when rotated by 1)
else: # Else we must have e.g. aaaaA, i.e. train is going clockwise from Point Zero
a_train_direction = -1 # we'll rotate forwards through deque (i.e. deque 1,2,3,4 becomes 2,3,4,1 when rotated by -1)
# Bring Train A to its starting point. Train position is always clockwise from Point Zero, irrespective of whether train direction is clockwise or anti-clockwise:
if a_train_pos != 0:
dq_a_train_coords.rotate(a_train_pos * -1) # rotate deque as far as needed (a_train_pos => rotate this many times, -1 => clockwise)
# Set up Train B direction as per Train A above:
if b_train[0].upper() == b_train[0]:
b_train_direction = 1
else:
b_train_direction = -1
# Bring Train B to its starting point:
if b_train_pos != 0:
dq_b_train_coords.rotate(b_train_pos * -1)
# We now want to populate two more deques, each representing ONLY the current coords of Train A and Train B engines and carriages:
dq_a_train_and_carriages = deque([], maxlen = a_train_length) # the maxlen property ensures that as we add elements to one end of the deque, they are removed from the other end if maxlen exceeded
for i in range(0, a_train_length):
dq_a_train_and_carriages.append(dq_a_train_coords[i * a_train_direction])
dq_b_train_and_carriages = deque([], maxlen = b_train_length)
for i in range(0, b_train_length):
dq_b_train_and_carriages.append(dq_b_train_coords[i * b_train_direction])
#print("A-Train+Cars",dq_a_train_and_carriages)
#print("B-Train+Cars",dq_b_train_and_carriages)
#print ("initial_coords A:",dq_a_train_coords[0])
#print ("initial_coords B:",dq_b_train_coords[0])
# Next up we move the trains one step at a time for up to "limit" number of steps.
# Also, build in a loop-delay whenever a non express train reaches a station.
# Create a set for each train (& carriages) after each move and test INTERSECT of sets
# If any common elements => TRAIN CRASH!!!
a_train_station_delay = 0
b_train_station_delay = 0
for time_step in range(0, limit+1):
#print("T=", time_step, "Engine A=", dq_a_train_coords[0], "Engine B=", dq_b_train_coords[0])
#print("Full A:", dq_a_train_and_carriages)
#print("Full B:", dq_b_train_and_carriages)
# ****** COLLISION DETECTIONS *************
# Between the two trains:
for i in dq_a_train_and_carriages: # If the engine or any carriage of a_train shares the coords with
if i in dq_b_train_and_carriages: # the engine or any carriage of b_train, COLLISION!
print("return",time_step)
return time_step # Return "when" the collision happened
# One train hitting itself is also possible (remember "Snake" game!) - convert deque A to set. If set is shorter => duplicate coords in deque => COLLISION!
test_collision_set = set(dq_a_train_and_carriages)
if len(test_collision_set) != len(dq_a_train_and_carriages):
print("return (self-collision A)",time_step)
return time_step # Return "when" the collision happened
# One train hitting itself is also possible (remember "Snake" game!) - convert deque B to set. If set is shorter => duplicate coords in deque => COLLISION!
test_collision_set = set(dq_b_train_and_carriages)
if len(test_collision_set) != len(dq_b_train_and_carriages):
print("return (self-collision B)",time_step)
return time_step # Return "when" the collision happened
# move the trains along unless the relevant train_station_delay is > 0
if a_train_station_delay > 0:
a_train_station_delay -= 1
if a_train_station_delay == 0:
dq_a_train_coords.rotate(a_train_direction)
dq_a_train_and_carriages.appendleft(dq_a_train_coords[0]) # the new coord replaces where train was and all other coords move back 1 (the last coord "falls off")
else:
dq_a_train_coords.rotate(a_train_direction)
dq_a_train_and_carriages.appendleft(dq_a_train_coords[0]) # the new coord replaces where train was and all other coords move back 1 (the last coord "falls off")
if b_train_station_delay > 0:
b_train_station_delay -= 1
if b_train_station_delay == 0:
dq_b_train_coords.rotate(b_train_direction)
dq_b_train_and_carriages.appendleft(dq_b_train_coords[0]) # the new coord replaces where train was and all other coords move back 1 (the last coord "falls off")
else:
dq_b_train_coords.rotate(b_train_direction)
dq_b_train_and_carriages.appendleft(dq_b_train_coords[0]) # the new coord replaces where train was and all other coords move back 1 (the last coord "falls off")
# if train is at a station, set delay before departure unless train is Express (X) or timer already underway
if dq_a_train_coords[0] in set_of_stations \
and a_train[0].upper() != "X" \
and a_train_station_delay == 0:
a_train_station_delay = a_train_length
# if train is at a station, set delay before departure unless train is Express (X) or timer already underway
if dq_b_train_coords[0] in set_of_stations \
and b_train[0].upper() != "X" \
and b_train_station_delay == 0:
b_train_station_delay = b_train_length
print("return -1")
return -1
|
Python
|
UTF-8
| 202
| 3.359375
| 3
|
[] |
no_license
|
data = input().split()
products = {}
for index in range(0, len(data), 2):
current_product = data[index]
quantity = data[index + 1]
products[current_product] = int(quantity)
print(products)
|
C++
|
UTF-8
| 2,999
| 3.453125
| 3
|
[] |
no_license
|
#include <cstdio>
struct Node {
int val;
int height;
Node* left;
Node* right;
Node(int v, Node* l=0, Node* r=0, int h=0)
: val(v), left(l), right(r), height(h)
{}
};
int getHeight(Node* root) {
if (root == 0) {
return 0;
}
else {
return root->height;
}
}
int max(int v1, int v2) {
return ((v1 > v2) ? v1 : v2);
}
void singleRotateRight(Node*& root) {
Node* temp = root->right;
root->right = temp->left;
temp->left = root;
root = temp;
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
temp->height = max(root->height, getHeight(temp->right)) + 1;
}
void singleRotateLeft(Node*& root) {
Node* temp = root->left;
root->left = temp->right;
temp->right = root;
root = temp;
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
temp->height = max(getHeight(temp->left), root->height) + 1;
}
void doubleRotateRight(Node*& root) {
singleRotateLeft(root->right);
singleRotateRight(root);
}
void doubleRotateLeft(Node*& root) {
singleRotateRight(root->left);
singleRotateLeft(root);
}
void insert(Node*& root, int x) {
if(root == 0) {
root = new Node(x);
return;
}
if(x > root->val) {
insert(root->right, x);
//printf("H right: %d , H left: %d\n",getHeight(root->right), getHeight(root->left));
if (getHeight(root->right) - getHeight(root->left) == 2 ) {
//printf("Right");
if ( x > root->right->val)
singleRotateRight(root);
else
doubleRotateRight(root);
}
}
else if(x < root->val) {
insert(root->left, x);
//printf("H right: %d , H left: %d, diff: %d \n",getHeight(root->right), getHeight(root->left), getHeight(root->right) - getHeight(root->left));
if (getHeight(root->right) - getHeight(root->left) == -2) {
//printf("Left");
if ( x < root-> left->val)
singleRotateLeft(root);
else
doubleRotateLeft(root);
}
}
root->height = max(getHeight(root->left),getHeight(root->right)) + 1;
}
int search(Node*& root, int x) {
if(root == 0) {
return 0;
}
else {
if(x == root->val) {
return 1;
}
else {
if(x > root->val)
return (search(root->right, x));
else if(x < root->val)
return (search(root->left, x));
}
}
}
void print_bst(Node*& root, int count) {
count++;
if(root->right != 0)
print_bst(root->right, count);
for(int i = 0; i < count ; i++) {
printf("...");
}
printf("* %d\n", root->val);
if(root->left != 0)
print_bst(root->left, count);
}
main() {
int n, cmd, val;
scanf("%d", &n);
int result[n];
Node* r = 0;
for (int i = 0 ; i < n ; i++) {
scanf("%d %d", &cmd, &val);
if(cmd == 1) {
insert(r,val);
result[i] = 2;
}
else if (cmd == 2) {
if (search(r,val) == 1 ) {
//printf("1\n");
result[i] = 1;
}
else if (search(r,val) == 0) {
//printf("0\n");
result[i] = 0;
}
}
//print_bst(r, -1);
}
for (int i = 0 ;i < n; i++) {
if (result[i] == 0)
printf("%d\n", result[i]);
else if (result[i] == 1)
printf("%d\n", result[i]);
}
}
|
Java
|
UTF-8
| 22,933
| 1.640625
| 2
|
[] |
no_license
|
package com.example.madcampproject2;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.location.LocationManager;
import android.media.Image;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.kakao.auth.AuthType;
import com.kakao.auth.ISessionCallback;
import com.kakao.auth.Session;
import com.kakao.network.ErrorResult;
import com.kakao.usermgmt.UserManagement;
import com.kakao.usermgmt.callback.LogoutResponseCallback;
import com.kakao.usermgmt.callback.MeV2ResponseCallback;
import com.kakao.usermgmt.response.MeV2Response;
import com.kakao.usermgmt.response.model.Profile;
import com.kakao.usermgmt.response.model.UserAccount;
import com.kakao.util.OptionalBoolean;
import com.kakao.util.exception.KakaoException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import io.socket.client.IO;
import io.socket.client.Manager;
import io.socket.client.Socket;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private boolean isLogin = false;
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_CODE = 100;
String[] REQUIRED_PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
private SessionCallback sessionCallback = new SessionCallback();
Session session;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
LoginResult.reset();
if (!checkLocationServicesStatus()) {
showDialogForLocationServiceSetting();
} else {
checkRunTimePermission();
}
try {
Log.e("socket on map::", "socket is opened 1");
LoginResult.setSocket(IO.socket("http://192.249.18.141:443"));
LoginResult.getSocket().connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
session = Session.getCurrentSession();
session.addCallback(sessionCallback);
LoginResult.setRetrofit(new Retrofit.Builder()
.baseUrl(LoginResult.getBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.build()
);
LoginResult.setRetrofitInterface(LoginResult.getRetrofit().create(RetrofitInterface.class));
Button btnLogin = findViewById(R.id.btn_login);
Button btnSignUp = findViewById(R.id.btn_signup);
FloatingActionButton btnLogout = findViewById(R.id.btn_logout);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleLoginDialog();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleSignupDialog();
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UserManagement.getInstance()
.requestLogout(new LogoutResponseCallback() {
@Override
public void onCompleteLogout() {
Toast.makeText(MainActivity.this, "로그아웃 되었습니다.", Toast.LENGTH_SHORT).show();
setInActive();
}
});
}
});
getAppKeyHash();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onRestart() {
super.onRestart();
}
private void handleLoginDialog() {
View view = getLayoutInflater().inflate(R.layout.dialog_login, null);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(view);
AlertDialog dialog = builder.create(); // Helper for dismiss();
dialog.show();
Button loginBtn = view.findViewById(R.id.login);
final EditText emailEdit = view.findViewById(R.id.emailEdit);
final EditText passwordEdit = view.findViewById(R.id.passwordEdit);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss(); // Need to handle dialog with dismiss function;
HashMap<String, Object> map = new HashMap<>();
map.put("email", emailEdit.getText().toString());
map.put("password", passwordEdit.getText().toString());
Call<User> call = LoginResult.getRetrofitInterface().executeLogin(map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.code() == 200) {
LoginResult.setLoginUser(response.body());
LoginResult.setIsLogin(true);
Intent intent = new Intent(getApplicationContext(), LobbyActivity.class);
startActivity(intent);
finish();
} else if (response.code() == 404) {
Toast.makeText(MainActivity.this, "Wrong Credentials",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
});
}
private void handleSignupDialog() {
View view = getLayoutInflater().inflate(R.layout.dialog_signup, null);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(view);
AlertDialog dialog = builder.create(); // Helper for dismiss();
dialog.show();
Button signupBtn = view.findViewById(R.id.signup);
final EditText nameEdit = view.findViewById(R.id.nameEdit);
final EditText emailEdit = view.findViewById(R.id.emailEdit);
final EditText passwordEdit = view.findViewById(R.id.passwordEdit);
signupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss(); // Need to handle dialog with dismiss function;
HashMap<String, Object> map = new HashMap<>();
map.put("name", nameEdit.getText().toString());
map.put("email", emailEdit.getText().toString());
map.put("password", passwordEdit.getText().toString());
Call<Void> call = LoginResult.getRetrofitInterface().executeSignup(map);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.code() == 200) {
Toast.makeText(MainActivity.this,
"Signed up successfully", Toast.LENGTH_LONG).show();
LoginResult.getLoginUser().setName(nameEdit.getText().toString());
LoginResult.getLoginUser().setEmail(emailEdit.getText().toString());
LoginResult.getLoginUser().setPassword(passwordEdit.getText().toString());
LoginResult.getLoginUser().setScore(0);
LoginResult.setIsLogin(true);
Intent intent = new Intent(getApplicationContext(), LobbyActivity.class);
startActivity(intent);
finish();
} else if (response.code() == 400) {
Toast.makeText(MainActivity.this, "Already registered", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
});
}
private void getAppKeyHash() {
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
Log.e("Hash key", something);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e("name not found", e.toString());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 세션 콜백 삭제
Session.getCurrentSession().removeCallback(sessionCallback);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// 카카오톡|스토리 간편로그인 실행 결과를 받아서 SDK로 전달
if (Session.getCurrentSession().handleActivityResult(requestCode, resultCode, data)) {
return;
}
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GPS_ENABLE_REQUEST_CODE) {//사용자가 GPS 활성 시켰는지 검사
if (checkLocationServicesStatus()) {
if (checkLocationServicesStatus()) {
Log.d("@@@", "onActivityResult : GPS 활성화 되있음");
checkRunTimePermission();
}
}
}
}
private class SessionCallback implements ISessionCallback {
// 로그인에 성공한 상태
@Override
public void onSessionOpened() {
Log.e("onSessionOpened", "open");
requestMe();
}
// 로그인에 실패한 상태
@Override
public void onSessionOpenFailed(KakaoException exception) {
Log.e("SessionCallback :: ", "onSessionOpenFailed : " + exception.getMessage());
}
// 사용자 정보 요청
public void requestMe() {
Log.e("Debug", "Hello");
UserManagement.getInstance()
.me(new MeV2ResponseCallback() {
@Override
public void onSessionClosed(ErrorResult errorResult) {
Log.e("KAKAO_API", "세션이 닫혀 있음: " + errorResult);
}
@Override
public void onFailure(ErrorResult errorResult) {
Log.e("KAKAO_API", "사용자 정보 요청 실패: " + errorResult);
}
@Override
public void onSuccess(MeV2Response result) {
UserAccount kakaoAccount = result.getKakaoAccount();
if (kakaoAccount != null) {
// 이메일
String email = kakaoAccount.getEmail();
if (email != null) Log.i("KAKAO_API", "email: " + email);
else if (kakaoAccount.emailNeedsAgreement() == OptionalBoolean.TRUE) { }
else { }
// 프로필
Profile profile = kakaoAccount.getProfile();
if (profile != null) {
Log.i("KAKAO_API", "nickname: " + profile.getNickname());
Log.i("KAKAO_API", "profile image: " + profile.getProfileImageUrl());
Log.i("KAKAO_API", "thumbnail image: " + profile.getThumbnailImageUrl());
} else if (kakaoAccount.profileNeedsAgreement() == OptionalBoolean.TRUE) { }
else { }
HashMap<String, Object> map = new HashMap<>();
map.put("name", profile.getNickname());
map.put("email", kakaoAccount.getEmail());
map.put("isactive", false);
Call<Void> call = LoginResult.getRetrofitInterface().executeSignup(map);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.code() == 200) {
Toast.makeText(MainActivity.this, "Signed up console.log(\"<5>\")successfully", Toast.LENGTH_LONG).show();
} else if (response.code() == 400) {
Toast.makeText(MainActivity.this, "Already registered", Toast.LENGTH_LONG).show();
}
LoginResult.getLoginUser().setName(profile.getNickname());
LoginResult.getLoginUser().setEmail(kakaoAccount.getEmail());
LoginResult.getLoginUser().setPassword("NoPassword");
LoginResult.getLoginUser().setScore(0);
LoginResult.setIsLogin(true);
Intent intent = new Intent(getApplicationContext(), LobbyActivity.class);
startActivity(intent);
finish();
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
});
}
}
/*
* ActivityCompat.requestPermissions를 사용한 퍼미션 요청의 결과를 리턴받는 메소드입니다.
*/
@Override
public void onRequestPermissionsResult(int permsRequestCode,
@NonNull String[] permissions,
@NonNull int[] grandResults) {
super.onRequestPermissionsResult(permsRequestCode, permissions, grandResults);
if ( permsRequestCode == PERMISSIONS_REQUEST_CODE && grandResults.length == REQUIRED_PERMISSIONS.length) {
// 요청 코드가 PERMISSIONS_REQUEST_CODE 이고, 요청한 퍼미션 개수만큼 수신되었다면
boolean check_result = true;
// 모든 퍼미션을 허용했는지 체크합니다.
for (int result : grandResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
check_result = false;
break;
}
}
if ( check_result ) {
//위치 값을 가져올 수 있음
;
}
else {
// 거부한 퍼미션이 있다면 앱을 사용할 수 없는 이유를 설명해주고 앱을 종료합니다.2 가지 경우가 있습니다.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_PERMISSIONS[0])
|| ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_PERMISSIONS[1])) {
Toast.makeText(MainActivity.this, "퍼미션이 거부되었습니다. 앱을 다시 실행하여 퍼미션을 허용해주세요.", Toast.LENGTH_LONG).show();
finish();
}else {
Toast.makeText(MainActivity.this, "퍼미션이 거부되었습니다. 설정(앱 정보)에서 퍼미션을 허용해야 합니다. ", Toast.LENGTH_LONG).show();
}
}
}
}
void checkRunTimePermission(){
//런타임 퍼미션 처리
// 1. 위치 퍼미션을 가지고 있는지 체크합니다.
int hasFineLocationPermission = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED) {
// 2. 이미 퍼미션을 가지고 있다면
// ( 안드로이드 6.0 이하 버전은 런타임 퍼미션이 필요없기 때문에 이미 허용된 걸로 인식합니다.)
// 3. 위치 값을 가져올 수 있음
} else { //2. 퍼미션 요청을 허용한 적이 없다면 퍼미션 요청이 필요합니다. 2가지 경우(3-1, 4-1)가 있습니다.
// 3-1. 사용자가 퍼미션 거부를 한 적이 있는 경우에는
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, REQUIRED_PERMISSIONS[0])) {
// 3-2. 요청을 진행하기 전에 사용자가에게 퍼미션이 필요한 이유를 설명해줄 필요가 있습니다.
Toast.makeText(MainActivity.this, "이 앱을 실행하려면 위치 접근 권한이 필요합니다.", Toast.LENGTH_LONG).show();
// 3-3. 사용자게에 퍼미션 요청을 합니다. 요청 결과는 onRequestPermissionResult에서 수신됩니다.
ActivityCompat.requestPermissions(MainActivity.this, REQUIRED_PERMISSIONS,
PERMISSIONS_REQUEST_CODE);
} else {
// 4-1. 사용자가 퍼미션 거부를 한 적이 없는 경우에는 퍼미션 요청을 바로 합니다.
// 요청 결과는 onRequestPermissionResult에서 수신됩니다.
ActivityCompat.requestPermissions(MainActivity.this, REQUIRED_PERMISSIONS,
PERMISSIONS_REQUEST_CODE);
}
}
}
//여기부터는 GPS 활성화를 위한 메소드들
private void showDialogForLocationServiceSetting() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n"
+ "위치 설정을 수정하실래요?");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent
= new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void setInActive() {
LoginResult.getLoginUser().setIsActive(false);
// Send two user's information to server
HashMap<String, Object> map = new HashMap<>();
LoginResult.getLoginUser().setIsActive(false);
map.put("email", LoginResult.getLoginUser().getEmail());
map.put("isactive", LoginResult.getLoginUser().getIsActive());
Call<Void> call = LoginResult.getRetrofitInterface().executeInActive(map);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.code() == 200) {
Toast.makeText(MainActivity.this,
"Send to Server successfully", Toast.LENGTH_LONG).show();
} else if (response.code() == 405) {
Toast.makeText(MainActivity.this,
"Failed to send ", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
|
PHP
|
UTF-8
| 492
| 2.65625
| 3
|
[] |
no_license
|
<?php
/*
Yes, randomly generated image, very simple code.
If you use it please credit to fedekiller.
*/
header ("Content-type: image/gif");
$string = htmlspecialchars(strip_tags(stripslashes($_GET['code'])), ENT_QUOTES);
$image = @imagecreate (50,15) ;
$black = imagecolorallocate ($image, 0, 0, 0);
$white = imagecolorallocate ($image, 255, 255, 255);
imageline ($image, 0, 8.5, 50, 8.5, $white);
imagestring ($image, 2, 10, 1, $string, $white);
imagegif ($image);
imagedestroy ($image);
?>
|
Python
|
UTF-8
| 554
| 2.84375
| 3
|
[] |
no_license
|
import random,time
COL,ROW=30,30
init=lambda:[[random.randint(0,1) for j in range(ROW)] for i in range(COL)]
neig=lambda c,x,y:sum([c[(x+i+COL)%COL][(y+j+ROW)%ROW] for j in [0,1,-1] for i in [0,1,-1]][1:])
nexT=lambda c:[[1 if neig(c,i,j)==3 else (c[i][j] if neig(c,i,j)==2 else 0) for j in range(ROW)] for i in range(COL)]
prin=lambda c:print('\n'.join([''.join(['[]' if c[i][j]==1 else ' ' for j in range(ROW)]) for i in range(COL)]))
life=lambda c=init():prin(c) or print(''.join(['--' for i in range(ROW)])) or time.sleep(1) or life(nexT(c))
life()
|
Shell
|
UTF-8
| 1,611
| 3.453125
| 3
|
[] |
no_license
|
#!/bin/bash
set -e
echo "Installing Lattice - Diego Cell"
LATTICE_DIEGO_CELL_BUILD_PATH=$1
if [ -z "$LATTICE_DIEGO_CELL_BUILD_PATH" ]; then
LATTICE_DIEGO_CELL_BUILD_PATH='.'
fi
install_dependencies() {
echo "Installing Dependencies..."
pushd /tmp
SHADOW_TAR_OBJECT_ID="8f17023f-2a94-4d98-a737-ddbf166e7188"
wget "http://go-diego-go.s3.amazonaws.com/${SHADOW_TAR_OBJECT_ID}" -O - | tar xzf -
pushd shadow-4.2.1
./configure --prefix=/var/lattice
make
make install
popd
popd
}
cp $LATTICE_DIEGO_CELL_BUILD_PATH/upstart/* /etc/init
cp -n $LATTICE_DIEGO_CELL_BUILD_PATH/bin/* /usr/local/bin
mkdir -p /var/lattice/garden
mkdir -p /var/lattice/garden/depot
mkdir -p /var/lattice/garden/rootfs
mkdir -p /var/lattice/garden/overlays
mkdir -p /var/lattice/garden/graph
cp -a $LATTICE_DIEGO_CELL_BUILD_PATH/garden/garden-bin /var/lattice/garden/garden-bin
cp -a $LATTICE_DIEGO_CELL_BUILD_PATH/garden/skeleton /var/lattice/garden/skeleton
mkdir -p /var/lattice/config
cp -a $LATTICE_DIEGO_CELL_BUILD_PATH/config /var/lattice
mkdir -p /var/lattice/setup
cp -a $LATTICE_DIEGO_CELL_BUILD_PATH/setup /var/lattice
apt-get -y update
apt-get -y install gcc
apt-get -y install make
apt-get -y install quota
apt-get -y install linux-image-extra-$(uname -r)
apt-get -y install curl
mkdir -p /var/lattice/run
mkdir -p /var/lattice/log
install_dependencies &> /var/lattice/log/diego-cell-install.log
start lattice-diego-cell-bootstrap
export $(cat /var/lattice/setup/lattice-environment)
echo "Finished Installing Lattice Diego-Cell!"
|
Markdown
|
UTF-8
| 294
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
# Free Thrower
Training a neural network to shoot basketball free throws consistantly.
## Initial plan:

# Results
We can see that the "Shooters" learn to shoot the basketballs to the right, but not too strong to overshoot the hoop.

|
Java
|
UTF-8
| 253
| 2.40625
| 2
|
[] |
no_license
|
package TowerDefense;
public class ImageObject extends GameEntity {
public ImageObject(String path) {
super(path);
}
/*
public void setLayoutPosition(int x, int y) {
setLayoutX(x);
setLayoutY(y);
}
*/
}
|
Python
|
UTF-8
| 1,632
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
import pytest
def assert_instrument_response(device, query, data):
response = device.query(query)
assert response == data, "%s, %r == %r" % (device.resource_name, query, data)
@pytest.mark.parametrize(
"resource",
[
"ASRL1::INSTR",
"GPIB0::8::INSTR",
"TCPIP0::localhost:1111::inst0::INSTR",
"USB0::0x1111::0x2222::0x1234::0::INSTR",
],
)
def test_instrument_with_channel_preselection(resource, channels):
inst = channels.open_resource(
resource,
read_termination="\n",
write_termination="\r\n" if resource.startswith("ASRL") else "\n",
)
assert_instrument_response(inst, "I?", "1")
assert_instrument_response(inst, "F?", "1.000")
inst.write("F 5.0")
assert_instrument_response(inst, "F?", "5.000")
assert_instrument_response(inst, "I 2;F?", "1.000")
inst.close()
@pytest.mark.parametrize(
"resource",
[
"ASRL2::INSTR",
"GPIB0::9::INSTR",
"TCPIP0::localhost:2222::inst0::INSTR",
"USB0::0x1111::0x2222::0x2468::0::INSTR",
],
)
def test_instrument_with_inline_selection(resource, channels):
inst = channels.open_resource(
resource,
read_termination="\n",
write_termination="\r\n" if resource.startswith("ASRL") else "\n",
)
assert_instrument_response(inst, "CH 1:VOLT:IMM:AMPL?", "+1.00000000E+00")
inst.write("CH 1:VOLT:IMM:AMPL 2.0")
assert_instrument_response(inst, "CH 1:VOLT:IMM:AMPL?", "+2.00000000E+00")
assert_instrument_response(inst, "CH 2:VOLT:IMM:AMPL?", "+1.00000000E+00")
|
Java
|
UTF-8
| 3,339
| 2.5
| 2
|
[] |
no_license
|
package avishkar2k17.com.tpo;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
public class Helper {
public static ArrayList<String> getStreamConnection(String rurl,String data,String s)
{
ArrayList<String> arr=new ArrayList<>();
try {
URL url1 = new URL(rurl);
HttpURLConnection httpURLConnection1 = (HttpURLConnection) url1.openConnection();
httpURLConnection1.setRequestMethod("POST");
httpURLConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//httpURLConnection1.setRequestProperty("Host", "192.168.0.101");
httpURLConnection1.setDoOutput(true);
httpURLConnection1.setDoInput(true);
httpURLConnection1.connect();
OutputStream OS1 = httpURLConnection1.getOutputStream();
BufferedWriter bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(OS1, "UTF-8"));
bufferedWriter1.write(data);
bufferedWriter1.flush();
bufferedWriter1.close();
OS1.close();
InputStream IS1 = httpURLConnection1.getInputStream();
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(IS1, "iso-8859-1"));
String response1 = "";
String line1 = "";
while ((line1 = bufferedReader1.readLine()) != null) {
response1 += line1;
arr.add(line1);
}
Log.d("dkkk",response1);
bufferedReader1.close();
IS1.close();
httpURLConnection1.disconnect();
return arr;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
arr.add(s);
return arr;
}
public static ArrayList<String> getInputStreamConnection(String rurl,String s)
{
ArrayList<String> arr=new ArrayList<>();
try {
URL url = new URL(rurl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
arr.add(line);
}
bufferedReader.close();
IS.close();
httpURLConnection.disconnect();
return arr;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
arr.add(s);
return arr;
}
}
|
C
|
UTF-8
| 1,976
| 3.515625
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include "deque.h"
p_deque criar_deque() {
p_deque deque = malloc(sizeof(Deque));
deque->ini = NULL;
deque->fim = NULL;
return deque;
}
void destruir_lista_rec(p_no lista) {
if (lista == NULL) return;
destruir_lista_rec(lista->prox);
free(lista);
}
void destruir_deque(p_deque deque) {
destruir_lista_rec(deque->ini);
free(deque);
}
void imprime_lista_rec(p_no lista) {
if (lista == NULL) return;
printf("Valor: %d\n", lista->dado);
imprime_lista_rec(lista->prox);
}
void imprimir_deque(p_deque deque) {
imprime_lista_rec(deque->ini);
}
p_deque insere_inicio(p_deque deque, int x) {
p_no novo = malloc(sizeof(No));
novo->dado = x;
novo->ant = NULL;
if(deque->ini == NULL) {
novo->prox = NULL;
deque->fim = novo;
deque->ini = novo;
} else {
p_no anterior = deque->ini;
anterior->ant = novo;
novo->prox = anterior;
deque->ini = novo;
}
return deque;
}
p_deque insere_fim(p_deque deque, int x) {
p_no novo = malloc(sizeof(No));
novo->dado = x;
novo->prox = NULL;
if(deque->fim == NULL) {
novo->ant = NULL;
deque->ini = novo;
deque->fim = novo;
} else {
p_no fim_anterior = deque->fim;
fim_anterior->prox = novo;
novo->ant = fim_anterior;
deque->fim = novo;
}
return deque;
}
int remove_inicio(p_deque deque) {
p_no remover = deque->ini;
int x = remover->dado;
deque->ini = remover->prox;
if(deque->ini == NULL) {
deque->fim = NULL;
} else {
deque->ini->ant = NULL;
}
free(remover);
return x;
}
int remove_fim(p_deque deque) {
p_no remover = deque->fim;
int x = remover->dado;
deque->fim = remover->ant;
if(deque->fim == NULL) {
deque->ini = NULL;
} else {
deque->fim->prox = NULL;
}
free(remover);
return x;
}
|
Python
|
UTF-8
| 198
| 2.6875
| 3
|
[] |
no_license
|
#coding=utf-8
'''
Created on 2015年3月19日
@author: asus
'''
import re
#u不能掉
f=u"我"
b=re.findall(ur"[\u4e00-\u9fa5]+",f)
if b==[]:
print "不是中文"
else:
print "是中文"
|
Markdown
|
UTF-8
| 714
| 2.859375
| 3
|
[] |
no_license
|
### 支持中文,文字转图片,支持自动断行,加阴影
#### 使用说明
```
composer require turbo-text2image
```
```php
use Turbo\text2Image\text2Image;
// 指定容器宽高
$width = 800;
$height = 600;
// 当不指定宽时,将不自动断行
// 当指定高时,文字超出部分将不会显示
$image = new text2Image($width, $height);
$text = <<<MSG_EOF
<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension)
// = SomeFont;
?>
MSG_EOF;
$image->setFontSize(30)->setColor("red")->setShadow([
'x'=> 2,
'y'=> 2,
'color' => "#0ff|0.8"
])->generate($text)
->save('1.png');
```
|
C#
|
UTF-8
| 1,420
| 2.765625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TarefaWeb.Models;
namespace TarefaWeb.Controllers
{
public class TarefasController : ApiController
{
public List<Tarefa> Get()
{
using(TarefaModel model = new TarefaModel())
{
return model.Read();
}
}
public HttpResponseMessage Post([FromBody]Tarefa t)
{
if (ModelState.IsValid)
{
using (TarefaModel model = new TarefaModel())
{
t.Data = DateTime.Now;
model.Create(t);
return Request.CreateResponse(HttpStatusCode.OK, "Cadastrado com sucesso");
}
}
else
{
return Request.CreateResponse(HttpStatusCode.PreconditionFailed, ModelState.Values);
}
}
public Tarefa Get(int id)
{
using(TarefaModel model = new TarefaModel())
{
return model.Read(id);
}
}
[HttpGet]
[Route("api/tarefas/obtem/{id}")]
public Tarefa Obtem(int id)
{
using (TarefaModel model = new TarefaModel())
{
return model.Read(id);
}
}
}
}
|
Python
|
UTF-8
| 624
| 3.515625
| 4
|
[] |
no_license
|
#Recursion Set
# search
def search(array, query):
if array == []:
return False
if array [0] == query:
return True
return search(array[1:], query)
# is_palindrome
def is_palindrome(str):
if len(str) <=1:
return True
if str [0] != str[-1]:
return False
return is_palindrome(str[1:-1])
# digit_match
def digit_match(num1, num2):
if num1 == 0 and num2 == 0:
return 1
count = 0
if num1 % 10 == num2 % 10:
count += 1
if num1//10 == 0 or num2 //10 == 0:
return count
return count + digit_match(num1//10, num2//10)
|
Java
|
UTF-8
| 3,442
| 2.265625
| 2
|
[] |
no_license
|
package com.example.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.*;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;
@Slf4j
@Configuration
@EnableWebSocketMessageBroker //開啟使用STOMP協議來傳輸基於代理的消息
// WebSocketMessageBrokerConfigurer or AbstractWebSocketMessageBrokerConfigurer
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//允許客戶端使用socketJs方式訪問,訪問點為ws,允許跨域
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
// registry.addEndpoint("/endpointSang").withSockJS();
// registry.addEndpoint("/endpointChat").withSockJS();
// registry.addEndpoint("/socket").withSockJS()
// .setInterceptors( new ChatHandlerShareInterceptor())
// .setStreamBytesLimit(512 * 1024)
// .setHttpMessageCacheSize(1000)
// .setDisconnectDelay(30 * 1000);
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//訂閱廣播 Broker(消息代理)名稱
registry.enableSimpleBroker("/queue");
// registry.enableSimpleBroker("/topic"); // Enables a simple in-memory broker
//全局使用的訂閱前綴(客戶端訂閱路徑上會體現出來)
registry.setApplicationDestinationPrefixes("/app/");
//點對點使用的訂閱前綴(客戶端訂閱路徑上會體現出來),不設置的話,默認也是/user/
registry.setUserDestinationPrefix("/user/");
}
@Override
public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
@Override
public WebSocketHandler decorate(final WebSocketHandler handler) {
return new WebSocketHandlerDecorator(handler) {
@Override
public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
// 客户端与服务器端建立连接后,此处记录谁上线了
String username = session.getPrincipal().getName();
log.info("online: " + username);
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
// 客户端与服务器端断开连接后,此处记录谁下线了
String username = session.getPrincipal().getName();
log.info("offline: " + username);
super.afterConnectionClosed(session, closeStatus);
}
};
}
});
}
}
|
Java
|
UTF-8
| 3,178
| 3.15625
| 3
|
[] |
no_license
|
package util;
import config.Constants;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
private FileUtils() {
}
/**
* Returns the desktop directory path of the current user
*
* @return Desktop Directory Path
*/
public static String getDesktopDirectory() {
return System.getProperty("user.home") + "/Desktop";
}
/**
* Returns the drive directory
*
* @return Drive directory
*/
public static String getDriveDirectory() {
return getDesktopDirectory() + "/" + Constants.SYNC_FOLDER_NAME;
}
/**
* Returns a list of files in the given path
*
* @param path Folder path
* @return list of files
*/
public static File[] getFileList(String path) {
File dir = new File(path);
return dir.listFiles();
}
/**
* Creates a new folder with the given file path
*
* @param path Directory Path
*/
public static void createFolder(String path) {
File dir = new File(path);
if (!dir.exists())
dir.mkdir();
}
/**
* Returns the file with the given checksum in the given file list
*
* @param checksum File to be found
* @param list List of files that will be searched
* @return File with the given checksum
*/
public static File getFileWithChecksum(String checksum, File[] list) {
for (File file : list)
if (MD5checksum(file).equals(checksum))
return file;
return null;
}
/**
* Returns a list of checksum of the given files
*
* @param list File list
* @return List of checksum
*/
public static List<String> getChecksumList(File[] list) {
List<String> result = new ArrayList<>();
for (File file : list) {
result.add(MD5checksum(file));
}
return result;
}
/**
* Returns the MD5 checksum value of the given file
*
* @param input File
* @return MD5 checksum value
*/
public static String MD5checksum(File input) {
try (InputStream inputStream = new FileInputStream(input)) {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] block = new byte[Constants.BUFFER_SIZE];
int length;
while ((length = inputStream.read(block)) > 0) {
digest.update(block, 0, length);
}
return StringUtils.byteArrayToString(digest.digest());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returns the drive folder. If the DEBUG_MODE is TRUE, then it returns a folder with "-debug" suffix. Otherwise returns the original drive folder
*
* @return Drive folder
*/
public static String getDebugDriveDirectory() {
if (Constants.DEBUG_MODE)
return getDesktopDirectory() + "/" + Constants.SYNC_FOLDER_NAME + "-debug";
return getDriveDirectory();
}
}
|
Java
|
UTF-8
| 366
| 2.078125
| 2
|
[] |
no_license
|
package xlxacidxlx.datmod.item;
import xlxacidxlx.datmod.base.Item;
import xlxacidxlx.datmod.creativetab.CreativeTabs;
/**
* Created by Acid on 10/26/2016.
*/
public class EmeraldiDust extends Item {
/**
* Constructs the Emeraldi Dust
*/
public EmeraldiDust() {
super("Emeraldi Dust");
setCreativeTab(CreativeTabs.dusts);
setImplemented(true);
}
}
|
Java
|
UTF-8
| 2,832
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.theah64.pigeon.utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by theapache64 on 14/9/16,6:07 PM.
*/
public class FCMUtils {
private static final String FCM_SEND_URL = "https://fcm.googleapis.com/fcm/send";
public static final String KEY_TYPE = "type";
public static final String TYPE_LOCATION_REQUEST = "location_request";
public static final String KEY_DATA = "data";
public static final String KEY_TO = "to";
private static final String FCM_NOTIFICATION_KEY = "AAAAPhR8lrk:APA91bFQjEEOrSQUg2y5fPOD0Xe_mv4bb6MsgYsZPu3nJhzHEsT-LA74GSDcpDOasDjH3Ms8EdkLb6oXbk0NIENRAEW6dkh3jgyZitScDYS8sAYIvaWOmhMh_xNGUEu9ix0zs1H05LSL";
private static final String KEY_REG_IDS = "registration_ids";
public static JSONObject sendLocationRequest(final JSONArray jaFcmIds) {
System.out.println(jaFcmIds);
final JSONObject joFcm = new JSONObject();
try {
joFcm.put(jaFcmIds.length() == 1 ? FCMUtils.KEY_TO : FCMUtils.KEY_REG_IDS, jaFcmIds.length() == 1 ? jaFcmIds.get(0) : jaFcmIds);
final JSONObject joData = new JSONObject();
joData.put(FCMUtils.KEY_TYPE, FCMUtils.TYPE_LOCATION_REQUEST);
joFcm.put(FCMUtils.KEY_DATA, joData);
} catch (JSONException e) {
e.printStackTrace();
}
return sendPayload(joFcm.toString());
}
private static JSONObject sendPayload(String payload) {
try {
System.out.println("To FCM: " + payload);
final URL url = new URL(FCM_SEND_URL);
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("Authorization", "key=" + FCM_NOTIFICATION_KEY);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
OutputStream os = urlConnection.getOutputStream();
os.write(payload.getBytes());
os.flush();
os.close();
final BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
final StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line).append("\n");
}
br.close();
System.out.println("FCM Says : " + response.toString());
return new JSONObject(response.toString());
} catch (java.io.IOException e) {
e.printStackTrace();
return null;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
|
Markdown
|
UTF-8
| 864
| 2.609375
| 3
|
[] |
no_license
|
# TaskGroups2.Add Method (Project)
Der **TaskGroups2** -Auflistung hinzugefügt ein **[Group2](a7a61fa4-e752-006e-a47e-03987b04f01c.md)** -Objekt.
## Syntax
_Ausdruck_. **Add**( ** _Name_**, ** _FieldName_** )
_Ausdruck_ Ein Ausdruck, der ein **TaskGroups2** -Objekt zurückgibt.
### Parameter
|**Name**|**Erforderlich/Optional**|**Datentyp**|**Beschreibung**|
|:-----|:-----|:-----|:-----|
| _Name_|Erforderlich|**String**|Der Name einer Gruppendefinition.|
| _FieldName_|Erforderlich|**String**|Der Name des ersten Felds, nach dem gruppiert werden soll.|
### Rückgabewert
**Group2**
## Siehe auch
#### Konzepte
[TaskGroups2-Auflistung (Objekt)](08346fd5-3dbd-23ea-9dc8-c2361ce043f4.md)
#### Weitere Ressourcen
[Elemente des TaskGroups2-Objekts](http://msdn.microsoft.com/library/01d23ee9-94e8-0b08-bddf-c7f24fbd3a00%28Office.15%29.aspx)
|
C++
|
UTF-8
| 928
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int minOperations(vector<int>& nums, int x) {
int N = nums.size();
int l = 0;
int s = 0;
int ans = -1;
for (; l<N and s<x; l++) {
s += nums[l];
}
if (s == x) ans = l;
l--;
int r = N - 1;
for (; l>=0; l--) {
s -= nums[l];
while (r > l and s < x) {
s += nums[r];
r--;
}
if (s == x) {
if (ans == -1) ans = (l + N - r - 1);
else ans = min(ans, (l + N - r - 1));
}
}
return ans;
}
};
int main()
{
Solution S;
std::vector<int> t;
t.push_back(3);
t.push_back(2);
t.push_back(20);
t.push_back(1);
t.push_back(1);
t.push_back(3);
int x=10;
cout << S.minOperations(t,x);
return 0;
}
|
Java
|
UTF-8
| 5,485
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package com.qxcmp.spider;
import com.qxcmp.core.init.QxcmpInitializer;
import com.qxcmp.spider.event.AdminSpiderFinishEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* 蜘蛛执行器
* <p>
* 负责在平台启动的时候加载所有蜘蛛配置,然后根据加载的蜘蛛配置启动蜘蛛组,并且在蜘蛛结束时记录到蜘蛛日志中
*
* @author aaric
*/
@Order(Ordered.LOWEST_PRECEDENCE - 2)
@Slf4j
@Component
@RequiredArgsConstructor
public class SpiderRunner implements QxcmpInitializer {
private final ApplicationContext applicationContext;
private final TaskExecutor taskExecutor;
private final SpiderContextHolder spiderContextHolder;
private final SpiderLogService spiderLogService;
/**
* 启动蜘蛛运行器
* <p>
* 从{@link SpiderContextHolder}中加载注册的蜘蛛配置信息根据分组数量对每个组启动一个任务来执行该组中所有的蜘蛛
*/
void start() {
spiderContextHolder.getSpiderDefinitions().keySet().forEach(group -> taskExecutor.execute(() -> startGroup(group)));
}
/**
* 循环执行一个蜘蛛组任务
* <p>
* 会从{@link SpiderContextHolder} 中注册的蜘蛛元数据动态状态一个蜘蛛组队列,依次执行该蜘蛛组中的每一个蜘蛛
* <p>
* 当蜘蛛组中所有任务执行完成以后,重新执行该组的所有蜘蛛,如果在这期间蜘蛛的顺序发生变化,需要等到下一轮任务启动
*
* @param group 要启动的蜘蛛组的名称
*/
private void startGroup(String group) {
/*
* 执行一个组的任务
* */
FutureTask<String> groupTask = new FutureTask<>(() -> {
List<SpiderDefinition> spiderDefinitionList = spiderContextHolder.getSpiderDefinitions().get(group).stream().filter(spiderDefinition -> !spiderDefinition.isDisabled()).sorted(Comparator.comparing(SpiderDefinition::getOrder)).collect(Collectors.toList());
if (spiderDefinitionList.isEmpty()) {
try {
TimeUnit.MINUTES.sleep(1);
} catch (Exception ignored) {
}
} else {
spiderDefinitionList.forEach(this::startSpider);
}
return group;
});
taskExecutor.execute(groupTask);
try {
/*
* 当一个组的任务执行完以后,重新执行该组的任务
* */
String groupName = groupTask.get();
startGroup(groupName);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
/**
* 根据蜘蛛元数据启动同步一个蜘蛛任务
*
* @param spiderDefinition 蜘蛛元数据
*/
@SuppressWarnings("unchecked")
private void startSpider(SpiderDefinition spiderDefinition) {
if (spiderDefinition.isDisabled()) {
return;
}
try {
SpiderPageProcessor spiderPageProcessor = applicationContext.getBean(spiderDefinition.getPageProcess());
us.codecraft.webmagic.Spider spider = us.codecraft.webmagic.Spider.create(spiderPageProcessor).thread(spiderDefinition.getThread());
spiderDefinition.getStartUrls().forEach(spider::addUrl);
spiderDefinition.getPipelines().forEach(aClass -> {
SpiderPipeline spiderPipeline = applicationContext.getBean(aClass);
spider.addPipeline(spiderPipeline);
spiderPageProcessor.getSpiderPipelines().add(spiderPipeline);
});
log.info("Start spider: [{}]:[{}]", spiderDefinition.getGroup(), spiderDefinition.getName());
SpiderRuntime spiderRuntime = new SpiderRuntime(spiderDefinition.getGroup(), spiderDefinition.getName(), spider, spiderPageProcessor);
spiderContextHolder.getSpiderRuntimeInfo().add(spiderRuntime);
spider.run();
spiderContextHolder.getSpiderRuntimeInfo().remove(spiderRuntime);
spiderLogService.save(spiderPageProcessor);
applicationContext.publishEvent(new AdminSpiderFinishEvent(spiderDefinition, spiderPageProcessor));
} catch (NoSuchBeanDefinitionException e) {
log.error("Start spider failed, cause: {}", e.getMessage());
}
}
private void loadSpiderDefinition() {
applicationContext.getBeansOfType(SpiderPageProcessor.class).forEach((s, spiderPageProcessor) -> {
try {
spiderContextHolder.register(spiderPageProcessor);
} catch (Exception e) {
log.error("Can't register spider definition for {}, cause: {}", spiderPageProcessor.getClass().getName(), e.getMessage());
}
});
}
@Override
public void init() {
loadSpiderDefinition();
start();
}
}
|
Java
|
UTF-8
| 3,339
| 2.640625
| 3
|
[] |
no_license
|
package br.com.hotel;
import java.util.ArrayList;
import java.util.Date;
import br.com.clientes.Conta;
import br.com.clientes.Hospede;
/**
*
* @author Igor Silva & Savio Silva
*
*/
public class Reserva { //antiga class Hospedagem
private int codigo;
private Date dataEntrada;
private Date dataSaida;
private ArrayList<Hospede> hospedes;
private Hospede responsavel;
private Aposento aposento;
private Conta conta;
private int quantidadeHospedes;
//Checar pra saber se ja existe o codigo, se existir retorna false
/**
*
* @param codigo
* @param reservas
* @return
*/
public static boolean checagemDeCodigo(int codigo, ArrayList <Reserva> reservas) {
for(int i = 0; i < reservas.size(); i++) {
if(codigo == reservas.get(i).getCodigo()) {
return false;
}
}
return true;
}
//Checar se o codigo pertence a algum hospede
/**
*
* @param codigo
* @param reservas
* @return
*/
public static boolean checarExistencia(int codigo, ArrayList <Reserva> reservas) {
for(int i = 0; i < reservas.size(); i++) {
//for(int j=0; j < reservas.get(i).getQuantidadeHospedes(); j++) {
if(codigo == reservas.get(i).getHospedes().get(i).getCodigo()) {
//if(reservas.get(i).getHospedes().get(i).isResponsavel()) {
return true;
//}
//getResponsavel().getCodigo()) {
}
//}
}
return false;
}
/**
*
* @param codigo
* @param dataEntrada
* @param dataSaida
* @param hospedes
* @param aposento
* @param conta
* @param quantidadeHospedes
*/
public Reserva(int codigo, Date dataEntrada, Date dataSaida, ArrayList<Hospede> hospedes, Aposento aposento, Conta conta, int quantidadeHospedes) {
this.codigo = codigo;
this.dataEntrada = dataEntrada;
this.dataSaida = dataSaida;
this.hospedes = hospedes;
this.aposento = aposento;
this.conta = conta;
this.quantidadeHospedes = quantidadeHospedes;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public Date getDataEntrada() {
return dataEntrada;
}
public void setDataEntrada(Date dataEntrada) {
this.dataEntrada = dataEntrada;
}
public Date getDataSaida() {
return dataSaida;
}
public void setDataSaida(Date dataSaida) {
this.dataSaida = dataSaida;
}
public ArrayList<Hospede> getHospedes() {
return hospedes;
}
public void setHospedes(ArrayList<Hospede> hospedes) {
this.hospedes = hospedes;
}
public void setHospede(Hospede hospede) {
this.hospedes.add(hospede);
}
public Aposento getAposento() {
return aposento;
}
public void setAposento(Aposento aposento) {
this.aposento = aposento;
}
public Conta getConta() {
return conta;
}
public void setConta(Conta conta) {
this.conta = conta;
}
public Hospede getResponsavel(ArrayList<Hospede> hospedes) {
for(int i=0; i < hospedes.size(); i++) {
if(hospedes.get(i).isResponsavel() == true) {
setResponsavel(hospedes.get(i));
}
}
return responsavel;
}
public Hospede getResponsavel() {
return responsavel;
}
public void setResponsavel(Hospede responsavel) {
this.responsavel = responsavel;
}
public int getQuantidadeHospedes() {
return hospedes.size();
}
}
|
Java
|
UTF-8
| 365
| 2.546875
| 3
|
[] |
no_license
|
package code.gui;
public final class TopLeftFrame {
private int width;
private int height;
public int getWidth() {
return width;
}
public void setWidth(int _width) {
width = _width;
}
public int getHeight() {
return height;
}
public void setHeight(int _height) {
height = _height;
}
}
|
Markdown
|
UTF-8
| 3,191
| 3.15625
| 3
|
[] |
no_license
|
### 外媒:人们主要认知问题是过度自信 而非缺乏自信`龘龘龘`
http://www.chinanews.com/gj/2014/05-19/6185085.shtml
- 女性往往太缺乏自信。
>作者认为几乎从来都看不到任何由自信心不足造成的问题,但是每天都会看到过度自信造成的问题,自己也会制造这种问题。
>>很多最近的心理学研究也显示,人们主要的认知问题是过度自信而非缺乏自信。
>>>数不胜数的实验,显示出人们会多么频繁地做出自信但错误的结论。
- 研究表明,人们惯于过度表扬自己的优点、为自己的缺点开脱,于是人们就可以过高地评价自己。
多数人都自以为诚实,但实际上,如果时机合适,多数人常会在小问题上作弊。
- 人们应该如何向更广泛的文化注入自省和自我怀疑。怎样让每个人在“女性的”自我怀疑和“男性的”自负之间,取得更好的平衡?
>当一个人试图产生自信的感觉时,其实是在窥视许许多多变幻莫测的精神系统,其中多数都处在无法觉察的层次。
>>你并没有得到真家伙,那才可以被可靠地称作自信,你其实只是在臆想出一种抽象的东西。
>>>尝试思考“自信”的这个举动本身,就会让虚荣心构建出这样一种不稳定的、飘渺的自我,而这种自我也因此显得脆弱得让人痛心、防御性极强、喜欢夸大,对轻慢又十分敏感。
---
>如果一个人想谈论实实在在的东西,那么用“自信”这个可疑的概念或许就是个错误,毕竟它指向自我。
>>考虑“技能”或许是个更好的想法,它指向的是任务。如果你问自己,“我能胜任吗?”你至少是在根据一个具体领域的标准衡量自己。
---
>持自信心态的人,仿佛是宴会上一个局促不安的人,他会在内心里痛苦地追问,“大家对我印象怎么样?”而持工具心态的人,则是在从事一项技艺,他会问自己,“这个具体的工作需要什么?
>>持自信心态的人,被人教导要“相信自己”,可这会激发起各种历史的偏见和社会的成见。而持工具心态的人,则被人教导,要“准确地看待你做过的事
---
>人生中有一件艰难的事情是,学会问那些你实际上能回答的问题。
>>例如,如果你在考虑从事某个工作,问“这个工作未来能带来什么机遇”可能就很傻,毕竟你并不知道答案。更好的问题或许是:“到这个地方工作能不能每天都得到回报?”这才是一个更实际的问题。
>>>如果你要结婚,问一个答案无法确知的问题可能会比较蠢,比如“这个人能让我幸福50年吗?”更聪明的问法可能是,“这个人让我倾慕的程度,足以让我把自己交给他,与他度过一生吗?”你至少当下就能大略地看到某个人的习性。
---
- 如果一个人开始考虑“自信心”,就只是在编造自我评价的故事。在生活中关注于哪些具体的事情需要做,或许会更加容易。后者来源于一系列外部的责任和标准,因而可以让自己沉静下来。
|
Python
|
UTF-8
| 6,062
| 2.578125
| 3
|
[] |
no_license
|
from zplot import *
def guess_interval(x):
import math
div = int(10**(int(math.log10(x))-1))
return max(2, int(x)/5/div*div)
def ceil_and_interval(x):
interval = guess_interval(x)
return int(math.ceil(x/interval)*interval), interval
def producer():
t = table('plot2.data', separator=',')
# acks batch_size flush_messages flush_ms latency linger num_producers num_records partition record_size replica throughput
c = canvas(title='producer_partitions', canvas_type='pdf')
ymax = t.getmax('throughput')
ymax, yinterval = ceil_and_interval(ymax*1.2)
d = drawable(c, xrange=[-0.5,4.5], yrange=[0,ymax])
axis(d, xtitle='Partitions', xmanual=[[1, 0],[6, 1],[12, 2],[18, 3], [24, 4]],
ytitle='Throughput (MB/s)', yauto=[0,ymax,yinterval],
xlabelfontsize=7, ylabelfontsize=7, xtitlesize=7, ytitlesize=7,
title='Producer Throughput at Different Replication Factors',
titlesize=7)
l = legend()
r1 = table(table=t, where='replica = 1')
p = plotter()
p.verticalbars(drawable=d, table=r1, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='blue', barwidth=0.8,
labelfield='latency_95', cluster=[0,3],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Replicas 1')
r3a = table(table=t, where='replica = 3 and acks = 1')
p = plotter()
p.verticalbars(drawable=d, table=r3a, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='red', barwidth=0.8,
labelfield='latency_95', cluster=[1,3],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Async Replicas 3')
r3 = table(table=t, where='replica = 3 and acks = -1')
p = plotter()
p.verticalbars(drawable=d, table=r3, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='green', barwidth=0.8,
labelfield='latency_95', cluster=[2,3],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Replicas 3')
l.draw(canvas=c, coord=d.map([-.4,2300]), fontsize=5, width=3, height=3)
c.text(anchor='l', coord=[d.left(),d.bottom()-30], text='*number in parentheses are latency in ms', size=4)
c.render()
t = table('plot1.data', separator=',')
c = canvas(title='producer_record_and_batch_size', canvas_type='pdf')
ymax = t.getmax('throughput')
ymax, yinterval = ceil_and_interval(ymax*1.5)
d = drawable(c, xrange=[-0.5,2.5], yrange=[0,ymax])
axis(d, xtitle='Record Size (byte)', xmanual=[[128, 0],[256, 1],[512, 2]],
ytitle='Throughput (MB/s)', yauto=[0,ymax,yinterval],
ylabelfontsize=7, xlabelfontsize=7, xtitlesize=7, ytitlesize=7,
title='Producer Throughput')
l = legend()
bs1 = table(table=t, where='batch_size = 4096')
p = plotter()
p.verticalbars(drawable=d, table=bs1, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='blue', barwidth=0.8,
labelfield='latency_95', cluster=[0,4],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Batch Size 4k')
bs2 = table(table=t, where='batch_size = 16384')
p = plotter()
p.verticalbars(drawable=d, table=bs2, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='red', barwidth=0.8,
labelfield='latency_95', cluster=[1,4],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Batch Size 16kB')
bs3 = table(table=t, where='batch_size = 65536')
p = plotter()
p.verticalbars(drawable=d, table=bs3, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='green', barwidth=0.8,
labelfield='latency_95', cluster=[2,4],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Batch Size 64kB')
bs4 = table(table=t, where='batch_size = 131072')
p = plotter()
p.verticalbars(drawable=d, table=bs4, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='yellow', barwidth=0.8,
labelfield='latency_95', cluster=[3,4],
labelsize=4, labelformat='(%s)', labelrotate=90, labelanchor='l,l',
legend=l, legendtext='Batch Size 128kB')
l.draw(canvas=c, coord=d.map([-0.40,660]), fontsize=4, width=3, height=2)
c.text(anchor='l', coord=[d.left(),d.bottom()-30], text='*number in parentheses are latency in ms', size=4)
c.render()
def consumer():
t = table('plot3.data', separator=',')
c = canvas(title='consumer_partitions', canvas_type='pdf')
ymax = t.getmax('throughput')
ymax, yinterval = ceil_and_interval(ymax)
d = drawable(c, xrange=[-0.5,4.5], yrange=[0,ymax])
axis(d, xtitle='Partitions', xmanual=[[1, 0],[6, 1],[12, 2],[18, 3], [24, 4]],
ytitle='Throughput (MB/s)', yauto=[0,ymax,yinterval],
xlabelfontsize=7, ylabelfontsize=7, xtitlesize=7, ytitlesize=7,
title='Consumer Throughput')
l = legend()
r1 = table(table=t, where='replica = 1')
p = plotter()
p.verticalbars(drawable=d, table=r1, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='blue', barwidth=0.8,
cluster=[0,2],
legend=l, legendtext='Replicas 1')
r3 = table(table=t, where='replica = 3')
p = plotter()
p.verticalbars(drawable=d, table=r3, xfield='rownumber', yfield='throughput',
fill=True, fillcolor='red', barwidth=0.8,
cluster=[1,2],
legend=l, legendtext='Replicas 3')
l.draw(canvas=c, coord=d.map([-.4,1000]), fontsize=5, width=3, height=3)
c.text(anchor='l', coord=[d.left(),d.bottom()-30], text='*number in parentheses are latency in ms', size=4)
c.render()
if __name__ == '__main__':
producer()
consumer()
|
Python
|
UTF-8
| 1,635
| 3
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
from time import sleep
import requests
from dev.models import *
# run migration (adding, removing or changing your DB)
try:
db.execute_sql("ALTER TABLE schools ADD COLUMN latitude DECIMAL(9, 6)")
db.execute_sql("ALTER TABLE schools ADD COLUMN longitude DECIMAL(9, 6)")
except:
print("already added columns, skipping that part")
#schools = School.select()
#for school in schools:
# print (school.full_address())
# get all schools that haven't been geo coded yet
# by selecting where latitude is NULL
schools = School.select().where(School.latitude >> None)
for school in schools:
# wait a few seconds between each to not be banned and be polite
sleep(1)
try:
# form URL with address in it
# "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=91-30 METROPOLITAN AVENUE, QUEENS, NY"
url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address={}".format(school.full_address())
# request URL
response = requests.get(url)
# examine JSON, e.g {u'lat': 40.7135296, u'lng': -73.9856844}
# print(response.json())
coords = response.json()['results'][0]['geometry']['location']
# assign lat, lang to school object
school.latitude = coords['lat']
school.longitude = coords['lng']
# save to DB
school.save()
print("{} is at {}, {}".format(school.school_name, school.latitude, school.longitude))
except:
print(">> failed geocoding for {}".format(school.school_name))
|
Swift
|
UTF-8
| 2,449
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
// https://leetcode.com/problems/path-sum-ii
class Solution {
func pathSum(_ root: TreeNode?, _ targetSum: Int) -> [[Int]] {
return findPath(root, targetSum, [Int](), [[Int]]())
}
private func findPath(_ root: TreeNode?, _ sum: Int, _ path: [Int], _ paths: [[Int]]) -> [[Int]] {
guard let root = root else { return paths }
var cpath = path
cpath.append(root.val)
if root.left == nil && root.right == nil && root.val == sum {
var cPaths = paths
cPaths.append(cpath)
return cPaths
}
let val = sum - root.val
let left = findPath(root.left, val, cpath, paths)
let right = findPath(root.right, val, cpath, paths)
return left + right
}
}
// MARK: - Test Cases
import XCTest
// Executed 3 tests, with 0 failures (0 unexpected) in 0.339 (0.341) seconds
class Tests: XCTestCase {
private let s = Solution()
func test1() {
XCTAssertEqual(s.pathSum(.init([5,4,8,11,nil,13,4,7,2,nil,nil,5,1]), 22), [[5,4,11,2],[5,8,4,5]])
}
func test2() {
XCTAssertEqual(s.pathSum(.init([1,2,3]), 5), [])
}
func test3() {
XCTAssertEqual(s.pathSum(.init([1,2]), 0), [])
}
}
Tests.defaultTestSuite.run()
// MARK: - TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
// Making an additional initializer from an array of integers
public init?(_ array: [Int?]) {
var values = array
guard !values.isEmpty, let head = values.removeFirst() else { return nil }
val = head; left = nil; right = nil
var queue = [self]
while !queue.isEmpty {
let node = queue.removeFirst()
if !values.isEmpty, let val = values.removeFirst() {
node.left = TreeNode(val)
queue.append(node.left!)
}
if !values.isEmpty, let val = values.removeFirst() {
node.right = TreeNode(val)
queue.append(node.right!)
}
}
}
}
|
Java
|
UTF-8
| 6,358
| 2.390625
| 2
|
[] |
no_license
|
package com.trc202.CombatTagListeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
//import org.bukkit.event.entity.EntityDamageEvent;
//import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import com.topcat.npclib.NPCManager;
import com.topcat.npclib.entity.NPC;
import com.trc202.CombatTag.CombatTag;
import com.trc202.Containers.PlayerDataContainer;
public class NoPvpPlayerListener implements Listener{
private final CombatTag plugin;
public static int explosionDamage = -1;
public NPCManager npcm;
public NoPvpEntityListener entityListener;
public NoPvpPlayerListener(CombatTag instance) {
plugin = instance;
}
@EventHandler(ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent event){
Player loginPlayer = event.getPlayer();
onPlayerJoinNPCMode(loginPlayer);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent e){
Player quitPlr = e.getPlayer();
onPlayerQuitNPCMode(quitPlr);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerKick(PlayerKickEvent event){
Player player = event.getPlayer();
if (plugin.hasDataContainer(player.getName())) {
PlayerDataContainer kickDataContainer = plugin.getPlayerData(player.getName());
if (!kickDataContainer.hasPVPtagExpired()) {
if (plugin.settings.dropTagOnKick()) {
if (plugin.isDebugEnabled()) {plugin.log.info("[CombatTag] Player tag dropped for being kicked.");}
kickDataContainer.setPvPTimeout(0);
plugin.removeDataContainer(player.getName());
}
}
}
}
/*
private void onPlayerQuitTimedMode(Player quitPlr){
if(plugin.hasDataContainer(quitPlr.getName())){
PlayerDataContainer quitDataContainer = plugin.getPlayerData(quitPlr.getName());
if(!quitDataContainer.hasPVPtagExpired()){
if(plugin.isDebugEnabled()){plugin.log.info("[CombatTag] " + quitPlr.getName() + " has logged of during pvp!");}
if(plugin.settings.isInstaKill()){
quitPlr.damage(1000);
quitPlr.setHealth(0);
plugin.removeDataContainer(quitPlr.getName());
}else{
final NPC npc = plugin.spawnNpc(quitPlr.getName(),quitPlr.getLocation());
if(npc.getBukkitEntity() instanceof Player){
Player npcPlayer = (Player) npc.getBukkitEntity();
plugin.copyContentsNpc(npc, quitPlr);
String plrName = quitPlr.getName(); //tempfix
plugin.npcm.rename(plrName, plugin.getNpcName(plrName)); //tempfix
npcPlayer.setHealth(quitPlr.getHealth());
quitDataContainer.setSpawnedNPC(true);
quitDataContainer.setNPCId(quitPlr.getName());
quitDataContainer.setShouldBePunished(true);
quitPlr.getWorld().createExplosion(quitPlr.getLocation(), explosionDamage); //Create the smoke effect //
plugin.scheduleDelayedKill(npc, quitDataContainer);
}
}
}
}
}
*/
private void onPlayerQuitNPCMode(Player quitPlr){
if(plugin.hasDataContainer(quitPlr.getName())){
//Player is likely in pvp
PlayerDataContainer quitDataContainer = plugin.getPlayerData(quitPlr.getName());
if(!quitDataContainer.hasPVPtagExpired()){
//Player has logged out before the pvp battle is considered over by the plugin
if(plugin.isDebugEnabled()){plugin.log.info("[CombatTag] " + quitPlr.getName() + " has logged of during pvp!");}
if(plugin.settings.isInstaKill()){
quitPlr.damage(1000);
quitPlr.setHealth(0);
plugin.removeDataContainer(quitPlr.getName());
}else{
NPC npc = plugin.spawnNpc(quitPlr.getName(), quitPlr.getLocation());
if(npc.getBukkitEntity() instanceof Player){
Player npcPlayer = (Player) npc.getBukkitEntity();
plugin.copyContentsNpc(npc, quitPlr);
plugin.npcm.rename(quitPlr.getName(), plugin.getNpcName(quitPlr.getName()));
int healthSet = healthCheck(quitPlr.getHealth(), quitPlr.getName());
npcPlayer.setHealth(healthSet);
quitDataContainer.setSpawnedNPC(true);
quitDataContainer.setNPCId(quitPlr.getName());
quitDataContainer.setShouldBePunished(true);
quitPlr.getWorld().createExplosion(quitPlr.getLocation(), explosionDamage); //Create the smoke effect //
if(plugin.settings.getNpcDespawnTime() > 0){
plugin.scheduleDelayedKill(npc, quitDataContainer);
}
}
}
}
}
}
private void onPlayerJoinNPCMode(Player loginPlayer){
if(plugin.hasDataContainer(loginPlayer.getName())){
//Player has a data container and is likely to need some sort of punishment
PlayerDataContainer loginDataContainer = plugin.getPlayerData(loginPlayer.getName());
if(loginDataContainer.hasSpawnedNPC()){
//Player has pvplogged and has not been killed yet
//despawn the npc and transfer any effects over to the player
//if(plugin.isDebugEnabled()){plugin.log.info("[CombatTag] Player logged in and has npc");}
loginPlayer.setNoDamageTicks(0);
plugin.despawnNPC(loginDataContainer);
}
/*
if(loginDataContainer.shouldBePunished()){
loginPlayer.setExp(loginDataContainer.getExp());
loginPlayer.getInventory().setArmorContents(loginDataContainer.getPlayerArmor());
loginPlayer.getInventory().setContents(loginDataContainer.getPlayerInventory());
int healthSet = healthCheck(loginDataContainer.getHealth(), loginDataContainer.getPlayerName());
loginPlayer.setHealth(healthSet);
assert(loginPlayer.getHealth() == loginDataContainer.getHealth());
loginPlayer.setLastDamageCause(new EntityDamageEvent(loginPlayer, DamageCause.ENTITY_EXPLOSION, 0));
loginPlayer.setNoDamageTicks(1);
}
*/
plugin.removeDataContainer(loginPlayer.getName());
plugin.createPlayerData(loginPlayer.getName()).setPvPTimeout(plugin.getTagDuration());
}
}
private int healthCheck(int health, String plr) {
if(health < 0){
health = 0;
}
if(health > 20){
health = 20;
}
if(health == 0){
if(plugin.isDebugEnabled()){plugin.log.info("[CombatTag] " + plr +" has been set a health of 0.");}
}
return health;
}
}
|
Python
|
UTF-8
| 1,024
| 4.0625
| 4
|
[] |
no_license
|
#calculate number of elements in an array using recursive
def lenArr(lst):
if lst == []:
return 0
else:
return 1 + lenArr(lst[1:])
print (lenArr([1,3,4,2,4]))
#calculate sum of an array
def arrSum(lst):
if lst == []:
return 0
elif len(lst) == 1:
return lst[0]
else:
return lst[0] + arrSum(lst[1:])
print (arrSum([2,3,4,1,43,21,1]))
#find the largest num in a list
def maxList(lst):
if len(lst) == 1:
return lst[0]
elif len(lst) == 0:
return None
else:
return lst[0] if lst[0] > maxList(lst[1:]) else maxList(lst[1:])
print (maxList([43,2,34,56,31,22,23,19]))
#binary search using recursive
def find(lst, target, start = 0, end = None):
end = len(lst) if end is None else end
mid_index = (end - start)//2 + start
if lst[mid_index] < target:
find(lst, target, start = mid_index+1, end = end)
elif lst[mid_index] > target:
find(lst, target, start = start, end = mid_index-1)
else:
print('Found index: {}, value: {}'.format(mid_index, target))
print (find([2,3,5,10,16,18], 5))
|
TypeScript
|
UTF-8
| 2,007
| 2.796875
| 3
|
[
"CC0-1.0"
] |
permissive
|
import Loader from './Loader';
import StyleChange from '../Interfaces/StyleChange';
import KeyframeChange from '../Interfaces/KeyframeChange';
class LoaderFacebook extends Loader {
transform(size: string, color: string) {
const newSizeInt = parseInt(size, 10);
const keyFrame0top = newSizeInt * 0.1;
const keyFrame0height = newSizeInt - keyFrame0top * 2;
const keyFrame100height = keyFrame0height / 2;
const keyFrame100top = (newSizeInt - keyFrame100height) / 2;
const ruleChanges: StyleChange[] = [
{
selector: '.lds-facebook',
replacements: {
width: `${newSizeInt}px`,
height: `${newSizeInt}px`,
},
},
{
selector: '.lds-facebook div',
replacements: {
width: `${newSizeInt * 0.2}px`,
background: color,
},
},
{
selector: '.lds-facebook div:nth-child(1)',
replacements: {
left: `${newSizeInt * 0.1}px`,
},
},
{
selector: '.lds-facebook div:nth-child(2)',
replacements: {
left: `${newSizeInt * 0.4}px`,
},
},
{
selector: '.lds-facebook div:nth-child(3)',
replacements: {
left: `${(newSizeInt * 0.7).toFixed(1)}px`,
},
},
];
let replacedStyles = super.replaceStyles(ruleChanges);
const keyframesChanges: KeyframeChange[] = [
{
selector: 'lds-facebook',
replacements: {
'0%': {
top: `${keyFrame0top}px`,
height: `${keyFrame0height}px`,
},
'100%': {
top: `${keyFrame100top}px`,
height: `${keyFrame100height}px`,
},
},
},
];
replacedStyles = super.replaceKeyframeStyles(
keyframesChanges,
replacedStyles
);
return {
...this,
cssRules: replacedStyles,
};
}
clone() {
return new LoaderFacebook({ ...this });
}
}
export default LoaderFacebook;
|
Python
|
UTF-8
| 1,007
| 2.78125
| 3
|
[] |
no_license
|
'''
Created on Jan 17, 2014
@author: alessioferrari
'''
from ModelIndex import ModelIndex
from RequirementsModel import WORD_STRING, STEM_STRING, GOAL_STRING
class ModelIndexManager(object):
'''
This class stores a set of ModelIndexes and calls one index or the
other according to the type of query that is issued
'''
def __init__(self, requirementsModelLoader):
'''
Constructor
'''
self.wordIndex = ModelIndex(requirementsModelLoader, WORD_STRING)
self.stemIndex = ModelIndex(requirementsModelLoader, STEM_STRING)
self.goalIndex = ModelIndex(requirementsModelLoader, GOAL_STRING)
def searchModels(self, keyword, searchType = STEM_STRING):
if searchType == STEM_STRING:
return self.stemIndex.searchModels(keyword)
if searchType == WORD_STRING:
return self.wordIndex.searchModels(keyword)
if searchType == GOAL_STRING:
return self.goalIndex.searchModels(keyword)
|
Swift
|
UTF-8
| 357
| 2.625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
//
// JSONAdapter.swift
// TMDBCore
//
// Created by Guilherme Rambo on 20/06/16.
// Copyright © 2016 Guilherme Rambo. All rights reserved.
//
import Foundation
import SwiftyJSON
public protocol JSONAdaptable {
init?(json: JSON)
}
class JSONAdapter<M where M:JSONAdaptable> {
class func adapt(json: JSON) -> M? {
return M(json: json)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.