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,181 | 3.71875 | 4 |
[] |
no_license
|
package oop.codblock;
/** 代码块的使用
* @author hyc
* @date 2020/12/7
*
* 代码块有静态代码块和费静态代码块
*
* 静态代码块在类加载时自动执行,只会执行一次
* 非静态代码块在对象创建时自定执行,每次创建对象都会被执行一次.
* 不能显示调用代码块的执行.
*
*
* 非静态代码块可以用来初始化成员信息,关于初始化顺序:
* 代码块的初始化顺序和就地初始化的顺序取决于声明的顺序
*/
public class CodeBlockTest {
public static void main(String[] args) {
//观察执行顺序
CodeBlock codeBlock = new CodeBlock();
System.out.println(CodeBlock.className);
}
}
class CodeBlock{
/*
int id = 3;
{
id = 4;
}
* 在这种情况下,是先执行id = 3,后执行 id = 4
*/
{
id = 4;
}
int id = 3;
//在这种情况下是先执行id = 4,后执行id = 3
String name;
static String className = CodeBlock.class.getName();
{
System.out.println("非静态的代码块");
}
static {
System.out.println("static修饰的静态代码块");
}
}
|
C++
|
UTF-8
| 1,771 | 3 | 3 |
[] |
no_license
|
/*
* ++C - C++ introduction
* Copyright (C) 2013, 2014, 2015, 2016, 2017 Wilhelm Meier <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "demangler.h"
//[impl -impl2
namespace detail {
template<typename T>
struct unsigned_type_impl;
template<>
struct unsigned_type_impl<char> {
typedef unsigned char type;
};
//[impl2
template<>
struct unsigned_type_impl<int> {
typedef unsigned int type;
};
template<>
struct unsigned_type_impl<double> {
typedef double type;
};
//]
}
//]
//[alias
template<typename T>
using unsigned_type = typename detail::unsigned_type_impl<T>::type; //<> Die (öffentliche) Metafunktion ist nun dieses Alias-Template
//]
//[ abs
template<typename T>
unsigned_type<T> absolute(T value) { // <> Typ-Abbilung mit der Meta-Funktion `unsigned_type<>`
if (value < T{0}) {
return -value;
}
return value;
}
//]
int main() {
//[main
auto uv = absolute((char)-2); // <> Berechnung des Betrags
std::cout << PPC::demangle(uv) << std::endl; // <> Ausgabe der Typinformation als _un-mangled_ Name
//]
}
|
Java
|
UTF-8
| 402 | 1.835938 | 2 |
[] |
no_license
|
package top.duanyd.plantation.dao;
import top.duanyd.plantation.entity.SpeciesEntity;
public interface SpeciesDao {
int deleteByPrimaryKey(Long id);
int insert(SpeciesEntity record);
int insertSelective(SpeciesEntity record);
SpeciesEntity selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(SpeciesEntity record);
int updateByPrimaryKey(SpeciesEntity record);
}
|
Rust
|
UTF-8
| 7,455 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
use crate::misc::error::{AoCError, AoCResult};
use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::{BufRead, BufReader};
struct TicketData {
my_ticket: Vec<usize>,
nearby_tickets: Vec<Vec<usize>>,
parameters: HashMap<String, BTreeSet<usize>>,
}
impl TicketData {
fn parse_ticket_data(filename: String) -> AoCResult<TicketData> {
let file = File::open(filename)?;
let reader = BufReader::new(file);
let mut fields = HashMap::new();
let mut my_ticket: Vec<usize> = Vec::new();
let mut nearby_tickets: Vec<Vec<usize>> = Vec::new();
let mut is_fields = true;
let mut is_my_ticket = false;
let mut is_nearby_tickets = false;
for line in reader.lines() {
let line = line?;
if is_fields {
if line.eq("") {
is_fields = false;
is_my_ticket = true;
continue;
}
let mut split = line.split(':');
let name = AoCError::from_option(split.next())?;
let parameters = split.next().unwrap().split(" or ");
let mut values = BTreeSet::new();
for param in parameters {
let mut split_param = param.trim().split('-');
let start = split_param.next().unwrap().parse::<usize>().unwrap();
let end = split_param.next().unwrap().parse::<usize>().unwrap();
for x in start..(end + 1) {
values.insert(x);
}
}
fields.insert(name.to_string(), values);
} else if is_my_ticket && !line.contains(':') {
is_my_ticket = false;
is_nearby_tickets = true;
my_ticket = line
.split(',')
.map(|x| x.parse::<usize>().unwrap())
.collect();
} else if is_nearby_tickets && !line.contains(':') && !line.is_empty() {
is_my_ticket = false;
nearby_tickets.push(
line.split(',')
.map(|x| x.trim().parse::<usize>().unwrap())
.collect(),
);
}
}
Ok(TicketData {
my_ticket,
nearby_tickets,
parameters: fields,
})
}
fn nearby_tickets_to_string(&self) -> String {
let mut output = String::new();
for ticket in &self.nearby_tickets {
output.push_str(format!(" {:?}\n", ticket).as_str());
}
output
}
fn parameters_to_string(&self) -> String {
let mut output = String::new();
for (field, values) in &self.parameters {
output.push_str(format!(" {} : {:?}\n", field, values).as_str());
}
output
}
fn count_error_rate(&self) -> usize {
let mut valid_values = BTreeSet::new();
for value in self.parameters.values() {
valid_values.append(&mut (value.clone()));
}
let mut error_count = 0;
for ticket in &self.nearby_tickets {
for x in ticket {
if !valid_values.contains(x) {
error_count += x;
}
}
}
error_count
}
fn discard_invalid_tickets(&mut self) {
let mut valid_values = BTreeSet::new();
for value in self.parameters.values() {
valid_values.append(&mut (value.clone()));
}
self.nearby_tickets.retain(|ticket| {
let mut is_valid = true;
for x in ticket {
if !valid_values.contains(x) {
is_valid = false;
}
}
is_valid
});
}
fn find_field_positions(&self) -> HashMap<usize, &String> {
let mut possible_field_positions = HashMap::new();
for (field, values) in &self.parameters {
let mut possible_positions = Vec::new();
for index in 0..(&self.nearby_tickets.get(0)).unwrap().len() {
let mut valid = true;
for ticket in &self.nearby_tickets {
if let Some(x) = ticket.get(index) {
if !values.contains(x) {
valid = false;
}
} else {
valid = false;
}
}
if valid {
possible_positions.push(index);
}
}
possible_field_positions.insert(field, possible_positions);
}
let mut taken = HashMap::new();
let mut index = 0;
while !possible_field_positions.is_empty() {
/* println!(
"Pass: {}, Remaining Indexes: {}",
index,
possible_field_positions.len()
);*/
possible_field_positions.retain(|field, possible| {
if possible.len() == 1 {
let index = *possible.get(0).unwrap();
if taken.contains_key(&index) {
panic!("Two conflicting field positions!");
}
taken.insert(index, *field);
false
} else {
possible.retain(|x| !taken.contains_key(x));
true
}
});
index += 1;
if index >= 50 {
println!("Failed to assign values!");
break;
}
}
taken
}
}
impl Display for TicketData {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"My Ticket: {:?}\n\nNearby Tickets:\n{}\nParameters:\n{}",
self.my_ticket,
self.nearby_tickets_to_string(),
self.parameters_to_string()
)
}
}
fn part_1(file: String) -> usize {
let ticket_data = TicketData::parse_ticket_data(file).unwrap();
ticket_data.count_error_rate()
}
fn part_2(file: String) -> usize {
let mut ticket_data = TicketData::parse_ticket_data(file).unwrap();
ticket_data.discard_invalid_tickets();
let positions = ticket_data.find_field_positions();
let mut output = 1;
for (index, field) in &positions {
if field.contains("departure") {
output *= ticket_data.my_ticket.get(*index).unwrap();
}
}
output
}
pub(crate) fn run() {
let file = String::from("Inputs/input16.txt");
println!(" Part 1: {}", part_1(file.clone()));
println!(" Part 2: {}", part_2(file));
}
#[cfg(test)]
mod tests {
use crate::days::day16::{part_1, part_2};
#[test]
fn part_1_test() {
let file = String::from("Inputs/test16a.txt");
assert_eq!(part_1(file), 71);
}
#[test]
fn part_1_input() {
let file = String::from("Inputs/input16.txt");
assert_eq!(part_1(file), 29878);
}
#[test]
fn part_2_test() {
let file = String::from("Inputs/test16b.txt");
assert_eq!(part_2(file), 1);
}
#[test]
fn part_2_input() {
let file = String::from("Inputs/input16.txt");
assert_eq!(part_2(file), 855438643439);
}
}
|
Java
|
UHC
| 877 | 3 | 3 |
[] |
no_license
|
package swexpert;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution_1859_鸸Ʈ {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
for (int t = 1; t <= T; t++) {
int N = Integer.parseInt(br.readLine().trim());
int[] arr = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
long result = 0;
int temp = arr[N - 1];
for (int i = N - 2; i >= 0; i--) {
if(temp >= arr[i]) {
result += temp - arr[i];
} else {
temp = arr[i];
}
}
System.out.println("#" + t + " " + result);
}
}
}
|
Java
|
UTF-8
| 1,417 | 2.453125 | 2 |
[] |
no_license
|
package com.traversebd.calorie_hunter.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.traversebd.calorie_hunter.R;
import java.util.ArrayList;
public class NutritionDetailTipsAdapter extends RecyclerView.Adapter<NutritionDetailTipsAdapter.ViewHolder> {
private ArrayList<String> extraDetails;
public NutritionDetailTipsAdapter(ArrayList<String> extraDetails) {
this.extraDetails = extraDetails;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_recycler_nutrition_tips_detail_list,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.DetailsItem.setText(extraDetails.get(position));
}
@Override
public int getItemCount() {
return extraDetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView DetailsItem;
public ViewHolder(@NonNull View itemView) {
super(itemView);
DetailsItem = (TextView) itemView.findViewById(R.id.DetailsItem);
}
}
}
|
Java
|
UTF-8
| 2,555 | 2.6875 | 3 |
[] |
no_license
|
package com.example.articles.model.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.example.articles.model.dto.User;
public class DbManager extends SQLiteOpenHelper {
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String DB_NAME = "news";
private static final int DB_VERSION = 3;
private static final String CREATE_USERS_TABLE =
"CREATE TABLE " + DbContract.UsersEntry.TABLE_NAME + "(" +
DbContract.UsersEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
DbContract.UsersEntry.USERNAME + " TEXT, " +
DbContract.UsersEntry.PASSWORD + " TEXT )";
private static final String DROP_TABLE_USERS = "DROP TABLE IF EXISTS users";
private static final String SELECT_USER = "SELECT * FROM users";
private static DbManager instance;
private DbManager(@Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static DbManager getInstance(Context context) {
if (instance == null) {
instance = new DbManager(context);
}
return instance;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USERS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int newVersion, int oldVersion) {
db.execSQL(DROP_TABLE_USERS);
onCreate(db);
}
public void saveUser(User user) {
ContentValues content = new ContentValues();
content.put(USERNAME, user.getUsername());
content.put(PASSWORD, user.getPassword());
instance.getWritableDatabase().insert(DbContract.UsersEntry.TABLE_NAME, null, content);
}
public boolean existsUser(String username, String pass) {
Cursor cursor = instance.getReadableDatabase().rawQuery(SELECT_USER, null);
while (cursor.moveToNext()) {
String currentUsername = cursor.getString(cursor.getColumnIndex(USERNAME));
String currentPassword = cursor.getString(cursor.getColumnIndex(PASSWORD));
if (currentUsername.equals(username) && currentPassword.equals(pass)) {
cursor.close();
return true;
}
}
cursor.close();
return false;
}
}
|
Java
|
UTF-8
| 889 | 2.09375 | 2 |
[] |
no_license
|
package com.fitpolo.support.task;
import com.fitpolo.support.FitConstant;
import com.fitpolo.support.OrderEnum;
import com.fitpolo.support.callback.OrderCallback;
import com.fitpolo.support.entity.BaseResponse;
/**
* @Date 2017/5/11
* @Author wenzheng.liu
* @Description 设置手环震动
* @ClassPath com.fitpolo.support.task.ShakeBandTask
*/
public class ShakeBandTask extends OrderTask {
public ShakeBandTask(OrderCallback callback) {
setOrder(OrderEnum.setShakeBand);
setCallback(callback);
setResponse(new BaseResponse());
}
@Override
public byte[] assemble(Object... objects) {
byte[] byteArray = new byte[5];
byteArray[0] = (byte) FitConstant.HEADER_SET_SHAKE_BAND;
byteArray[1] = 0x02;
byteArray[2] = 0x02;
byteArray[3] = 0x0A;
byteArray[4] = 0x0A;
return byteArray;
}
}
|
Python
|
UTF-8
| 204 | 3.296875 | 3 |
[] |
no_license
|
def monotonic(lst):
for i in range(1,len(lst)):
if lst[i-1] >= lst[i]:
yield True
else:
yield False
lst = "6 5 4 4".split()
print(all(list(monotonic(lst))))
|
Java
|
UTF-8
| 122 | 1.632813 | 2 |
[] |
no_license
|
package com.practice.creational.patterns.abstract_factory;
public class AmexPlatinumCreditCard extends CreditCard {
}
|
Java
|
UTF-8
| 645 | 2.796875 | 3 |
[] |
no_license
|
package musicShop;
import Behaviours.ISell;
public class MusicAccessories implements ISell {
String name;
double costPrice;
double listPrice;
public MusicAccessories(String name, double costPrice, double listPrice){
this.name = name;
this.costPrice = costPrice;
this.listPrice = listPrice;
}
public String getName(){
return this.name;
}
public double getCostPrice(){
return this.costPrice;
}
public double getListPrice(){
return this.listPrice;
}
public double calculateMarkup() {
return this.listPrice - this.costPrice;
}
}
|
Java
|
UTF-8
| 303 | 2.640625 | 3 |
[] |
no_license
|
package com.zyd.strategy;
import com.zyd.Door;
import java.util.List;
public class ChangeChoiceStrategy implements ChooseStrategy {
@Override
public void chooseSecondTime(List<Door> doors) {
doors.stream().filter(d -> !d.isOpened()).forEach(d -> d.setChosen(!d.isChosen()));
}
}
|
Java
|
UTF-8
| 1,724 | 3.5625 | 4 |
[] |
no_license
|
package offer.chapter3;
import offer.structure.TreeNode;
/**
* Created by ryder on 2017/5/7.
*
*/
public class P117_SubstructureInTree {
//判断sub是否是root树的子结构
//很像是字符串模式匹配的暴力解法
//因此,针对于树结构,应该也有更优的匹配算法
public static boolean isSubtree(TreeNode root,TreeNode sub){
if(sub==null)
return true;
else if(root==null)
return false;
else{
boolean result = false;
if(root.val==sub.val)
result = isTree1HasTree2(root,sub);
if(!result)
result = isSubtree(root.left,sub);
if(!result)
result = isSubtree(root.right,sub);
return result;
}
}
public static boolean isTree1HasTree2(TreeNode tree1,TreeNode tree2){
if(tree2==null)
return true;
if(tree1==null)
return false;
if(tree1.val==tree2.val)
return isTree1HasTree2(tree1.left,tree2.left) && isTree1HasTree2(tree1.right,tree2.right);
else
return false;
}
public static void main(String[] args){
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(5);
root.right.right.right = new TreeNode(6);
TreeNode sub = new TreeNode(3);
sub.left = new TreeNode(4);
sub.right = new TreeNode(5);
System.out.println(isSubtree(null,sub));
System.out.println(isSubtree(root,null));
System.out.println(isSubtree(root,sub));
}
}
|
Java
|
UTF-8
| 426 | 1.90625 | 2 |
[] |
no_license
|
package enterprises.orbital.impl.evexmlapi.chr;
import java.util.HashSet;
import java.util.Set;
import enterprises.orbital.impl.evexmlapi.ApiResponse;
public class MailMessagesResponse extends ApiResponse {
private Set<ApiMailMessage> mails = new HashSet<ApiMailMessage>();
public void addApiMail(ApiMailMessage member) {
mails.add(member);
}
public Set<ApiMailMessage> getApiMails() {
return mails;
}
}
|
JavaScript
|
UTF-8
| 1,515 | 2.953125 | 3 |
[] |
no_license
|
'use strict';
const meow = require('meow');
const chalk = require('chalk');
const tlv = require('tlv');
const hexify = require('hexify');
const cli = meow(``, {
string: ['_']
});
const input = cli.input[0];
if (!input) {
console.error('TLV required');
process.exit(1);
}
const bytes = hexify.toByteArray(input);
const parsedTlv = tlv.parse(new Buffer(bytes));
function leftpad (str, len, ch) {
str = String(str);
var i = -1;
if (!ch && ch !== 0) ch = ' ';
len = len - str.length;
while (++i < len) {
str = ch + str;
}
return str;
}
function formatTag(tag) {
return chalk.red(tag.toString('16'));
}
function formatLength(length) {
return chalk.blue(leftpad(length, 2, '0'));
}
function formatValue(value) {
const ascii = chalk.green.bgWhite(value.toString());
const hex = chalk.magenta.bgWhite(value.toString('hex'));
return `${hex} ${ascii}`;
}
function format(tlv, index) {
index++;
const tabs = new Array(index).join(' ');
if (tlv.constructed) {
const tagOut = formatTag(tlv.tag);
const lengthOut = formatLength(tlv.originalLength);
const arr = tlv.value;
arr.map(function(child) {
format(child, index);
});
} else {
const tagOut = formatTag(tlv.tag);
const lengthOut = formatLength(tlv.originalLength);
var valueOut = formatValue(tlv.value);
console.log(`${tabs} ${tagOut} ${lengthOut} ${valueOut}`)
}
}
format(parsedTlv, 0);
|
PHP
|
UTF-8
| 3,642 | 2.71875 | 3 |
[] |
no_license
|
<?php
/*****************
GLOBALS
******************/
$level_admin = $_SESSION['MM_UserGroup']==1;
$level_user = $_SESSION['MM_UserGroup']==2;
$status_on = '<span class="label label-success">online</span>';
$status_off = '<span class="label label-danger">offline</span>';
$dateNow = date("Ymd-His");
$formDateNow = date("Y-m-d H:i:s");
/// Notifications
$save_success = '
<div class="col-sm-12">
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="fa fa-check-circle"></i> Gravação com sucesso!
</div>
</div>';
$save_error = '
<div class="col-sm-12">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="fa fa-exclamation-circle"></i> Gravação sem sucesso!
</div>
</div>';
$error_no_jpg = '
<div class="col-sm-12">
<div class="alert alert-warning alert-dismissable" style="top:140px">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="fa fa-exclamation-circle"></i> Seleccione uma imagem com a extenção em .jpg ou .jpeg e que seja abaixo de 5Mb!
</div>
</div>';
/// Path's
$path_imgs = "../assets/imgs/";
$path_imgs_portfolio = "../assets/imgs/portfolio/";
/*****************
FUNCTIONS
******************/
/*
* Resize Images
*/
/// Define image size
$img_XL = '1880';
$img_L = '1280';
$img_M = '1024';
$img_S = '480';
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename);}
elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename);}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=644) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
}
elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
}
elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) { chmod($filename,$permissions); }
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
}
elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
}
elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()
);
$this->image = $new_image;
}
}
// And resize
// ----------
?>
|
C#
|
UTF-8
| 5,896 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Threading;
using System.Threading.Tasks;
using DiagnosticCore.Statistics;
namespace DiagnosticCore
{
/// <summary>
/// Register Options for tracker callbacks and Cancelltion token
/// </summary>
public class ProfilerTrackerOptions
{
/// <summary>
/// CancellcationToken to cancel reading event channel.
/// </summary>
public CancellationTokenSource CancellationTokenSource { get; set; } = new CancellationTokenSource();
/// <summary>
/// Callback invoke when Contention Event emitted (generally lock event) and error.
/// </summary>
public (Func<ContentionEventStatistics, Task> OnSuccess, Action<Exception> OnError) ContentionEventCallback { get; set; }
/// <summary>
/// Callback invoke when GC Event emitted and error.
/// </summary>
public (Func<GCEventStatistics, Task> OnSuccess, Action<Exception> OnError) GCEventCallback { get; set; }
/// <summary>
/// Callback invoke when ThreadPool Event emitted and error.
/// </summary>
public (Func<ThreadPoolEventStatistics, Task> OnSuccess, Action<Exception> OnError) ThreadPoolEventCallback { get; set; }
/// <summary>
/// Callback invoke when Timer GCInfo Event emitted and error.
/// </summary>
public (Func<GCInfoStatistics, Task> OnSuccess, Action<Exception> OnError) GCInfoTimerCallback { get; set; }
/// <summary>
/// Callback invoke when Timer ProcessInfo Event emitted and error.
/// </summary>
public (Func<ProcessInfoStatistics, Task> OnSuccess, Action<Exception> OnError) ProcessInfoTimerCallback { get; set; }
/// <summary>
/// Callback invoke when Timer ThreadInfo Event emitted and error.
/// </summary>
public (Func<ThreadInfoStatistics, Task> OnSuccess, Action<Exception> OnError) ThreadInfoTimerCallback { get; set; }
/// <summary>
/// Timer dueTime/interval Options.
/// </summary>
public (TimeSpan dueTime, TimeSpan intervalPeriod) TimerOption { get; set; } = (TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
}
public class ProfilerTracker
{
/// <summary>
/// Singleton instance access.
/// </summary>
public static Lazy<ProfilerTracker> Current = new Lazy<ProfilerTracker>(() => new ProfilerTracker());
/// <summary>
/// Options for the tracker
/// </summary>
public static ProfilerTrackerOptions Options { get; set; } = new ProfilerTrackerOptions();
private readonly IProfiler[] profilerStats;
private int initializedNum;
private ProfilerTracker()
{
// list Stats
profilerStats = new IProfiler[] {
// event
new GCEventProfiler(Options.GCEventCallback.OnSuccess, Options.GCEventCallback.OnError),
new ThreadPoolEventProfiler(Options.ThreadPoolEventCallback.OnSuccess, Options.ThreadPoolEventCallback.OnError),
new ContentionEventProfiler(Options.ContentionEventCallback.OnSuccess, Options.ContentionEventCallback.OnError),
// timer
new ThreadInfoTimerProfiler(Options.ThreadInfoTimerCallback.OnSuccess, Options.ThreadInfoTimerCallback.OnError, Options.TimerOption),
new GCInfoTimerProfiler(Options.GCInfoTimerCallback.OnSuccess, Options.GCInfoTimerCallback.OnError, Options.TimerOption),
new ProcessInfoTimerProfiler(Options.ProcessInfoTimerCallback.OnSuccess, Options.ProcessInfoTimerCallback.OnError, Options.TimerOption),
};
}
/// <summary>
/// Start tracking.
/// </summary>
public void Start()
{
// offer thread safe single access
Interlocked.Increment(ref initializedNum);
if (initializedNum != 1) return;
// reset initialization status if cancelled.
Options.CancellationTokenSource.Token.Register(() => initializedNum = 0);
foreach (var profile in profilerStats)
{
profile.Start();
// FireAndForget
profile.ReadResultAsync(Options.CancellationTokenSource.Token);
}
}
/// <summary>
/// Restart tracking.
/// </summary>
public void Restart()
{
if (initializedNum != 1) return;
foreach (var stat in profilerStats)
{
stat.Restart();
}
}
/// <summary>
/// Stop tracking.
/// </summary>
public void Stop()
{
if (initializedNum != 1) return;
foreach (var stat in profilerStats)
{
stat.Stop();
}
}
/// <summary>
/// Cancel tracking.
/// </summary>
public void Cancel()
{
Options.CancellationTokenSource.Cancel();
}
/// <summary>
/// Reset tracking.
/// Available when existing cancellation token source is cancelled.
/// </summary>
/// <param name="cts"></param>
public bool Reset(CancellationTokenSource cts)
{
if (Options.CancellationTokenSource.IsCancellationRequested)
{
Options.CancellationTokenSource = cts;
return true;
}
return false;
}
/// <summary>
/// Show profiler status.
/// </summary>
/// <param name="action"></param>
public void Status(Action<(string Name, bool Enabled)> action)
{
foreach (var profiler in profilerStats)
{
action((profiler.Name, profiler.Enabled));
}
}
}
}
|
Java
|
UTF-8
| 3,794 | 2.125 | 2 |
[] |
no_license
|
package com.example.majujayarental;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import static androidx.room.Room.databaseBuilder;
public class RoomCreateActivity extends AppCompatActivity {
private AppDatabase db = databaseBuilder(getApplicationContext(),
AppDatabase.class, "mobildb").build();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
final EditText Enamapeminjam = findViewById(R.id.Enamapeminjam);
final EditText Etanggalpinjam = findViewById(R.id.Etanggalpinjam);
final EditText Etanggalkembali = findViewById(R.id.Etanggalkembali);
final EditText Enamamobil = findViewById(R.id.Enamamobil);
Button btSubmit = findViewById(R.id.btsubmit);
final stok_mobil stok_mobil = (stok_mobil) getIntent().getSerializableExtra("data");
if(stok_mobil!=null){
Enamapeminjam.setText(stok_mobil.getnamapeminjam());
Etanggalpinjam.setText(stok_mobil.gettanggalpinjam());
Etanggalkembali.setText(stok_mobil.gettanggalkembali());
Enamamobil.setText(stok_mobil.getnamamobil());
btSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stok_mobil.setnamapeminjam(Enamapeminjam.getText().toString());
stok_mobil.settanggalpinjam(Etanggalpinjam.getText().toString());
stok_mobil.settanggalkembali(Etanggalkembali.getText().toString());
stok_mobil.setnamamobil(Enamamobil.getText().toString());
updatestok_mobil(stok_mobil);
}
});
}else{
btSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stok_mobil s = new stok_mobil();
s.setnamapeminjam(Enamapeminjam.getText().toString());
s.settanggalpinjam(Etanggalpinjam.getText().toString());
s.settanggalkembali(Etanggalkembali.getText().toString());
insertData(s);
}
});
}
}
private void updatestok_mobil(final stok_mobil stok_mobil) {
new AsyncTask<Void, Void, Long>(){
@Override
protected Long doInBackground(Void... voids) {
long status = db.mobilDAO().updatenopol(stok_mobil);
return status;
}
@Override
protected void onPostExecute(Long status) {
Toast.makeText(RoomCreateActivity.this, "status row "+status, Toast.LENGTH_SHORT).show();
}
}.execute();
}
private void insertData(final stok_mobil stok_mobil){
new AsyncTask<Void, Void, Long>(){
@Override
protected Long doInBackground(Void... voids) {
long status = db.mobilDAO().insertnopol(stok_mobil);
return status;
}
@Override
protected void onPostExecute(Long status) {
Toast.makeText(RoomCreateActivity.this, "status row "+status, Toast.LENGTH_SHORT).show();
}
}.execute();
}
public static Intent getActIntent(Activity activity) {
return new Intent(activity, RoomCreateActivity.class);
}
}
|
Java
|
UTF-8
| 1,513 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
package com.github.songjiang951130.leetcode.dp;
public class Square {
/**
* @todo case5 未通过
* @param matrix
* @return
*/
public int maximalSquare(char[][] matrix) {
int len = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] != '1') {
continue;
}
len = Math.max(1, len);
int k = 0;
while (tryLen(matrix, i, j, k)) {
k++;
len = Math.max(k, len);
}
}
}
return len * len;
}
/**
* 尝试该处 长为len的外圈是否可行
*
* @param matrix
* @param i
* @param j
* @param len
* @return
*/
private boolean tryLen(char[][] matrix, int i, int j, int len) {
if (i + len >= matrix.length - 1 || i + len >= matrix[i].length - 1) {
return false;
}
if (j + len >= matrix[i].length - 1 || j + len >= matrix.length - 1) {
return false;
}
for (int m = i; m < i + len; m++) {
System.out.println(m + " " + i + " " + j + " " + len);
if (matrix[i + len][j + m] != '1') {
return false;
}
System.out.println(4);
if (matrix[i + m][j + len] != '1') {
return false;
}
}
return true;
}
}
|
Python
|
UTF-8
| 184 | 3.390625 | 3 |
[] |
no_license
|
vowels = ['a', 'e', 'i', 'o', 'u']
types = ["Vowel" if i in vowels else "Consonant" for i in "hello"]
types = ['Vowel' if i in vowels else "Consonents" for i in "hello"]
print(types)
|
Python
|
UTF-8
| 371 | 3.8125 | 4 |
[] |
no_license
|
while True: # (1) it is a while look whose condition is always true
print('Please type your name.')
name = input() # (2)
if name == 'your name': # (3) if statement is present inside the wile statement
break # (4)
print('Thank you!') # (5)
|
Java
|
UTF-8
| 3,418 | 2.546875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
//snippet-sourcedescription:[ListMetrics.java demonstrates how to list Amazon CloudWatch metrics.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-service:[Amazon CloudWatch]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.cloudwatch;
// snippet-start:[cloudwatch.java2.list_metrics.import]
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest;
import software.amazon.awssdk.services.cloudwatch.model.ListMetricsResponse;
import software.amazon.awssdk.services.cloudwatch.model.Metric;
// snippet-end:[cloudwatch.java2.list_metrics.import]
/**
* Before running this Java V2 code example, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class ListMetrics {
public static void main(String[] args) {
final String usage = "\n" +
"Usage:\n" +
" <namespace> \n\n" +
"Where:\n" +
" namespace - The namespace to filter against (for example, AWS/EC2). \n" ;
if (args.length != 1) {
System.out.println(usage);
System.exit(1);
}
String namespace = args[0];
Region region = Region.US_EAST_1;
CloudWatchClient cw = CloudWatchClient.builder()
.region(region)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
listMets(cw, namespace) ;
cw.close();
}
// snippet-start:[cloudwatch.java2.list_metrics.main]
public static void listMets( CloudWatchClient cw, String namespace) {
boolean done = false;
String nextToken = null;
try {
while(!done) {
ListMetricsResponse response;
if (nextToken == null) {
ListMetricsRequest request = ListMetricsRequest.builder()
.namespace(namespace)
.build();
response = cw.listMetrics(request);
} else {
ListMetricsRequest request = ListMetricsRequest.builder()
.namespace(namespace)
.nextToken(nextToken)
.build();
response = cw.listMetrics(request);
}
for (Metric metric : response.metrics()) {
System.out.printf("Retrieved metric %s", metric.metricName());
System.out.println();
}
if(response.nextToken() == null) {
done = true;
} else {
nextToken = response.nextToken();
}
}
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
// snippet-end:[cloudwatch.java2.list_metrics.main]
}
|
C
|
UTF-8
| 11,552 | 2.765625 | 3 |
[] |
no_license
|
//
// server.c
// File Server
//
// Created by Alessio Giordano on 23/12/18.
//
// O46001858 - 23/12/18
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#define UTENTI 5
/*
Generale
*/
char homepath[4097] = "";
int LastIndexOf(char c, char *str) {
int index = -1; int max = strlen(str);
for(int i = 0; i < max; i++) {
if(c == str[i]) index = i;
};
return index;
}
/* ***************************************** */
/*
Gestione della lista dei path
*/
pthread_mutex_t locker;
typedef struct pathnode {
char path[4097];
struct pathnode *next;
} pathnode_t;
typedef pathnode_t* pathlist_t;
pathlist_t ind = NULL;
pathlist_t cur = NULL;
pthread_mutex_t lista;
void AddPathList(char *pat) {
pathlist_t temp_list;
temp_list = (pathlist_t)malloc(sizeof(pathnode_t));
strncpy(temp_list->path, pat, 4097);
temp_list->next = NULL;
if (cur == NULL) {
ind = temp_list;
cur = temp_list;
} else {
cur->next = temp_list;
cur = temp_list;
};
}
void ScanDir(char *pat) {
DIR *dir; struct dirent *dir_info;
if( (dir = opendir(pat)) != NULL) {
while ( (dir_info = readdir(dir)) != NULL) {
char abs_path[4097];
if ( ((dir_info->d_type == DT_DIR) || (dir_info->d_type == DT_REG)) &&
((strcmp(dir_info->d_name, ".") != 0) && (strcmp(dir_info->d_name, "..") != 0)) ) {
strcpy(abs_path, pat);
strcat(abs_path, dir_info->d_name);
if (dir_info->d_type == DT_DIR) {
abs_path[0] = 'd';
strcat(abs_path, "/");
};
AddPathList(abs_path);
};
};
closedir(dir);
};
}
int ScanList(char *dir) {
pathlist_t tem = ind; pathlist_t pre = NULL;
while (tem != NULL) {
if (tem->path[0] == 'd') {
strcpy(dir, tem->path);
dir[0] = '/';
if (tem == ind) {
if (ind->next == NULL) {
ind = NULL;
cur = NULL;
} else {
ind = tem->next;
};
} else if (tem->next == NULL) {
pre->next = NULL;
cur = pre;
} else {
pre->next = tem->next;
};
free(tem);
return 1;
};
pre = tem;
tem = tem->next;
};
return 0;
}
void *ListHandler(void *args) {
while(1) {
char pat[4097];
pthread_mutex_lock(&lista);
if ( ScanList(pat) ) {
ScanDir(pat);
} else {
int *retval = 0;
pthread_mutex_unlock(&lista);
pthread_exit( (void*)retval );
};
pthread_mutex_unlock(&lista);
}
}
pthread_t Scanner(char *dir) {
ScanDir(dir);
char messaggio[] = ""; pthread_t tid;
pthread_create(&tid, NULL, ListHandler, (void*)messaggio);
return tid;
}
/* ***************************************** */
/*
Sistema di Login
*/
typedef struct utente {
char nome[50];
char password[50];
char token[50];
} utente;
typedef char token[50];
utente clienti[UTENTI];
int Login(int login_to, char *nome, char *password, token tok) {
char login_buffer[50] = "";
for(int i = 0; i < UTENTI; i++) {
if( (strcmp(nome, clienti[i].nome) == 0) && (strcmp(password, clienti[i].password) == 0) && (strlen(nome) > 4) ) {
// Genero il token
sprintf(clienti[i].token, "%c%d%c%c", clienti[i].nome[0], (int)time(NULL), clienti[i].nome[3], clienti[i].nome[4]);
strcpy(tok, clienti[i].token);
strcpy(login_buffer, clienti[i].token);
send(login_to, (void*)login_buffer, sizeof(login_buffer), 0);
return 1;
};
};
strcpy(login_buffer, "ERR");
send(login_to, (void*)login_buffer, sizeof(login_buffer), 0);
return 0;
}
int IsLogged(token tok) {
for(int i = 0; i < UTENTI; i++) {
if( strcmp(tok, clienti[i].token) == 0 ) return 1;
};
return 0;
}
int PopulateClients(char *path) {
FILE *f;
f = fopen(path, "r");
if(f != NULL) {
for(int i = 0; i < UTENTI; i++) {
char temp_nome[50] = ""; char temp_password[50] = "";
int result = fscanf(f, "%s %s", temp_nome, temp_password);
if( (result == 2) && (strlen(temp_nome) > 4) ) {
strcpy(clienti[i].nome, temp_nome); strcpy(clienti[i].password, temp_password);
} else if (result == EOF) {
break;
} else {
i--;
};
};
return 1;
} else {
return 0;
};
}
/* ***************************************** */
/*
Listing dei File disponibili
*/
void Listing(int list_to) {
pathlist_t position = ind;
char buffer[4097] = "";
while (position != NULL) {
strncpy(buffer, "", sizeof(buffer));
strcpy(buffer, position->path);
send(list_to, (void*)buffer, sizeof(buffer), 0);
position = position->next;
};
strncpy(buffer, "", sizeof(buffer));
strcpy(buffer, "END");
send(list_to, (void*)buffer, sizeof(buffer), 0);
}
/* ***************************************** */
/*
Funzionalità di Download
*/
int Download(char *path, int download_to) {
int target = strlen(homepath);
if ( strncmp(path, homepath, target) == 0) {
int requested_file = open(path, O_RDONLY, NULL);
if (requested_file != -1) {
char buffer[200] = "";
while( read(requested_file, (void*)buffer, sizeof(buffer)) != 0) {
send(download_to, (void*)buffer, sizeof(buffer), 0);
strncpy(buffer, "", sizeof(buffer));
};
close(requested_file);
sprintf(buffer, "%d", EOF);
send(download_to, (void*)buffer, sizeof(buffer), 0);
return 1;
} else {
char buffer[200] = "ERR";
send(download_to, (void*)buffer, sizeof(buffer), 0);
return 0;
};
} else {
char buffer[200] = "ERR";
send(download_to, (void*)buffer, sizeof(buffer), 0);
return 0;
};
};
/* ***************************************** */
/*
Funzionalità di Upload
*/
int Upload(char *name, int upload_from) {
char recvdir[4097];
strcpy(recvdir, homepath); strcat(recvdir, "recvdir/");
mkdir(recvdir, S_IRUSR | S_IWUSR | S_IXUSR);
strcat(recvdir, name);
int uploaded_file = open(recvdir, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR);
if (uploaded_file != -1) {
char buffer[200] = ""; char EOFcond[200]; sprintf(EOFcond, "%d", EOF);
while( strcmp(buffer, EOFcond) != 0 ) {
strncpy(buffer, "", sizeof(buffer));
recv(upload_from, (void*)buffer, sizeof(buffer), 0);
if(strcmp(buffer, EOFcond) != 0) write(uploaded_file, buffer, sizeof(buffer));
};
close(uploaded_file);
return 1;
} else {
return 0;
};
};
/* ***************************************** */
/*
Gestione delle richieste TCP del client
*/
void *ClientHandler(void *args) {
int socket_client = (*(int *)args);
while(1) {
char buffer[4118] = "";
recv(socket_client, (void*)buffer, sizeof(buffer), 0);
char comando[20] = ""; token tok; char argomento1[4097]; char argomento2[50];
sscanf(buffer, "%s %s %s %s", comando, tok, argomento1, argomento2);
if(strcmp(comando, "LOGIN") == 0) {
// Verifica che l'utente in questione sia collegato
if(Login(socket_client, argomento1, argomento2, tok)) {
printf("Login Effettuato - Token: %s\n", tok);
} else {
printf("Login Fallito\n");
}
} else if(strcmp(comando, "LIST") == 0) {
// Invia al client la lista di file disponibili al Download
if(IsLogged(tok)) {
Listing(socket_client);
printf("Listing dei file disponibili a %s\n", tok);
} else {
printf("Tentativo di Listing non autorizzato\n");
};
} else if(strcmp(comando, "DOWNLOAD") == 0) {
// Incomincia la procedura di download
if(IsLogged(tok)) {
if(Download(argomento1, socket_client)) {
printf("%s ha scaricato il file %s\n", tok, argomento1);
} else {
printf("Fallito Download del file %s\n", argomento1);
};
} else {
printf("Tentativo di Download non autorizzato\n");
};
} else if(strcmp(comando, "UPLOAD") == 0) {
// Incomincia la procedura di upload
if(IsLogged(tok)) {
if(Upload(argomento1, socket_client)) {
printf("%s ha caricato il file %s\n", tok, argomento1);
} else {
printf("Fallito Upload del file %s\n", argomento1);
};
} else {
printf("Tentativo di Upload non autorizzato\n");
};
} else if(strcmp(comando, "ESCI") == 0) {
close(socket_client);
printf("Disconnesso\n");
pthread_exit(0);
};
strncpy(buffer, "", sizeof(buffer));
};
}
/* ***************************************** */
int main(int argc, const char *argv[]) {
printf("Attendi mentre indicizzo la cartella Home... ");
// Inizializzazione del Mutex e verifica dell'esito
if (pthread_mutex_init(&lista, NULL) != 0) exit(1);
// Creazione della lista a partire dalla home
pthread_t tid;
// La variabile Path è definita nell'header
strcpy(homepath, getenv("HOME")); strcat(homepath, "/");
// strcat(homepath, "Desktop/"); // Usato nella demo mostrata in README.md
tid = Scanner(homepath);
pthread_join(tid, NULL);
printf("Fatto\n");
// Popoliamo il vettore dei Client
if(!PopulateClients("clients.txt")) {
strcpy(clienti[0].nome, "default"); strcpy(clienti[0].password, "default");
};
// Preparazione al Socket TCP
int socket_id = socket(AF_INET, SOCK_STREAM, 0); // Creiamo un socket Internet
if(socket_id < 0) exit(1);
struct sockaddr_in bind_socket_id;
bind_socket_id.sin_family = AF_INET; // Siamo nel dominio di Internet
bind_socket_id.sin_addr.s_addr = INADDR_ANY; // Accettiamo da qualsiasi interfaccia
bind_socket_id.sin_port = htons(8960); // Porta 8960 senza problema di Big/Little End.
int bind_result = bind(socket_id, (struct sockaddr*)&bind_socket_id, sizeof(bind_socket_id)); // Infine facciamo la Bind
if(bind_result < 0) exit(1);
int listen_result = listen(socket_id, UTENTI); // Il numero massimo di client consentiti è definito nella costante UTENTI a inizio file...
if(listen_result < 0) exit(1);
// E 24/12/18 17:51
// TCP stuff
while (1) {
printf("Attendo il client... ");
fflush(stdout);
pthread_t tid;
int accept_result = accept(socket_id, NULL, NULL);
printf("Connesso\n");
pthread_create(&tid, NULL, ClientHandler, (void *)&accept_result);
};
}
|
PHP
|
UTF-8
| 5,707 | 2.953125 | 3 |
[] |
no_license
|
<?php
/**
* PHP Class to manage table structures (print table, order by, etc)
*
* <code><?php
* include('table.class.php');
* $table = new tableManager();
* ? ></code>
*
* ==============================================================================
*
* @version $Id: table.class.php,v 0.93 2008/05/02 10:54:32 $
* @copyright Copyright (c) 2007 Lorenzo Becchi (http://ominiverdi.org)
* @author Lorenzo Becchi <[email protected]>
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
*
* ==============================================================================
*/
/**
* Table manager- The main class
*
* @param string $dbName
* @param string $dbHost
* @param string $dbUser
* @param string $dbPass
* @param string $dbQuery
*/
class flowNavigator{
/*Settings*/
/**
* The variable holding the session info for this class
* var string
*/
var $sessionVariable = 'flowNavigatorClass';
/**
* Display errors? Set this to true if you are going to seek for help, or have troubles with the script
* var bool
*/
var $displayErrors = true;
/*Do not edit after this line*/
/**
* table navigation variables
*/
var $id;//the current ID
var $id_list;//the list of all IDs
var $current_page; //the current page of the navigation
var $start_page = 1; //the starting page for the navigation
var $tot_rows; //the total number of resulting rows
/**
* Class Constructure
*
* @param string $dbConn
* @param array $settings
* @return void
*/
function flowNavigator($settings = '')
{
$this->id = '';
$this->id_list = '';
$this->first = '';
$this->prev = '';
$this->last = '';
$this->next = '';
$this->current = '';
$this->tot = '';
if ( is_array($settings) ){
foreach ( $settings as $k => $v ){
if ( !isset( $this->{$k} ) ) die('Property '.$k.' does not exists. Check your settings.');
$this->{$k} = $v;
}
}
//$this->remCookieDomain = $this->remCookieDomain == '' ? $_SERVER['HTTP_HOST'] : $this->remCookieDomain;
if ( !empty($_SESSION[$this->sessionVariable]) )
{
$this->sessionData = $_SESSION[$this->sessionVariable];
}
$id = $this->id;
//print "id: ".$_REQUEST['id'];
//print "<br>list: ".$this->sessionData['id_list'];
$ids=explode(',',$this->id_list);
$i = 0;
$f;//first
$p;//prev
$a;//actual
$n;//next
$l;//last
$tot = count($ids)-1;
foreach ($ids as $r) {
if($r==$id){
$a = $ids[$i];
$pi = $i-1;
$ni = $i+1;
//echo "<p>pi,ni: $pi,$ni</p>";
$p =(isset($ids[$pi]))?$ids[$pi]:null;
$n =(isset($ids[($ni)]))?$ids[($ni)]:null;
}
$i++;
};
if (isset($ids[0]) && $ids[0] != $id){
$qs = 'id='.$ids[0];
$this->first = " <a href='{$_SERVER['PHP_SELF']}?$qs'><< first</a> ";
} else
$this->first = "<< first";
if (isset($p)){
$qs = 'id='.$p;
$this->prev = " <a href='{$_SERVER['PHP_SELF']}?$qs'> < prev</a> ";
} else
$this->prev = " < prev";
$c = array_search($id,$ids)+1;
$t = count($ids);
//$output .= " - ($c of $t) - ";
$this->current = $c;
$this->tot = $t;
if (isset($n)){
$qs = 'id='.$n;
$this->next = "<a href='{$_SERVER['PHP_SELF']}?$qs'>next ></a> ";
} else
$this->next =" next > ";
if (isset($ids[$tot]) && $ids[$tot] != $id){
$qs = 'id='.$ids[$tot];
$this->last = " <a href='{$_SERVER['PHP_SELF']}?$qs'>last >></a> ";
} else
$this->last = " last >>";
//$output .= "";
}
/**
* Function to determine if a property is true or false
* param string $prop
* @return bool
*/
function is($prop){
return $this->get_property($prop)==1?true:false;
}
/**
* return the list of all ids of the active recordset
* @return list
*/
function get_ids(){
return $id_list;
}
/**
* all the values...
* @return varchar
*/
function get_first(){
return $this->first;
}
function get_last(){
return $this->last;
}
function get_prev(){
return $this->prev;
}
function get_next(){
return $this->next;
}
function get_current(){
return $this->current;
}
function get_tot(){
return $this->tot;
}
////////////////////////////////////////////
// PRIVATE FUNCTIONS
////////////////////////////////////////////
/**
* Error holder for the class
* @access private
* @param string $error
* @param int $line
* @param bool $die
* @return bool
*/
function error($error, $line = '', $die = false) {
if ( $this->displayErrors )
echo '<b>Error: </b>'.$error.'<br /><b>Line: </b>'.($line==''?'Unknown':$line).'<br />';
if ($die) exit;
return false;
}
/**
* replace key/value pairs in query strings
* @access private
* @param string $nq
* @return string
*/
function replace_query_string($nq){
$na =explode('&',$nq);
$q = $_SERVER['QUERY_STRING'];
$res = array();
$qa = explode('&',$q);
foreach($qa as $a){
//print "<p>a:$a</p>";
if(strstr($a,'=')){
$aa =explode('=',$a);
$ak = $aa[0];
$av = $aa[1];
if($ak!='del')$res[$ak]= $av;
}
}
//print_r($res);
foreach($na as $n){
//print "<p>n:$n</p>";
if(strstr($n,'=')){
$nn = explode('=',$n);
$nk = $nn[0];
$nv = $nn[1];
$res[$nk]= $nv;
}
}
//print_r($res);
$q ='';
foreach($res as $k=>$r){
$q.=(strlen($q)>0)? '&'.$k."=".$r:$k."=".$r;
}
//print "<p>q: $q</p>";
return $q;
}
}
?>
|
PHP
|
UTF-8
| 1,011 | 2.578125 | 3 |
[
"Unlicense"
] |
permissive
|
<?php
namespace ServiceBoiler\Prf\Site\Mail\Esb;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use ServiceBoiler\Prf\Site\Models\EsbUserVisit;
class EsbVisitEmail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
/**
* @var EsbUserVisit
*/
public $esbVisit;
public $subject;
public $view;
/**
* Create a new message instance.
* @param EsbVisit $esbVisit
*/
public function __construct(EsbUserVisit $esbVisit, $view, $subject='Ferroli')
{
$this->esbVisit = $esbVisit;
$this->subject = $subject;
$this->view = $view;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this
->subject($this->subject .' ' .$this->esbVisit->created_at->format('d.m.Y').'/' .$this->esbVisit->id)
->view($this->view);
}
}
|
Markdown
|
UTF-8
| 8,195 | 3.203125 | 3 |
[] |
no_license
|
---
lang: fr
lang-ref: ch.02-3
title: Motivation des problèmes, algèbre linéaire et visualisation
lecturer: Alfredo Canziani
authors: Rajashekar Vasantha
date: 04 Feb 2021
typora-root-url: 02-3
translation-date: 19 Jun 2021
translator: Loïck Bourdois
---
<!--
## Resources
Please follow Alfredo Canziani [on Twitter @alfcnz](https://twitter.com/alfcnz). Videos and textbooks with relevant details on linear algebra and singular value decomposition (SVD) can be found by searching Alfredo's Twitter, for example type `linear algebra (from:alfcnz)` in the search box.
-->
## Ressources
Nous vous invitons à suivre Alfredo Canziani [sur Twitter @alfcnz](https://twitter.com/alfcnz). Vous trouverez sur son compte des vidéos et des manuels contenant des détails pertinents sur l'algèbre linéaire et la décomposition en valeurs singulières (SVD). Ce contenu est trouvable en effectuant une recherche (en anglais) sur le Twitter d'Alfredo, en tapant par exemple `linear algebra (from:alfcnz)` dans la barre de recherche.
<!--
## [Neural Nets: Rotation and Squashing](https://youtu.be/0TdAmZUMj2k)
A traditional neural network is an alternating collection of two blocks - the linear blocks and the non-linear blocks. Given below is a block diagram of a traditional neural network.
<br>
<br>
<center>
<img src="{{site.baseurl}}/images/week02/02-3/figure1.png" width="1000px"/>
Figure 1: Block Diagram of a Traditional Neural Network
</center>
<br>
The linear blocks (Rotations, for simplicity) are given by:
$$
\vect{s}_{k+1} = \mW_k z_k
$$
And the non-linear blocks (Squashing functions for intuitive understanding) are given by:
$$ \vect{z}_k = h(\vect{s}_k) $$
In the above diagram and equations, $$\vx \in \mathbb{R}^n$$ represents the input vector. $$\mW_k \in \mathbb{R}^{n_{k} \times n_{k-1}}$$ represents the matrix of an affine transformation corresponding to the $$k^{\text{th}}$$ block and is described below in further detail. The function $h$ is called the activation function and this function forms the non-linear block of the neural network. Sigmoid, ReLu and tanh are some of the common activation functions and we will look at them in the later parts of this section. After alternate applications of linear and non-linear blocks, the above network produces an output vector $$\vect{s}_k \in \mathbb{R}^{n_{k-1}}$$.
Let us first have a look at the linear block to gain some intuition on affine transformations. As a motivating example, let us consider image classification. Suppose we take a picture with a 1 megapixel camera. This image will have about 1,000 pixels vertically and 1,000 pixels horizontally, and each pixel will have three colour dimensions for red, green, and blue (RGB). Each particular image can then be considered as one point in a 3 million-dimensional space. With such massive dimensionality, many interesting images we might want to classify -- such as a dog *vs.* a cat -- will essentially be in the same region of the space.
In order to effectively separate these images, we consider ways of transforming the data in order to move the points. Recall that in 2-D space, a linear transformation is the same as matrix multiplication. For example, the following are transformations, which can be obtained by changing matrix characterictics:
- Rotation (when the matrix is orthonormal).
- Scaling (when the matrix is diagonal).
- Reflection (when the determinant is negative).
- Shearing.
- Translation.
Note that translation alone is not linear since 0 will not always be mapped to 0, but it is an affine transformation. Returning to our image example, we can transform the data points by translating such that the points are clustered around 0 and scaling with a diagonal matrix such that we "zoom in" to that region. Finally, we can do classification by finding lines across the space which separate the different points into their respective classes. In other words, the idea is to use linear and nonlinear transformations to map the points into a space such that they are linearly separable. This idea will be made more concrete in the following sections.
In the next part, we visualize how a neural network separates points and a few linear and non-linear transformations. This can be accessed [here](https://atcold.github.io/pytorch-Deep-Learning/en/week01/01-3/).
-->
## [Réseaux neuronaux : rotation et écrasement](https://youtu.be/0TdAmZUMj2k)
Un réseau de neurones traditionnel est une collection alternée de deux blocs : les blocs linéaires et les blocs non linéaires.
Voici le schéma fonctionnel d'un réseau de neurones traditionnel.
<br>
<br>
<center>
<img src="{{site.baseurl}}/images/week02/02-3/figure1.png" width="1000px"/>
<b>Figure 1 :</b> Schéma d'un réseau de neurones traditionnel
</center>
<br>
Les blocs linéaires (rotations pour simplifier) sont donnés par :
$$
\vect{s}_{k+1} = \mW_k z_k
$$
Et les blocs non linéaires (fonctions d'écrasement pour une compréhension intuitive) sont donnés par :
$$ \vect{z}_k = h(\vect{s}_k) $$
Dans le schéma et les équations ci-dessus, $$\vx \in \mathbb{R}^n$$ représente le vecteur d'entrée.
$$\mW_k \in \mathbb{R}^{n_{k} \times n_{k-1}}$$ représente la matrice d'une transformation affine correspondant au $$k^{\text{ème}}$$ bloc et est décrite plus en détail ci-dessous.
La fonction $h$ est appelée fonction d'activation et cette fonction forme le bloc non linéaire du réseau neuronal.
Sigmoïde, ReLU et tanh sont quelques-unes des fonctions d'activation les plus courantes et nous les examinerons dans les parties suivantes de cette section.
Après des applications alternées des blocs linéaire et non linéaire, le réseau ci-dessus produit un vecteur de sortie $$\vect{s}_k \in \mathbb{R}^{n_{k-1}}$$.
Examinons d'abord le bloc linéaire pour comprendre les transformations affines. Comme exemple considérons la classification d'images.
Supposons que nous prenions une photo avec un appareil photo de $1$ mégapixel.
Cette image aura environ $1 000$ pixels verticalement et $1 000$ pixels horizontalement, et chaque pixel aura trois dimensions de couleur pour le rouge, le vert et le bleu (RVB).
Chaque image peut donc être considérée comme un point dans un espace à $3$ millions de dimensions.
Avec une telle dimensionnalité, de nombreuses images intéressantes que nous pourrions vouloir classer, comme un chien *vs* un chat, se trouveront essentiellement dans la même région de l'espace.
Afin de séparer efficacement ces images, nous envisageons des moyens de transformer les données afin de déplacer les points.
Rappelons que dans l'espace bidimensionnel, une transformation linéaire équivaut à une multiplication de matrice.
Par exemple, les transformations suivantes peuvent être obtenues en changeant les caractéristiques de la matrice :
- Rotation : lorsque la matrice est orthonormée.
- Mise à l'échelle (« scalabilité ») : lorsque la matrice est diagonale.
- Réflexion : lorsque le déterminant est négatif.
- *Shearing*.
- Translation.
A noter que la translation seule n'est pas linéaire puisque $0$ ne sera pas toujours mis en correspondance avec 0, mais c'est une transformation affine.
Pour revenir à notre exemple d'image, nous pouvons transformer les points de données en les translatant de manière à ce qu'ils soient regroupés autour de 0 et en les mettant à l'échelle à l'aide d'une matrice diagonale de manière à effectuer un « zoom avant » sur cette région.
Enfin, nous pouvons effectuer une classification en trouvant des lignes dans l'espace qui séparent les différents points dans leurs classes respectives.
En d'autres termes, l'idée est d'utiliser des transformations linéaires et non linéaires pour représenter les points dans un espace tel qu'ils soient linéairement séparables.
Cette idée sera rendue plus concrète dans les sections suivantes.
Dans la suite, nous visualisons comment un réseau neuronal sépare des points et quelques transformations linéaires et non linéaires.
Ce contenu est essentiellement le même que celui de l'année dernière, ainsi nous vous invitons à vous rendre [ici](https://atcold.github.io/pytorch-Deep-Learning/fr/week01/01-3/) pour le consulter.
|
Markdown
|
UTF-8
| 2,409 | 2.6875 | 3 |
[] |
no_license
|
# SO item 085
I have an Excel AddIn (`.xlam` file) and within it is a few macros and my attemt at a custom ribbon tab. The Macros work as expected but now I am trying to make a ribbon to call them to be more user friendly. I have the ribbon and a button which works, and a dropdown menu which I cannot figure out. I am unsure of what the Macro Parameters need to be. Below is what I have thus far.
The XML for the ribbon (Works!):
```
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon>
<tabs>
<tab id="My_Tab" label="My Tab">
<group id="NC_Material" label="Button1">
<button id="Button1" label="1st button" size="large" onAction="Module1.Button1Click" imageMso="ResultsPaneStartFindAndReplace" />
<dropDown id="DropDown" onAction="Module1.DropDownAction">
<item id="ddmItem1" label="Item1" />
<item id="ddmItem2" label="Item2" />
</dropDown>
</group >
</tab>
</tabs>
</ribbon>
</customUI>
```
The VBA in Module1 of the `.xlam` files VBA Project:
```
'this one works
Public Sub Button1Click(ByVal control As IRibbonControl)
call Button1Macro
End Sub
'this one does not work
Public Sub DropDownAction(ByVal control As IRibbonControl)
call DropDownMacro
End Sub
```
I am getting errors when I change the value of the drop down menu in my ribbon. I do not know what parameters I need for the onAction macro of the drop down menu. I have been unable to find a good reference or example.
I am unable to do this using Visual Studio and cannot download any utilities or other programs.
Thanks in advance.
----
If you want to save your sanity, you can use [Andy Pope's Ribbon Editor](http://www.andypope.info/vba/ribboneditor.htm) which will generate the callbacks automatically (at least the text for them). Then you just copy them into the VBA module. (I am not affiliated with that add-in, I just use it and recommend it highly)
Using that tool, I get the following for `onAction` within a `Dropdown`
```
Public Sub DropDownAction(control as IRibbonControl, id as String, index as Integer)
'
' Code for onAction callback. Ribbon control dropDown
'
End Sub
```
Working code is also shown [in this answer](http://stackoverflow.com/questions/4562550/getting-the-selected-item-from-the-dropdown-in-a-ribbon-in-word-2007-using-macro) which was near the top of my search.
|
JavaScript
|
UTF-8
| 1,612 | 2.921875 | 3 |
[] |
no_license
|
window.onload = function () {
fetchAllPosts();
};
async function fetchAllPosts() {
try {
const response = await fetch("http://localhost:5000/posts");
const posts = await response.json();
let postHTML = "";
for (post of posts) {
let dateObj = new Date(post.date);
postHTML += `
<tr>
<td>${post.title}</td>
<td>${post.author}</td>
<td>${post.tags}</td>
<td>${formatDate(dateObj)}</td>
<td id="center-icons">
<a href="#" class="admin-links" id="delete-btn" ><i class="far fa-trash-alt" data-id="${
post["_id"]
}"></i></a>
<a href="/web_com/blog-client-template/admin/update-post.html?id=${
post["_id"]
}" class="admin-links"><i class="fas fa-edit"></i></a>
</td>
</tr>
`;
document.querySelector("#blog-content").innerHTML = postHTML;
}
let delBtns = document.querySelectorAll("#delete-btn");
for (let del of delBtns) {
del.addEventListener("click", async function (e) {
let delClick = e.target;
let postId = delClick.dataset.id;
try {
await fetch("http://localhost:5000/posts/" + postId, {
method: "DELETE",
});
delClick.parentNode.parentNode.parentNode.remove();
} catch (error) {
console.log(error);
}
});
}
} catch (error) {
console.log(error);
}
}
function formatDate(dateObj) {
let dateString = String(dateObj).split(" ").splice(0,5).join(" ");
return dateString;
}
|
Python
|
UTF-8
| 3,543 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
#codigo por
#Eduardo Migueis
#Illy Bordini
#Guilherme Lima
from controller import Robot, Motor, DistanceSensor, Camera
import requests
from PIL import Image
import threading
import time
# cria a instancia do robo
robot = Robot()
time_step = 64
max_speed = 6.28
# motor
# rodas da frente
right_motor_front = robot.getDevice('wheel_rf')
right_motor_front.setPosition(float('inf'))
right_motor_front.setVelocity(0.0)
left_motor_front = robot.getDevice('wheel_lf')
left_motor_front.setPosition(float('inf'))
left_motor_front.setVelocity(0.0)
# rodas de traz
right_motor_back = robot.getDevice('wheel_rb')
right_motor_back.setPosition(float('inf'))
right_motor_back.setVelocity(0.0)
left_motor_back = robot.getDevice('wheel_lb')
left_motor_back.setPosition(float('inf'))
left_motor_back.setVelocity(0.0)
# sensor de IR
right_ir = robot.getDevice('RIGHT')
right_ir.enable(time_step)
mid_ir = robot.getDevice('MID')
mid_ir.enable(time_step)
left_ir = robot.getDevice('LEFT')
left_ir.enable(time_step)
camera = robot.getDevice("camera")
camera.enable(time_step)
#thread que aciona o server para abrir uma instancia do
#chrome a cada dez segundos com uma nova foto
def sendImg():
while 1 == 1:
time.sleep(10)
img = camera.getImage()
camera.saveImage("photo.png", 100)
requests.post('http://localhost:5000/api/img')
counter = 0
# Main loop:
# - efetua os passos da simulacao ate que o Webots pare o controller
while robot.step(time_step) != -1:
if counter == 0:
print("malygno")
x = threading.Thread(target=sendImg)
x.start()
counter = 1
# le-se os sensores:
right_ir_val = right_ir.getValue()
mid_ir_val = mid_ir.getValue()
left_ir_val = left_ir.getValue()
left_speed_f = max_speed # _f for front
right_speed_f = max_speed # _f for front
left_speed_b = max_speed # _b for back
right_speed_b = max_speed # _b for back
# Processamento dos dados do sensor.
if left_ir_val < 300 and right_ir_val < 300 and mid_ir_val >= 300:
left_motor_front.setVelocity(left_speed_f)
right_motor_front.setVelocity(right_speed_f)
left_motor_back.setVelocity(left_speed_b)
right_motor_back.setVelocity(right_speed_b)
if left_ir_val < 300 and right_ir_val >= 300 and mid_ir_val >= 300:
left_motor_front.setVelocity(left_speed_f)
right_motor_front.setVelocity(0)
left_motor_back.setVelocity(left_speed_b)
right_motor_back.setVelocity(0)
if left_ir_val >= 300 and right_ir_val < 300 and mid_ir_val >= 300:
left_motor_front.setVelocity(0)
right_motor_front.setVelocity(right_speed_f)
left_motor_back.setVelocity(0)
right_motor_back.setVelocity(right_speed_b)
if left_ir_val >= 300 and right_ir_val < 300 and mid_ir_val < 300:
left_motor_front.setVelocity(0)
right_motor_front.setVelocity(right_speed_f)
left_motor_back.setVelocity(0)
right_motor_back.setVelocity(right_speed_b)
if left_ir_val < 300 and right_ir_val >= 300 and mid_ir_val < 300:
left_motor_front.setVelocity(left_speed_f)
right_motor_front.setVelocity(0)
left_motor_back.setVelocity(left_speed_b)
right_motor_back.setVelocity(0)
if left_ir_val < 300 and right_ir_val < 300 and mid_ir_val < 300:
left_motor_front.setVelocity(left_speed_f)
right_motor_front.setVelocity(right_speed_f)
left_motor_back.setVelocity(left_speed_b)
right_motor_back.setVelocity(right_speed_b)
pass
|
Java
|
UTF-8
| 1,265 | 2.203125 | 2 |
[] |
no_license
|
package br.com.PersistStruts.servicos;
import java.util.List;
import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import br.com.PersistStruts.dao.ClienteDao;
import br.com.PersistStruts.modelo.Cliente;
@Service
public class ClienteServico {
@Autowired
ClienteDao clienteDao;
public String salvar(Cliente cliente){
String msg ="Cadastro Efetuado";
try {
clienteDao.save(cliente);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
msg = e.getMessage();
}
return msg;
}
public List<Cliente> pesquisarCliente(){
return clienteDao.findAll();
}
public List<Cliente> pesquisarClienteNome(Cliente cliente){
return clienteDao.findByNamedQuery("Cliente.buscaNome",cliente.getNome());
}
public Cliente pesquisarClienteId(Cliente cliente){
return clienteDao.findById(cliente.getId());
}
public Cliente pesquisarId(Integer id){
return clienteDao.findById(id);
}
/*
public void deletarCliente(Cliente cliente){
clienteDao.delete(cliente);
}*/
public void deletarCliente(Cliente cliente){
clienteDao.delete(cliente.getId());
}
}
|
TypeScript
|
UTF-8
| 1,512 | 2.734375 | 3 |
[] |
no_license
|
import {Injectable} from '@angular/core';
import {User} from '../models/user';
import {JwtHelper} from 'angular2-jwt';
@Injectable()
export class AuthService {
private _token_key = 'id_token';
constructor() {
}
public login(token: string): void {
let jwtHelper = new JwtHelper();
try {
jwtHelper.decodeToken(token);
localStorage.setItem(this._token_key, token);
}
catch (error) {
localStorage.removeItem(this._token_key);
}
}
public getToken() {
return localStorage.getItem(this._token_key);
}
public isLoggedIn(): boolean {
let token = this.getToken();
if (!token)
return false;
let jwtHelper = new JwtHelper();
return !jwtHelper.isTokenExpired(token);
}
public logout(): void {
localStorage.removeItem(this._token_key)
}
public getUser(): User {
let token = this.getToken();
if (!token)
return {name: '', roles: []};
let jwtHelper = new JwtHelper();
let tokenData = jwtHelper.decodeToken(token);
return tokenData;
}
public hasRole(role: string | Array<string>) {
if (!this.getUser())
return false;
if (typeof role === 'string')
return this.hasRoleString(role);
if (role instanceof Array) {
return role.some(r => this.hasRoleString(r))
}
return false;
}
private hasRoleString(role: string): boolean {
const user = this.getUser();
if(!user.roles)
return false;
return user.roles.some(x => x === role);
}
}
|
Python
|
UTF-8
| 911 | 2.765625 | 3 |
[] |
no_license
|
class Presenter:
"""This class controls the console view
author: V. Van den Schrieck
date: November 2020
"""
def __init__(self, sites):
self.__sites = sites
self.__sites.attach(self)
self.__view = None
def set_view(self, view_instance):
self.__view = view_instance
def test_all(self):
"""Called by the view, to be applied to the model"""
self.__sites.test_all()
def sites(self):
"""Returns a representation of the sites for the view"""
view_sites = {}
for site in self.__sites :
view_sites[site.name] = site.status
return view_sites
def update(self, msg=""):
"""Implementation of Observer pattern- Observer side
This method is called whenever the model is modified.
"""
if msg:
self.__view.msg(msg)
else:
self.__view.refresh()
|
Java
|
UTF-8
| 270 | 2.03125 | 2 |
[] |
no_license
|
package sso.domain.user.core.domain;
import sso.util.domain.ValueObject;
public class UserId extends ValueObject<Long> {
private UserId(long value) {
super(value);
}
public static UserId of(long value) {
return new UserId(value);
}
}
|
TypeScript
|
UTF-8
| 1,008 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
import 'reflect-metadata';
export interface DecoratorFunction<T> extends Function {
new (...args: any[]): T;
}
export class DecoratorReader {
private annotationMap: Map<DecoratorFunction<any>, symbol> = new Map();
create<T>(func: DecoratorFunction<T>): Function {
const symbol = Symbol(func.name);
this.annotationMap.set(func, symbol);
return () => {
const data = Reflect.construct(func as Function, arguments);
return Reflect.metadata(symbol, data);
};
}
readClassAnnotation<T>(target: Function, annotation: DecoratorFunction<T>): T | null {
const symbol = this.annotationMap.get(annotation);
if (!symbol) return null;
return Reflect.getMetadata(symbol, target) || null;
}
readPropertyAnnotation<T>(target: Function, propertyName: string, annotation: DecoratorFunction<T>): T | null {
const symbol = this.annotationMap.get(annotation);
if (!symbol) return null;
return Reflect.getMetadata(symbol, target, propertyName) || null;
}
}
|
Python
|
UTF-8
| 976 | 4.34375 | 4 |
[] |
no_license
|
"""
Problem Statement
Given an integer array, find and return all the subsets of the array. The
order of subsets in the output array is not important. However the order of
elements in a particular subset should remain the same as in the input array.
Note: An empty set will be represented by an empty list
Example 1
arr = [9]
output = [[]
[9]]
Example 2
arr = [9, 12, 15]
output = [[],
[15],
[12],
[12, 15],
[9],
[9, 15],
[9, 12],
[9, 12, 15]]
"""
def subsets(arr):
"""
:param: arr - input integer array
Return - list of lists (two dimensional array) where each list represents a subset
TODO: complete this method to return subsets of an array
"""
res = []
dfs(arr, 0, [], res)
return res
def dfs(arr, index, path, res):
res.append(path)
for i in range(index, len(arr)):
dfs(arr, i+1, path + [arr[i]], res)
print(subsets([5, 7]))
|
PHP
|
UTF-8
| 780 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Facade\Ignition\Middleware;
use Facade\FlareClient\Report;
use Facade\IgnitionContracts\SolutionProviderRepository;
class AddSolutions
{
/** @var \Facade\IgnitionContracts\SolutionProviderRepository */
protected $solutionProviderRepository;
public function __construct(SolutionProviderRepository $solutionProviderRepository)
{
$this->solutionProviderRepository = $solutionProviderRepository;
}
public function handle(Report $report, $next)
{
$throwable = $report->getThrowable();
$solutions = $this->solutionProviderRepository->getSolutionsForThrowable($throwable);
foreach ($solutions as $solution) {
$report->addSolution($solution);
}
return $next($report);
}
}
|
Markdown
|
UTF-8
| 2,840 | 3.40625 | 3 |
[] |
no_license
|
# Assignment 1: Welcome to App Lab
Due Monday, September 9
# Instructions
1. Clone this repository to your local computer (hint: use the terminal and the `git clone` command).
2. Open the `welcome-to-app-lab-yourgithubusername` folder in vscode.
3. Edit the file `README.md` in response to the prompt (The Benefits and Costs of My Digital Life)
4. Replace the **About Me** section with your own. I've included my own as a template.
5. Include your answer to the Prompt (The Benefits and Costs of My Digital Life)
6. Delete the **Assignment** and **Instructions** sections.
7. `git push` your changed file - this is your assignment submission (don't forget a `commit` message)!
Be sure and use [markdown](https://medium.com/applab-fall-2019/homework-1-github-bootcamp-bb21077a878b) to help format your document. You can study this document and how it appears on Github to learn more.
# About Me
Hello! My name is Christian and I live in Shanghai, China. I spend time exploring the intersections of management, creativity, art and technology. I have a lot of ideas and I make a lot of stuff: messaging apps, cryptocurrency hardware, virtual reality games and educational content. I teach students at NYU Shanghai with the goal of helping them understand the intersection of ideas and realities.
I'm a founding member of NYU Shanghai, China's first Sino-American university. I was on the ground floor putting in the plumbing, and was initially responsible for planning and operations to establish the school in Shanghai. Currently I'm teaching and researching full time, while continuing to build interesting products and art in my spare time.
My diverse skill set lends itself well to small, nimble teams. I pride myself on my ability to take risks to create new things. I work efficiently, play multiple roles and speak many languages (programming, business, Chinese). I know enough about most things to sound like an expert on technology, project management, software engineering, digital prototyping, corporate and venture finance, capital markets, macroeconomics and the Chinese innovation ecosystem.
# The Benefits and Costs of My Digital Life
In the first class, I mentioned that applications of the Internet improve lives and makes the world a better place, but we must work to improve the positive and mitigate or remove the negative impacts of a digital life.
* Give 3 specific examples of a positive change you’ve *personally* experienced as a result of an application of the Internet, be sure to specifically name the application (e.g., email, instant messaging, social media, etc…)
* Give 3 specific examples of a negative impact you’ve *personally* experienced as a result of an application of the Internet. For each example, indicate how you could mitigate the impact (make it less severe, or nonexistent).
|
PHP
|
UTF-8
| 1,849 | 2.890625 | 3 |
[] |
no_license
|
<?php
require_once 'Conexao.class.php';
class Produto
{
private $con;
function __construct()
{
$conexao = new Conexao();
$this->con = $conexao->getConexao();
}
//Insert novo produto
function insertProduto($sql)
{
if ($this->con->exec($sql)){
return true;
}
return false;
}
//Listas todos os produtos
function listarProdutos()
{
$lista = $this->con->query("SELECT * FROM produtos ORDER BY deprod");
if (count($lista) > 0) {
return $lista->fetchALL(PDO::FETCH_ASSOC);
}
return FALSE;
}
//Buscar produto por codigo
function buscaProduto($cod)
{
$busca = $this->con->query("SELECT * FROM produtos WHERE cdprod = '{$cod}'");
if (count($busca) > 0) {
return $busca->fetch(PDO::FETCH_ASSOC);
}
return false;
}
//Update info produto
function updateProduto($sql)
{
if ($this->con->exec($sql)){
return true;
}
return false;
}
//Delete produto
function deleteProduto($codigo)
{
if ($this->con->exec("DELETE FROM produtos WHERE cdprod = '{$codigo}'")) {
return TRUE;
}
return FALSE;
}
//Busca total produto estoque
function estoqueProduto($codigo)
{
$busca = $this->con->query("SELECT qtprod FROM produtos WHERE cdprod = '{$codigo}'");
if (count($busca) > 0) {
return $busca->fetch(PDO::FETCH_COLUMN);
}
return false;
}
//Update produto estoque
function atualizaEstoque($codigo, $qtd)
{
if ($this->con->exec("UPDATE produtos SET qtprod = '{$qtd}' WHERE cdprod = '{$codigo}'")) {
return TRUE;
}
return FALSE;
}
}
|
Python
|
UTF-8
| 178 | 3.34375 | 3 |
[] |
no_license
|
a=int(input("ingres el numero:"))
b=int(input("ingres el otro numero:"))
c=a+b
if a<b:
print(a**b)
elif a>b:
print(a//b)
print(c)
print(a*b)
print(a/b)
#hola
#holax2
#holax3
|
Swift
|
UTF-8
| 6,270 | 2.578125 | 3 |
[] |
no_license
|
//
// SavedRecipesViewController.swift
// Yes Chef
//
// Created by Adam Larsen on 2016/02/02.
// Copyright © 2016 Conversant Labs. All rights reserved.
//
import UIKit
class SavedRecipesViewController: UITableViewController, UISearchResultsUpdating, SavedRecipesConversationTopicEventHandler
{
var selectionBlock: (Recipe -> ())?
var savedRecipesConversationTopic: SavedRecipesConversationTopic!
// MARK: Lifecycle
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.savedRecipesConversationTopic = SavedRecipesConversationTopic(eventHandler: self)
}
override func viewDidLoad()
{
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
savedRecipes = SavedRecipesManager.sharedManager.loadSavedRecipes()
tableView.tableHeaderView = searchController?.searchBar
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
savedRecipesConversationTopic.topicDidGainFocus()
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewWillDisappear(animated: Bool)
{
savedRecipesConversationTopic.topicDidLoseFocus()
super.viewWillDisappear(animated)
}
deinit {
searchController?.view.removeFromSuperview() // Required to avoid warning when dismissing this VC: "Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior"
}
// MARK: ListConversationTopicEventHandler Protocol Methods
func selectedRecipe(recipe: Recipe?)
{
if let selectedRecipe = recipe {
selectionBlock?(selectedRecipe)
}
else {
// TODO: Visual feedback?
print("SavedRecipesVC selectedRecipe, no recipe could be selected.")
}
}
func handlePlayCommand()
{
print("SavedRecipesVC handlePlayCommand")
// TODO: Interact with the command bar playback controls - change middle button to Pause
}
func handlePauseCommand()
{
print("SavedRecipesVC handlePauseCommand")
// TODO: Interact with the command bar playback controls - change middle button to Play
}
func beganSpeakingItemAtIndex(index: Int)
{
tableView?.selectRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), animated: true, scrollPosition: UITableViewScrollPosition.Middle)
}
func finishedSpeakingItemAtIndex(index: Int)
{
tableView?.deselectRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), animated: true)
}
// MARK: SavedRecipesConversationTopicEventHandler Protocol Methods
func requestedRemoveItemWithName(name: String?, index: Int)
{
print("SavedRecipesVC handleRemoveRecipeCommand")
// TODO: Interact with Saved Recipes manager
}
// MARK: UISearchResultsUpdating Protocol Methods
func updateSearchResultsForSearchController(searchController: UISearchController)
{
// TODO
}
// MARK: UITableViewDelegate Protocol Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let index = indexPath.row
if index < savedRecipes.count {
selectionBlock?(savedRecipes[index])
}
}
// MARK: UITableViewDataSource Protocol Methods
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let index = indexPath.row
if
let cell = tableView.dequeueReusableCellWithIdentifier("RecipeCell") as? RecipeCell
where index < savedRecipes.count
{
let recipe = savedRecipes[index]
cell.recipeNameLabel.text = recipe.name
cell.thumbnailImageView.af_setImageWithURL(recipe.heroImageURL, placeholderImage: Utils.placeholderImage())
let ratingLabels = Utils.getLabelsForRating(recipe.presentableRating)
cell.ratingLabel.text = ratingLabels.textLabel
cell.ratingLabel.accessibilityLabel = ratingLabels.accessibilityLabel
cell.itemNumberLabel.text = "\(index + 1)." // Convert 0-based index to 1-based item number.
return cell
}
else {
return UITableViewCell()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return savedRecipes.count
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
// MARK: Helpers
private var savedRecipes: [Recipe]! {
didSet {
// Keeps savedRecipesCT's recipes in sync with savedRecipesVC's recipes.
savedRecipesConversationTopic.updateSavedRecipes(savedRecipes)
}
}
private var searchController: UISearchController?
}
class RecipeCell: UITableViewCell
{
@IBOutlet weak var recipeNameLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var itemNumberLabel: UILabel!
@IBOutlet weak var courseLabel: UILabel!
@IBOutlet weak var backdropView: UIView!
override func setHighlighted(highlighted: Bool, animated: Bool)
{
// Workaround for bug (feature?) that sets any subviews' backgroundColor to (0,0,0,0) when its parent cell is selected.
let backgroundColor = backdropView.backgroundColor
super.setHighlighted(highlighted, animated: animated)
backdropView.backgroundColor = backgroundColor
}
override func setSelected(selected: Bool, animated: Bool)
{
// Workaround for bug (feature?) that sets any subviews' backgroundColor to (0,0,0,0) when its parent cell is selected.
let backgroundColor = backdropView.backgroundColor
super.setSelected(selected, animated: animated)
backdropView.backgroundColor = backgroundColor
}
}
|
Python
|
UTF-8
| 512 | 4.125 | 4 |
[] |
no_license
|
def cumulative_sum(numlist):
""""
Takes a list of numbers and sums each element cumulatively and shows the result of each sums'
numlist: Must be a list of numbers; No nesting allowed
Returns a new list with each element being the cumulative sum of the previous elements of the original list
"""
incrementor=0
cumulList=[]
for eachNum in numlist:
newTerm=incrementor + eachNum
cumulList.append(newTerm)
incrementor=newTerm
return cumulList
numlist=[1,5,8,7,9,6]
print cumulative_sum(numlist)
|
Python
|
UTF-8
| 1,496 | 2.625 | 3 |
[] |
no_license
|
import numpy as np
from PIL import ImageGrab
import cv2
import time
from SimulateKeypress import PressKey, ReleaseKey, W, A, S, D
# import pyautogui
def RegionOfInterest(img, vertices):
mask = np.zeros_like(img)
cv2.fillPoly(mask, vertices, 255)
masked = cv2.bitwise_and(img, mask)
return masked
# def DrawLines(img, roadLine):
# try:
# for line in roadLine:
# except:
def ProcessImg(OriginalImg):
ProcessedImg = cv2.cvtColor(OriginalImg, cv2.COLOR_BGR2GRAY)
ProcessedImg = cv2.Canny(ProcessedImg, threshold1=200, threshold2=300)
ProcessedImg = cv2.GaussianBlur(ProcessedImg, (5,5), 0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500]])
ProcessedImg = RegionOfInterest(ProcessedImg,[vertices])
roadLine = cv2.HoughLinesP(ProcessedImg, 1, np.pi/180, 180, np.array([]), 100, 5)
#DrawLines(OriginalImg, roadLine)
return ProcessedImg
for i in range(3,0,-1):
print(i)
time.sleep(1)
i -= 1
while (True):
screen_img = np.array(ImageGrab.grab(bbox=(0,40,800,600)))
processed_screen_img = ProcessImg(screen_img)
# screen_numpy = np.array(screen_img.getdata(),dtype='uint8').reshape((screen_img.size[1],screen_img.size[0],3))
#ImgToShow = cv2.cvtColor(processed_screen_img, cv2.COLOR_BGR2RGB)
# print("down")
# PressKey(W)
# time.sleep(3)
# ReleaseKey(W)
# print("up")
# cv2.resizeWindow("window",800,600)
cv2.imshow('window',processed_screen_img)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
|
Markdown
|
UTF-8
| 3,060 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: grep command in Linux
bigimg: /img/image-header/road-to-solution.jpeg
tags: [Linux]
---
<br>
## Table of contents
- [Given problem](#given-problem)
- [Solution of grep command](#solution-of-grep-command)
- [Wrapping up](#wrapping-up)
<br>
## Given problem
In Linux, we usually have to search keyword in text, or file, or folders, or the result from the other commands. It is difficult to deal with it when we have to jump directly in these files or folders to check.
The drawbacks of this solution:
- It takes so much times to search.
- We do not automatically search our keywords that accepts input from the other sources.
So how do we solve these problems?
<br>
## Solution of grep command
1. Syntax
```
grep <options> <pattern> <file, folder>
```
With:
- pattern: It is used by regular expression.
- file, folder: The file or folder that we want to search in it.
2. Some options of **grep** command
Belows are the list of options that grep will use.
- ```-r``` or ```-R```: recursive
- ```-n```: display the line number that corresponding lines satisfy our pattern
- ```-w```: It means that match the whole word
- ```-l```: It can be added to just give the file name of matching files.
- ```-i```: case-insensitive search
- ```-v```: display the lines not containing the pattern.
- ```-c```: display the count of the matching pattern.
- ```-A```: display the n lines after the matching line.
For example:
```bash
grep -A 4 -i 'greeting' welcome.sh
```
- ```-B```: display the n lines before the matching line.
For example:
```bash
grep -B 3 'greeting' welcome.sh
```
- ```-C```: display the n lines around the matching line.
For example:
```bash
grep -C 3 'greeting' welcome.sh
```
- ```-o```: prints only the matched parts of a matching line.
For example:
```bash
echo "text with number -2.56325" | grep -Eo '[+-]?[0-9]+([.][0-9]+)?'
```
To use **-o** option correctly, we should utilize with **-E** option that means extended regex.
3. Some flags that accompany with **grep** command
- ```--exclude```: search all files that exclude these files that satisfy pattern in this flag.
For example:
```sh
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
```
- ```--include```: search all files that satisfy pattern in this flag.
For example:
```bash
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
```
- ```--exclude-dir```: For directories, it's possible to exclude one or more directories using the ```--exclude-dir``` parameter.
For example:
```
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
```
<br>
## Wrapping up
- Understanding about how to use, when to use grep command in Linux.
<br>
Thanks for your reading.
|
JavaScript
|
UTF-8
| 24,242 | 2.890625 | 3 |
[] |
no_license
|
TEXTWIDTH=80
MAXLINES=8
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false
}
return true
}
function jsNode(nm,o) {
this.name=nm;
this.parent={}
this.type='leaf';
this.visible=true // are you visible
//why should this structure hold visibility and not the page?
this.datatype=Object.prototype.toString.call(o)
// msg(this.name+" is a node of type "+this.datatype)
if ((this.datatype!="[object Object]") && (this.datatype!="[object Array]")) {
this.value=o
}
this.child=[]
}
jsNode.prototype = {
constructor: jsNode,
addChild:function (n) {
this.type="node"
this.child.push(n)
n.setParent(this)
return n
},
setParent:function (n) {
this.parent=n
},
setVisibility:function(vis,propogate) {
this.visible=vis
if (propogate) {
for (var i in this.child) {
this.child[i].setVisibility(vis,propogate)
}
}
},
showChildren:function() {
var children=[]
// alert(children)
for (var i in this.child){
// alert(this.child[i].name)
children.push(this.child[i].name)
}
alert(children)
},
moveChild:function(i,dir) {
// msg("asked to move child "+i+" by "+dir)
var tmp=this.child[i]
var trgt=i+dir
if ((trgt>=0) && (trgt<this.child.length)) {
this.child[i]=this.child[trgt]
this.child[trgt]=tmp
}
},
toString: function() {
return "Tree Object:"+this.name
},
toEditor: function(id) {
function setUpRowLabels(id,node) {
var d="<tr>"
if (node.type!="leaf") {
d=d+"<td>";
d=d+"<div id='col1' style='margin-left:"+String(level*10)+"'>"
if (node.datatype=="[object Array]") { //non-arrays with the newFromTemplate also needs to be accomodated.
if (node.feature) {
if (node.feature.type=="newFromTemplate") {
// msg("Setting up feature "+node.feature.type)
d=d+"<button id='"+id+"' onClick='insertFromTemplate(id)'>*</button>"
}
}
else {
d=d+"<button id='"+id+"' onClick='duplicateAChild(id)'>*</button>"
}
}
if (node.visible) {
d=d+"<button id='"+id+"' onClick='expandOrContractElement(id,-1,false)'>-</button>"
}
else {
d=d+"<button id='"+id+"' onClick='expandOrContractElement(id,1,false)'>+</button>"
}
d=d+"<b> "+node.name+"</b>"
d=d+"</div>"
d=d+"</td>";
}
else { // not too sure if this code gets executed
d=d+"<td>";
d=d+"<div id='col1' style='margin-left:"+String(level*10)+"'>"
if ((node.parent.datatype=="[object Array]")&&(node.parent.child.length>1)) {
d=d+"<button id='"+id+"' onClick='deleteItem(id)'>1Up</button>"
d=d+"<button id='"+id+"' onClick='deleteItem(id)'>Down</button>"
d=d+"<button id='"+id+"' onClick='deleteItem(id)'>Del</button>"
}
if (node.feature) {
if (node.feature.type=="newFromTemplate") {
// msg("Setting up feature "+node.feature.type)
d=d+"<button id='"+id+"' onClick='insertFromTemplate(id)'>*</button>"
}
}
d=d+node.name;
d=d+"</div>"
d=d+"</td>";
}
// msg(d)
return d
}
var d="" // setUpRowLabels(id)
var level=eval("["+id.replace(/_/g,",")+"].length")
if (this.parent.datatype=="[object Array]") {
var ka=eval("["+id.replace(/_/g,",")+"]")
this.name=String(ka[ka.length-1])
}
// msg("test here for global template for "+this.name) //if a global exists set it as a template on the node?
if (this.feature) {
// msg(this.name+" has feature of "+this.feature.type)
switch(this.feature.type)
{
case "newFromTemplate": {
// msg("New from template installed")
d=setUpRowLabels(id,this)
break
}
case "invisible": {
// d=d+"<input class='jsForm_input' size="+l+" onchange='readForm()' id='"+id+"' value='"+value+"'>"+"</input>";
break
}
case "textarea": {
d=setUpRowLabels(id,this)
d=d+"<td><div id='col2'style='margin-left:"+String(level*10)+"'><textarea class='jsForm_input' onchange='readForm()' id='"+id+"' cols='"+TEXTWIDTH+"' rows='"+this.feature.parameters.rows+"'>"+this.value+"</textarea>"
break
}
case "checkboxes": {
d=setUpRowLabels(id,this)
for (i in this.feature.parameter.options) {
// msg(o.feature.parameter.options[i])
d=d+"<td><div id='col2'style='margin-left:"+String(level*10)+"'><input type='checkbox' class='jsForm_input' onchange='readForm()' id='"+id+"' value='"+this.feature.parameter.options[i]+"'>"+this.feature.parameter.options[i]+"</input></br>"
}
break
}
case "select": {
d=setUpRowLabels(id,this)
d=d+"<td><div id='col2'style='margin-left:"+String(level*10)+"'><select class='jsForm_select' onChange='readForm()' id='"+id+"'>"
for (i in this.feature.parameters.selection) {
if (this.value==this.feature.parameters.selection[i]) {
var selctd=" SELECTED"
}
else {
var selctd=""
}
d=d+"<option value='"+this.feature.parameters.selection[i]+"'"+selctd+">"+this.feature.parameters.selection[i]+"</option>"
}
d=d+"</select>"
break
}
}
}
else {
// msg(this.name+" is naturale and is a "+this.datatype)
// d=setUpRowLabels(id,this)
// msg("before crash:"+this.type+":"+this.datatype)
d="<tr>"
if (this.type!="leaf") {
d=d+"<td>";
d=d+"<div id='col1' style='margin-left:"+String(level*10)+"'>"
// a stub '!leaf' has no children
if ((this.parent.datatype=="[object Array]")&&(this.parent.child.length>1)) { //is this the only place where this operates?
d=d+"<button id='"+id+"' onClick='moveElement(id,-1)'>\u2191</button>" //Up
d=d+"<button id='"+id+"' onClick='moveElement(id,1)'>\u2193</button>" // Down
d=d+"<button id='"+id+"' onClick='deleteItem(id)'>x</button>"
// d=d+"<button id='"+id+"' onClick='deleteItem(id)'>x</button>"
}
// msg("after crash")
if (this.datatype=="[object Array]") {
d=d+"<button id='"+id+"' onClick='duplicateAChild(id)'>*</button>"
}
if (this.visible) {
d=d+"<button id='"+id+"' onClick='expandOrContractElement(id,-1,false)'>-</button>"
}
else {
d=d+"<button id='"+id+"' onClick='expandOrContractElement(id,1,false)'>+</button>"
}
d=d+"<b> "+this.name+"</b>"
d=d+"</div>"
d=d+"</td>";
}
else {
d=d+"<td>";
d=d+"<div id='col1' style='margin-left:"+String(level*10)+"'>"
// a stub 'leaf' has no children
// msg("Children?"+(isEmpty(this.child)))
if (!isEmpty(this.child)) {
if ((this.parent.datatype=="[object Array]")&&(this.parent.child.length>1)) {
d=d+"<button id='"+id+"' onClick='moveElement(id,-1)'>\u2191</button>" //Up
d=d+"<button id='"+id+"' onClick='moveElement(id,1)'>\u2193</button>" // Down
d=d+"<button id='"+id+"' onClick='deleteItem(id)'>x</button>"
}
}
// msg("here "+this.name+this.value.length)
d=d+this.name;
d=d+"</div>"
d=d+"</td>";
if (this.value) {
d=d+"<td>";
d=d+"<div id='col2'style='margin-left:"+String(level*10)+"'>"
var l=Math.round(this.value.length*1.5)
// alert(l)
// msg("Displaying "+this.value+":"+this.value.replace(/'/g,"'"))
if(this.value.length>TEXTWIDTH) { // neeed to investigate escaping this.value
r=Math.round(this.value.length/TEXTWIDTH)+2
// msg(value.length+":"+r)
d=d+"<textarea class='jsForm_input' onchange='readForm()' id='"+id+"' cols='"+TEXTWIDTH+"' rows='"+r+"'>"+this.value.replace(/'/g,"'")+"</textarea>"
}
else {
d=d+"<input class='jsForm_input' size="+l+" onchange='readForm()' id='"+id+"' value='"+this.value.replace(/'/g,"'")+"'>"+"</input>";
}
}
else {
d=d+"<td>";
d=d+"<div id='col2'style='margin-left:"+String(level*10)+"'>"
d=d+"<input class='jsForm_input' size="+l+" onchange='readForm()' id='"+id+"' value='"+this.value+"'>"+"</input>";
}
}
}
// msg(d)
return d+"</div></td></tr>"
}
}
function treeWalker(t,func,trail,mode) {
// msg("trail="+trail)
var trl=trail
for (var i in t.child) {
// trail=trl+"_"+String(i)
trail=trl+"_"+String(i)
// alert(trail)
if (t.child[i].type!="leaf") {
//the function paramters will have to be refined eventually
func(t.child[i],trail,mode)
if(t.child[i].datatype=="[object Array]") {
// j[t.child[i].name]=[]
}
else {
// j[t.child[i].name]={}
}
// if any child is invisible don't carry on??
if (t.child[i].visible) {
// msg("trail2="+trail)
treeWalker(t.child[i],func,trail,mode)
}
}
else {
func(t.child[i],trail,mode)
// j[t.child[i].name]=t.child[i].value
}
}
}
function tree2JS(t,j) {
// msg("In tree2js with "+t.name+":"+t.datatype)
for (var i in t.child) {
if (t.child[i].type!="leaf") {
// msg("processing non-leaf: "+t.child[i].name+":"+t.child[i].datatype)
// if (typeof(t.child[i].type!='leaf')) {
if(t.child[i].datatype=="[object Array]") {
j[t.child[i].name]=[]
}
else {
j[t.child[i].name]={}
}
tree2JS(t.child[i],j[t.child[i].name])
// alert(JSON.stringify(j))
}
else {
// alert(t.name)
// msg("processing leaf: "+t.child[i].name+":"+t.child[i].datatype)
j[t.child[i].name]=t.child[i].value
// alert(JSON.stringify(j))
}
}
}
function tree2Tree(ts,tt) {
// msg("Cloning children of:"+ts.name)
for (var i in ts.child) {
if ((ts.child[i].datatype!="[object Object]") && (ts.child[i].datatype!="[object Array]")) {
last=tt.addChild(new jsNode(ts.child[i].name,"")) //clone to empty
}
else {
last=tt.addChild(new jsNode(ts.child[i].name,new Object()))
}
last.datatype=ts.child[i].datatype
if (ts.child[i].type!="leaf") {
tree2Tree(ts.child[i],last)
}
// else {
// msg("Cloning node with name:"+ts.child[i].name)
// }
}
}
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
function js2Tree(t,o) { //this is only ever called when there is an object
// msg("In js2tree "+t.name+":"+t.type+":"+typeof(o))
t.type="node"
// alert("so far "+JSON.stringify(t))
// msg("building tree from js "+JSON.stringify(o))
for (var i in o) {
// msg("js2tree children "+Object.prototype.toString.call(o[i])+":"+i+":"+o[i]+":"+typeof(o[i]))
var last=t.addChild(new jsNode(i,o[i]));
// msg("here+"+last+typeof(o[i]))
// msg(JSON.stringify(last))
if (typeof(o[i])=="object") {
// alert("down the rabbit hole")
//going one step down in the object tree!!
js2Tree(last,o[i]);
}
}
}
function showNode(n) {
alert(n.name)
}
function traverse(o,func) {
func.apply(this,o);
for (var i in o) {
if (typeof(o[i])=="object") {
//going one step down in the object tree!!
traverse(o[i],func);
}
}
}
function msg(txt){
// var m=$(".Message").html()
// if (m) {
// $(".message").append(txt+"<br>"+m)
// }
// else {
$(".message").append(txt+"<br>")
// }
}
function addElement(){
document.getElementById("jsBuild").innerHTML="<input id='elName'></input><button onclick='saveElement()'>add</button>"
}
function moveEl(el,dir){
readForm()
var i=js[el]
alert(i)
alert("moving "+el+" "+dir)
}
function moveElementOld(el,dir) {
ndx=eval("["+el+"]")
pndx=ndx.slice(0,(ndx.length-1))
var p=tr
for (i=1;i<pndx.length;i++) {
p=p.child[pndx[i]]
}
// p.showChildren()
// alert(String(pndx))
trgt=new Number(ndx.slice(-1))
// alert(typeof(trgt))
// alert(trgt)
// alert('p is')
// alert(JSON.stringify(p))
if ((trgt>0) && (dir==-1)) {
// alert("up")
tmp=p.child[trgt-1]
// alert(tmp.name)
p.child[trgt-1]=p.child[trgt]
p.child[trgt]=tmp
// alert("up and out")
}
// alert(trgt<p.child.length-1)
if ((trgt<p.child.length-1) && (dir==1)) {
// alert("down")
// alert(p.child.length)
// alert(trgt+1)
// alert(typeof(trgt+1))
// alert(JSON.stringify(p.child[trgt+1]))
tmp=p.child[trgt+1]
// alert(tmp.name)
p.child[trgt+1]=p.child[trgt]
p.child[trgt]=tmp
// alert("down and out")
}
// alert(JSON.stringify(p))
if (features) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","edit")
}
function expandOrContractElement(id,dir,prop) {
ndx=eval("["+id.replace(/_/g,",")+"]")
var p=tr
for (i=1;i<ndx.length;i++) {
p=p.child[ndx[i]]
}
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
p.setVisibility((dir==1),prop)
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
// $("jsForm").html("</table>")
}
function moveElement(id,dir) {
ndx=eval("["+id.replace(/_/g,",")+"]")
var p=tr
for (i=1;i<ndx.length;i++) {
p=p.child[ndx[i]]
}
p.parent.moveChild(parseInt(ndx.slice(-1)),dir)
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
// p.setVisibility((dir==1),prop)
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
// $("jsForm").html("</table>")
}
function extractTemplate() {
alert("in extract template")
j=JSON.stringify(tr)
msg(j)
request=$.ajax({
url:"couch",
type:"post",
data:{
docbase:"dictionary",
"_id":"template",
json:j
},
success:function(data) {
// alert('page content: ' + JSON.stringify(data))
alert("Template extracted")
tr=new jsNode("root",{})
js2Tree(tr,js)
if (features) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
tr.setVisibility(false,true)
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
},
error:function(data) {
s=JSON.parse(data["responseText"])
alert("Failure "+JSON.stringify(s.reason))
js=JSON.parse(jsBefore)
resetForm() //consiider setting a paramter on reetForm to be resetForm with ...
}
})
}
function deepCopy(source) {
alert("attempting deep copy of:"+JSON.stringify(source))
target=JSON.parse(JSON.stringify(source))
/*
for (s in source) {
alert(s+":"+JSON.stringify(source[s]))
target[s]=JSON.stringify(source[s])
}
*/
// alert(JSON.stringify(target))
return target
}
function duplicateAChild(id) { //allow a child to be created via a structure attached to a feature.
// msg("in the child factory")
ndx=eval("["+id.replace(/_/g,",")+"]")
var p=tr
for (i=1;i<ndx.length;i++) {
p=p.child[ndx[i]]
}
// msg("testing for child length "+p.child[0].child.length)
if (p.child[0].child.length>0) {
jstub={}
tree2JS(p.child[0],jstub)
var jj=new jsNode(String(p.child.length),{})
tree2Tree(p.child[0],jj)
// msg(JSON.stringify(p.child[0]))
// msg(jj.name+jj.child[0].name+jj.child[0].value)
p.child.push(jj)
jj.setParent(p)
}
else {
// msg("Attempting to clone simple array member as"+JSON.stringify(p.child[0]))
jj=new jsNode(String(p.child.length),{})
jj.value="" //need something to base the field on
jj.datatype=p.child[0].datatype
// tree2Tree(p.child[0],jj)
// msg(JSON.stringify(p.child[0]))
// msg(JSON.stringify(jj))
p.child.push(jj)
jj.setParent(p)
}
// alert(JSON.stringify(p.child[0]))
// need deep copy at node level here
/*
p.child.push(deepCopy(p.child[0]))
p.child[p.child.length-1].name=String(p.child.length-1)
p.child[p.child.length-1].value=""
p.visible=true
tree2JS(tr,js)
alert(JSON.stringify(js))
tr=new Node("root",{})
js2Tree(tr,js)
// alert(JSON.stringify(p.child[p.child.length-1]))
*/
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
// $("jsForm").html("</table>")
// alert(JSON.stringify(p.child[p.child.length-1]))
}
function insertFromTemplate(id) { //allow a child to be created via a structure attached to a feature.
// msg("inserting template")
ndx=eval("["+id.replace(/_/g,",")+"]")
var p=tr
var jj=new jsNode("template",{})
for (i=1;i<ndx.length;i++) {
p=p.child[ndx[i]]
}
// msg(JSON.stringify(p.feature.parameters.template))
js2Tree(jj,p.feature.parameters.template)
// msg(jj)
p.child.push(jj)
jj.setParent(p)
p.type="node"
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
}
function deleteItem(id) {
// msg("In delete item: "+id)
ndx=eval("["+id.replace(/_/g,",")+"]")
var p=tr
for (i=1;i<ndx.length;i++) {
p=p.child[ndx[i]]
}
// msg("...with name:"+p.name+" and parent:"+p.parent.name+p.parent.datatype)
// msg(Number(p.name)+"of"+p.parent.child.length)
p.parent.child.splice(Number(p.name),1)
// resetForm()
// readForm()
// msg(p.parent.child.length)
// msg(JSON.stringify(tr))
// tree2JS(tr,k)
// msg(JSON.stringify(k))
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
// msg("out")
}
function buildForm(o,id,mode) {
// msg("Building form:"+id)
if(o.jsForm) {
o.jsForm()
}
// test o.toEditor()
var d=o.toEditor(id,o.visible)
// alert(d);
$(".jsForm").append(d);
// msg(escape(d))
// document.write(d)
// console.log(d)
// console.log("---") //used to be .html
}
function saveElement(){
$("jsForm").html("")
eval("js['"+document.getElementById("elName").value+"']=''")
traverse(js,buildForm,"root")
document.getElementById("jsForm").innerHTML=document.getElementById("jsForm").innerHTML+"<button onclick=readForm()>submit</button>"
document.getElementById("elName").value=""
// alert(JSON.stringify(js))
}
function resetForm() {
tr=new jsNode("root",{})
js2Tree(tr,js)
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
tr.setVisibility(false,true)
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
}
function saveForm(docbase) {
// msg("save clicked")
var jsBefore=JSON.stringify(js) //A trick for getting a deep copy?
alert(js["_id"]+"("+js["_rev"]+")")
tree2JS(tr,js)
j=JSON.stringify(js)
// msg("Saving:"+j)
/*
tr=new jsNode("root",{})
js2Tree(tr,js)
tr.setVisibility(false,true)
document.getElementById("jsForm").innerHTML=""
treeWalker(tr,buildForm,"0","normal")
*/
// msg(document.URL.split('/').slice(3)[1])
request=$.ajax({
url:"/couch/"+docbase+"/"+js["_id"],
type:"put",
data:{json:j},
success:function(data) {
// alert('page content: ' + JSON.stringify(data))
// msg("Updated "+JSON.stringify(data))
alert("Updated "+JSON.stringify(data))
js["_rev"]=data["rev"]
tr=new jsNode("root",{})
js2Tree(tr,js)
//need to reset all features
tr.setVisibility(false,true)
// msg("known features "+(features.length==0))
if (features.length>0) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
// msg("Walking the tree")
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","normal")
},
error:function(data) {
s=JSON.parse(data["responseText"])
alert("Failure "+JSON.stringify(s.reason))
js=JSON.parse(jsBefore)
resetForm() //consiider setting a paramter on reetForm to be resetForm with ...
}
});
// alert("back")
}
function saveFormAs(docbase) {
// msg("save clicked")
var jsBefore=JSON.stringify(js) //A trick for getting a deep copy?
// alert(jsBefore)
var _id=prompt("Enter _id for document","Automatically assigned")
if (_id) {
tree2JS(tr,js)
if (_id=="Automatically assigned") {
delete js["_id"]
}
else {
js["_id"]=_id
}
delete(js["_rev"])
j=JSON.stringify(js)
request=$.ajax({
url:"/couch/"+docbase,
type:"post",
data:{json:j},
success:function(data) {
// alert('page content: ' + JSON.stringify(data))
alert("Created "+JSON.stringify(data["id"]))
window.location.href=data["id"];
},
error:function(data) {
s=JSON.parse(data["responseText"])
alert("Failure "+JSON.stringify(s.reason))
js=JSON.parse(jsBefore)
resetForm() //consiider setting a paramter on reetForm to be resetForm with ...
}
});
}
// alert("back")
}
function saveNewRule(rb) {
// msg("save clicked")
var jsBefore=JSON.stringify(js) //A trick for getting a deep copy?
// alert(jsBefore)
tree2JS(tr,js)
delete(js["_rev"])
j=JSON.stringify(js)
request=$.ajax({
url:"/couch/"+rb,
type:"post",
data:{json:j},
success:function(data) {
// alert('page content: ' + JSON.stringify(data))
alert("Updated "+JSON.stringify(data["rev"]))
window.location.href=data["id"];
},
error:function(data) {
s=JSON.parse(data["responseText"])
alert("Failure "+JSON.stringify(s.reason))
js=JSON.parse(jsBefore)
resetForm() //consiider setting a paramter on reetForm to be resetForm with ...
}
});
// alert("back")
}
function deleteForm(docbase,returnTo) {
tree2JS(tr,js)
j=JSON.stringify(js)
alert("Ready to delete:"+JSON.stringify(j))
request=$.ajax({
url:"/couch/"+docbase+"/"+js["_id"],
type:"delete",
data:{json:j},
success:function(data) {
// alert('page content: ' + JSON.stringify(data))
alert("Deleted "+JSON.stringify(data))
window.location.assign(returnTo)
},
error:function(data) {
s=JSON.parse(data["responseText"])
alert("Failure "+JSON.stringify(s.reason))
js=JSON.parse(jsBefore)
resetForm() //consiider setting a paramter on reetForm to be resetForm with ...
}
});
// alert("back")
}
function readForm(){
// msg("In readForm")
var allIn = $('.jsForm_input');
for(var k=0;k<allIn.length;k++){
ndx=eval("["+allIn[k].id.replace(/_/g,",")+"]")
var p=tr
// msg(p.child[1].name)
for (i=1;i<ndx.length;i++) {
// msg("moving through readForm"+ndx.length)
p=p.child[ndx[i]]
}
// msg(allIn[k].value)
p.value=allIn[k].value.trim()
}
// for each feature type - textarea works ok as a general input field
var allIn = $('.jsForm_select');
for(var k=0;k<allIn.length;k++){
// msg("Going after select fields:"+k+":"+allIn[k].id)
ndx=eval("["+allIn[k].id.replace(/_/g,",")+"]")
var p=tr
// msg(p.child[1].name)
for (i=1;i<ndx.length;i++) {
// msg("moving through readForm"+ndx.length)
p=p.child[ndx[i]]
}
// msg(allIn[k].id)
p.value=$("#"+allIn[k].id +" :selected").text().trim()
// msg("Assigned:"+p.value)
}
// msg("finished readForm")
// test if save clicked !!!!!!!!!!!!!!! Still to be done
}
function fact(i) {
if (i==1) {return 1}
else {
v=i*fact(i-1)
return v
}
}
function switch2Edit() {
if (features) {
jsFeatureInstall(tr,features,[])
// installFeatures(features,tr)
}
$(".jsForm").empty()
treeWalker(tr,buildForm,"0","edit")
}
//alert("js2tree loaded")
function jsPathWalker(t,func,k) {
// msg("jsPathWalker"+JSON.stringify(k))
// msg("In jsPathWalker:"+t.name+k.length+k[0]+":")
k=k.slice(1,k.length)
if ((k.length==0)) { //k is empty
// msg("good finish:"+t.name)
return t
}
else {
for (i in t.child) {
r=false
found=false
msg("attempting:"+k[0]+":"+t.child[i].name)
if ((t.child[i].name==k[0]) || (k[0]=="*")) {
// alert("i have found a match")
found=true
// msg(t.child[i].name+":"+k)
r=jsPathWalker(t.child[i],func,k)
// msg(found+"children"+r.name)
// found=found&&r
// return found
return r
}
// jsPathWalker(t.child[i],func,kk)
}
}
if (k.length>0) {
// msg("suspected fail")
return false
}
else {
// msg("out jsPathWalker"+":"+found+k)
return found
}
}
/*
if ((t.name==k[0])&&(k.length>0)) {
msg("In jsPathWalker starting @"+t.name+"?"+k[0]+":"+k.length)
for (i in t.child) { //look ahead to match child
msg(t.child[i].name+":"+kk[0])
else
{
return t.child[i].name
}
}
}
else {
msg("FAIL"+k.length)
}
for (var i in t.child) {
// msg(t.child[i].name+"="+k+"?"+(t.child[i].name in k))
// msg(t.child[i].name+t.child[i].type)
if (t.child[i].type!="leaf") {
func(t.child[i].name)
if(t.child[i].datatype=="[object Array]") {
// j[t.child[i].name]=[]
}
else {
// j[t.child[i].name]={}
}
jsPathWalker(t.child[i],func,kk)
}
else {
// msg("calling func for leaf")
func(t.child[i].name)
// j[t.child[i].name]=t.child[i].value
}
}
*/
// msg("End treeWalker")
function jsFromPath(jsPath,t) {
k=jsPath.split(".")
// msg("ready to walk")
ans=jsPathWalker(t,function() {},k)
return ans
}
|
Ruby
|
UTF-8
| 2,233 | 2.546875 | 3 |
[] |
no_license
|
require 'serialport'
require 'eventmachine'
require 'em-websocket'
require 'filewatch/tail'
require 'childprocess'
# Serial Port connection
begin
# @@sp = SerialPort.new("/dev/master", 9600, 8, 1, SerialPort::NONE)
rescue => e
STDERR.puts 'cannot open serial port!'
STDERR.puts e.to_s
exit 1
end
@@recvs = Array.new
@@channel = EM::Channel.new
@@channel.subscribe do |data|
now = Time.now.to_i*1000+(Time.now.usec/1000.0).round
@@recvs.unshift({:time => now, :data => data})
while @@recvs > 100
@@recvs.pop
end
end
class SerialSocketServer < EM::Connection
def post_init
@sid = @@channel.subscribe do |data|
send_data "#{data}\n"
end
puts "* new socket client <#{@sid}>"
def receive_data data
data = data.to_s.strip
return if data.size < 1
puts "* socket client <#{@sid}> : #{data}"
@@sp.puts data
end
def unbind
@@channel.unsubscribe @sid
puts "* socket client <#{@sid}> closed"
end
end
end
EM.run {
# Serial Port TCP Socket
# EM::start_server('0.0.0.0', 8785, SerialSocketServer)
# puts "* serial port TCP socket server start - port 8785"
# WebSocket Server
EM::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen do
sid = @@channel.subscribe{|msg| ws.send msg }
puts "* new WebSocket client <#{sid}> connected!"
# Messages received from client
# Used to manage process restart and logging
# Messages sent from client will have the following format:
# class name, action to perform ex.
# Gps start
ws.onmessage do |msg|
puts "* websocket client <#{@sid}> : #{msg}"
action_data = msg.split(',')
# @@sp.puts mes.strip
#app_object = Object.const_set(action_data[0], Class.new)
#app_object.send(action_data[1])
end
ws.onclose do
@@channel.unsubscribe(sid)
puts "* websocket client <#{@sid}> closed"
end
end
end
puts "* websocket server start - port 8080"
tail = FileWatch::Tail.new(:stat_interval => 0.2)
tail.tail("C:\\Tommaso\\mitadashboard\\tom")
tail.subscribe do | path, data |
@@channel.push data.tr('"', '')
puts data.tr('"', '')
end
}
|
JavaScript
|
UTF-8
| 689 | 3.40625 | 3 |
[] |
no_license
|
$(document).ready(function(){
// take the information from the search input
let images = document.getElementsByTagName('a');
// get the text that the user has typed
//use toLowerCase incase the user uses upper case
$('.search_box').on('keyup',function(){
let search = $('.searchInput').val().toLowerCase();
//use a loop to get a particular attribute
for (var i=0; i<images.length; i++) {
let searchVal= images[i].getAttribute('data-title');
// use of a conditional to look for a particular condition.
if (searchVal.toLowerCase().indexOf(search)> -1) {
images[i].style.display="";
} else {
images[i].style.display="none";
}
}
});
});
|
Java
|
UTF-8
| 2,233 | 3.375 | 3 |
[] |
no_license
|
import java.util.Date;
import java.util.Objects;
public abstract class Bike implements Movable {
protected String color;
protected String nameOfTheOwner;
protected Brand brand;
protected int numberOfSpeeds;
protected boolean moving;
protected Date dayOfRelease;
public Bike() {
}
public Bike(String color, String nameOfTheOwner, Brand brand, int numberOfSpeeds, boolean moving, Date dayOfRelease) {
this.color = color;
this.nameOfTheOwner = nameOfTheOwner;
this.brand = brand;
this.numberOfSpeeds = numberOfSpeeds;
this.moving = moving;
this.dayOfRelease = dayOfRelease;
}
abstract void methodOfDriving();
void stopMoving(int i) {
switch (i) {
case 1 -> System.out.println("Bike тормозит задним колесом");
case 2 -> System.out.println("Bike тормозит передним колесом");
case 3 -> System.out.println("Bike тормозит обоими колесами");
default -> System.out.println("Выбирите один из один из трех вариантов : 1,2 или 3");
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bike bike = (Bike) o;
return numberOfSpeeds == bike.numberOfSpeeds && moving == bike.moving && Objects.equals(color, bike.color) && Objects.equals(nameOfTheOwner, bike.nameOfTheOwner) && brand == bike.brand;
}
@Override
public int hashCode() {
return Objects.hash(color, nameOfTheOwner, brand, numberOfSpeeds, moving);
}
@Override
public String toString() {
StringBuilder stringBuilder;
stringBuilder = new StringBuilder("Bike{");
stringBuilder.append("color='").append(color).append('\'').append(", nameOfTheOwner='").append(nameOfTheOwner).append('\'').append(", brand=").append(brand).append(", numberOfSpeeds=").append(numberOfSpeeds).append(", moving=").append(moving).append(", dayOfRelease=").append(dayOfRelease).append('}');
System.out.println(stringBuilder);
return "";
}
}
|
Java
|
UTF-8
| 8,225 | 2.875 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import static java.lang.Thread.sleep;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.swing.JFrame;
/**
*
* @author usuario
*/
public class Main1 extends JFrame{
private Ball ball = new Ball();
private Ship ship;
private Image imageDB;
private Graphics graphDB;
private ArrayList<ArrayList<Block>> blockList;
public static void main(String args[]) {
Main1 m = new Main1();
m.init();
}
public void init() {
this.setTitle("ARKANOID");
this.setSize(600, 600);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e){
super.keyPressed(e);
ship.addMove(e);
}
});
imageDB = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
graphDB = imageDB.getGraphics();
run();
}
public void paint(Graphics g){
g.drawImage(imageDB,0,0,this);
}
public void run() {
try{
ball = new Ball(10, 500, 500,-1,-1,Color.CYAN);
ship = new Ship(100, 500, 120, 20, Color.red);
blockList = new ArrayList<ArrayList<Block>>();
fillBockList();
blockListUpdatepoints();
while(true){
try {
System.out.println("\n");
graphDB.clearRect(0, 0, getWidth(), getHeight());
//CRASHES
borderCrash();
ship.shipCrash(ball);
blockListCrashes();
blockListKill();
ball.wayCalculator();
ship.move();
ship.updateGuns();
ship.paintAllGuns(graphDB);
ship.updatePoints();//save ship points
//PAINT ELEMENTS
ship.paintBlock(graphDB);
ball.paintBall(graphDB,ball.getRadio(), ball.getXC(), ball.getYC());
paintBlockList(graphDB);
repaint();
sleep(1);
} catch (InterruptedException ex) {
System.out.println("there is a error in the while.....!!!!");
}
System.out.println("xc: "+ball.getXC()+"; yc: "+ball.getYC()+"; dx: "+ball.getDX()+"; dy: "+ball.getDY()+"; m: "+ball.getM());
//System.out.println(ball.printFirst());
}
}catch(Exception e){
System.out.println("there is a error!!!!");
}
}
@Override
public void update(Graphics g){
paint(g);
}
private void borderCrash(){
if(ball.getYC()<30 && ball.getDY()<0){
ball.setDY(ball.getDY()*-1);
ball.setAllFirst();
}
if(ball.getYC() >= 570 && ball.getDY()>0){
ball.setDY(ball.getDY()*-1);
ball.setAllFirst();
}
if(ball.getXC() <= 30 && ball.getDX()<0){
ball.setDX(ball.getDX()*-1);
ball.setAllFirst();
}
if(ball.getXC() >=570 && ball.getDX()>0){
ball.setDX(ball.getDX()*-1);
ball.setAllFirst();
}
}
private void paintBlockList(Graphics g){
for(ArrayList<Block> lb : blockList){
for(Block b: lb){
b.paintBlock(g);
//System.out.println(" BLOCK PAINTED !!!!!!!!!!!!!!!!!!!!!");
}
}
}
private void blockListCrashes(){
for(ArrayList<Block> lb : blockList){
for(Block b: lb){
b.blockCrash(ball);
//System.out.println(" BLOCK CRASH VERIFY !!!!!!!!!!!!!!!!!!!!!");
}
}
}
private void blockListUpdatepoints(){
for(ArrayList<Block> lb : blockList){
for(Block b: lb){
b.updatePoints();
//System.out.println(" BLOCK UPDATE VERIFY !!!!!!!!!!!!!!!!!!!!!");
}
}
}
//KILL BLOCKS FROM LISTBLOCK WITH SHIP GUN'S
private void blockListKill(){
try {
ArrayList<Gun> gunList = ship.getGunlist();
for(ArrayList<Block> lb : blockList){
for(Block b: lb){
int ym;
int xm;
int xlb;//left block
int xrb;//right block
int top;//top block
int below;//below block
for(Gun g :gunList){
ym = g.getYM();
xm = g.getXM();
xlb = b.sideX1;
xrb = b.sideX2;
top = b.sideY1;
below = b.sideY2;
if((ym == below)&&(xm>=xlb&&xm<=xrb)){
if(!b.getForEver()){
b.killBlock();
}
ship.getGunlist().remove(g);
}else
if((g.getYL() == below)&&(g.getXL()>=xlb && g.getXL()<=xrb)){
if(!b.getForEver()){
b.killBlock();
}
ship.getGunlist().remove(g);
}else
if((g.getYR() == below) && (g.getXR()>=xlb && g.getXR()<=xrb)){
if(!b.getForEver()){
b.killBlock();
}
ship.getGunlist().remove(g);
}
}
if(b.isDead()){
lb.remove(b);
}
}
}
} catch (Exception e) {
System.out.println("ERROR IN THE KILL LIST ");
}
}
private void fillBockList(){
ArrayList<Block> l1 = fillRow(5, 100, 100, 100, 20, Color.BLUE);
ArrayList<Block> l2 = fillRow(5, 70, 130, 100, 20, Color.BLUE);
ArrayList<Block> l3 = fillRow(5, 100, 160, 100, 20, Color.BLUE);
ArrayList<Block> l4 = fillRow(5, 70, 190, 100, 20, Color.BLUE);
ArrayList<Block> l5 = fillRow(5, 100, 210, 100, 20, Color.BLUE);
ArrayList<Block> l6 = fillRow(5, 70, 240, 100, 20, Color.BLUE);
ArrayList<Block> l7 = fillRow(5, 100, 270, 100, 20, Color.BLUE);
ArrayList<Block> l8 = fillRow(5, 70, 300, 100, 20, Color.BLUE);
blockList.add(l1);
blockList.add(l2);
blockList.add(l3);
blockList.add(l4);
blockList.add(l5);
blockList.add(l6);
blockList.add(l7);
blockList.add(l8);
}
private ArrayList<Block> fillRow(int n, int xo, int yo,int w, int h, Color c){
ArrayList<Block> lb = new ArrayList<Block>();
for(int i = 0; i<n; i++){
/*
if(i%2==0){
Block block = new Block(xo, yo, w, h, Color.WHITE);
xo += w;
block.setForEver();
lb.add(block);
}else{
*/
Block block = new Block(xo, yo, w, h, c);
xo += w;
lb.add(block);
//}
}
return lb;
}
}
|
Python
|
UTF-8
| 1,568 | 2.640625 | 3 |
[] |
no_license
|
# Utility script to provide some commonly used functions
def conn_s3():
"""
This function will build connection
to S3 with credentials
"""
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID', 'default')
aws_secret_access_key = os.getenv('AWS_SECRET_ACCESS_KEY', 'default')
conn = boto.connect_s3(aws_access_key, aws_secret_access_key)
bk = conn.get_bucket('cyber-insight', validate=False)
return(bk)
def spark_session():
"""
This function will build spark cass_session
and spark context with proper config
"""
conf = SparkConf().set('spark.cassandra.connection.host',
'ec2-18-232-2-76.compute-1.amazonaws.com') \
.set('spark.streaming.backpressure.enabled', True) \
.set('spark.streaming.kafka.maxRatePerPartition', 5000)
spark = SparkSession \
.builder \
.config(conf=conf) \
.appName("Real time prediction") \
.master('spark://ip-10-0-0-14.ec2.internal:7077') \
.getOrCreate()
sc = spark.sparkContext
return(spark, sc)
def cass_conn():
"""
This function builds a connection
to cassandra database
"""
cluster = Cluster(['ec2-18-232-2-76.compute-1.amazonaws.com'])
cass_session = cluster.connect('cyber_id')
return(cass_session)
def convertColumn(df, names, newType):
"""
This function converts all columns
from a dataframe to float type
"""
for name in names:
df = df.withColumn(name, df[name].cast(newType))
return(df)
|
Shell
|
UTF-8
| 1,867 | 2.8125 | 3 |
[] |
no_license
|
# reference: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap
# 6 ways to create configmap
# 1. create from config folder
# Folder files:
# the_folder/
# ui.properties
# logic.properties
# Result in:
# data:
# ui.properties: /
# screen_width: 40
# screen_height: 60
# ...
kubectl create configmap <name> --from-file=/path/to/the_folder/
# 2. create from config files
kubectl create configmap <name> --from-file=/path/to/the_folder/ui.properties --from-file=/path/to/the_folder/ui.properties
# you can also use custom key name instead of file name
kubectl create configmap <name> --from-file=ui=/path/to/the_folder/ui.properties
# 3. load config kv from file
kubectl create configmap <name> --from-env-file=/path/to/the_folder/ui.properties
kubectl create configmap <name> --from-env-file=/path/to/the_folder/ui2.properties # all previous data will be replaced
kubectl create configmap <name> --from-env-file=/path/to/the_folder/ui.properties --from-env-file=/path/to/the_folder/logic.properties
# 4. create from literals
kubectl create configmap <name> --from-literal=key1=value1 --from-literal=key2=value2
# 5. sometimes you want to create a configmap from a template with a name prefix
# ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#create-a-configmap-from-generator
# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-4
files:
- configure-pod-container/configmap/game.properties
EOF
kubectl apply -k .
configmap/game-config-4-m9dm2f92bt created
# 6. create from resource definition
kubctl -apply -f <configmap_file.yaml>
# ------
# configmap can be used with ENV or mounted file
# take `dapi-test-pod1` and `dapi-test-pod2` in configmap-template.yaml as an example
|
Markdown
|
UTF-8
| 10,147 | 2.890625 | 3 |
[
"Unlicense"
] |
permissive
|
---
title: "Automatentheorie (German)"
layout: post
---
Dieser Blogeintrag befasst sich mit den Inhalten der AT-Klausur 2021. Die Inhalte dieser Klausur sind aufgrund der Pandemie leider reduziert, was der Herausforderung verschuldet ist, dass die Lehrveranstaltung online zu organisieren und abzuhalten war.
Im Folgenden möchte ich eine Zusammenfassung der Inhalte erstellen um sie im Nachgang ein weiteres Mal reflektieren und abhandeln zu können.
# DEA
Der Deterministische endliche Automat (DEA) ist ein Fünftupel, und besteht aus:
Q - Menge der Zustände
Σ - Menge der Eingabesymbole
δ - einer Übergangsfunktion δ = Q x Σ -> Q
q0- einem Startzustand
F - Menge von Endzuständen
A = (Q, Σ, δ, q0, F)
Einen Automaten definiert man in dem man die durch die zugehörigkeit durch einsezten aufzeigt. und die Übergangsfunktionen bestimmt.
```
A = ({a,b,c,e,f}, {0,1}, δ, a, {f})
δ(a, 0) = b
δ(a, 1) = f
δ(b, 0) = f
δ(b, 1) = c
δ(c, 0) = e
δ(c, 1) = c
δ(e, 0) = f
δ(e, 1) = f
δ(f, 0) = f
δ(f, 1) = f
```
<span style="color:red">**MERKE:**</span>
Aus der Übergangsform ist ersichtlich, dass für jedes Eingabewort genau ein Weg existiert, weil übergänge aus den Zuständen für jedes Eingabesymbol aus Σ klar definiert sein müssen!
# Definition der erweiterten Übergangsfunktion:
```
> δ(q, ε) = q∈Q
> δ̂ (q, aw) = δ̂ ( δ(q, a), w) für a∈Σ, w∈Σ*
```
### Rechnen mit DeltaDach
Gegeben sei der zuvor formalisierte Automat und das Wort `w = '0110'`. Dieser soll im folgenden den Zustand angeben in dem er sich nach Abhandlung des Wortes befindet.
```
δ̂ ( a, 0110) =
δ( δ̂ ( a, 011), 0) =
δ( δ(δ̂ ( a, 01), 0), 1) =
δ( δ( δ( δ̂ (a, 0), 0), 1), 1) =
δ( δ( δ( δ(a, ε), 0), 1), 1), 0) =
δ( δ( δ( δ( a, 0), 1), 1), 0) =
δ( δ( δ( b, 1), 1), 0) =
δ( δ( c, 1), 0) =
δ( c, 0) =
e , und weil e∈F ist `0110` teil der Sprache L(A) welcher dieser Automat representiert.
```
### Vollständigkeit
Alle wörter der Sprache können durch den Automaten abgebildet werden
### Korrektheit:
Es werden nicht noch zufällig weitere Wörter abgebildet
### Weitere Definitionen
Ein Automat hat eine definierte Sprache L(A)
Diese Sprache L(A) ⊆ Σ* .
Σ* ist die Menge aller Wörter, die durch die Eingabesymbole aus Σ abgebildet werden können.
Da die leere Menge Teilmenge einer jeden Menge ist, existieren auch Automaten die die Leere Sprache akzeptieren. zB:

oder zB. alle Wörter:

# NEA
Der nichtdeterministische endliche Automat (NEA) ist ein genau wie der deterministische ein Fünftupel, und besteht aus:
A = (Q, Σ, δ, q0, F)
Q - Menge der Zustände
Σ - Menge der Eingabesymbole
δ - einer **Übergangsrelation** δ = Q x Σ -> **{Q}**
q0- einem Startzustand
F - Menge von Endzuständen
<span style="color:red">**MERKE:**</span>
NEA und DEA unterscheiden sich lediglich durch den Typ des Rückgabewertes von δ. Im Fall eines NEA handelt es sich um eine Menge von Zuständen und im Fall eines DEA um einen einzigen Zustand.
Das bedeutet, zu einem bestimmten Zeitpunkt kann sich der NEA in mehreren Zuständen zugleich befinden.
### Automat ohne Endzustände
Über Automaten ohne Endzustände lässt sich sagen, dass sie in der Praxis eher selten vorkommen, jedoch theoretisch möglich sind. Da im DEA als auch im NEA F eine Menge von Endzuständen ist und die leere Menge eine Teilmenge jeder Menge ist.
### Umwandlung NEA -> DEA (Potenzmengenkonstruktion)
Zur Umwandlung eines NEA zu einem DEA wird die Potenzmengenkonstruktion verwendet. Bei der Umwandlung kann es dazu kommen, dass der DEA im schlimmsten fall exponenziell größer wird.
Beispiel:
Gegeben sei folgender NEA:

A = (Q, Σ, δ, q0, F)
A = ({q0, q1, q2}, {0,1}, δ, q0, {q2})
Um die Potenzmengenkonstruktion durchführen zu können, muss zu Beginn die Potenzmenge der Zustände gebildet werden.
Die Potenzmenge einer Menge Q, ist die Menge, die alle Teilmengen von Q besitzt. Wieviele Potzenmengen gibt es von einer Menge?
Wenn Q eine Menge mit n Elementen ist, dann besitzt die Potenzmenge 2^n Elemenete
Das Bedeutet im Bezug auf unser Beispiel, da Q drei Elemente besitzt, dass die Potenzmenge 2³ = 8 Elemente besitzt und sieht wie folgt aus:
P(Q) = {∅, {q0}, {q1}, {q2}, {q0, q1}, {q0, q2}, {q1, q2}, {q0, q1, q2}}
Um Nun einen DEA mit der Potenzmengenkonstruktion Abbilden zu können muss für den Automaten ausgehend vom Startzustand die verschiedenen Übergänge für die Eingabesymbole aus Σ gebildet werden.
δ(∅, 0) = ∅
δ(∅, 1) = ∅
δ({q0}, 0) = {q0,q1}
δ({q0}, 1) = {q0}
δ({q1}, 0) = {q1}
δ({q1}, 1) = {q1,q2}
δ({q2}, 0) = ∅
δ({q2}, 1) = ∅
δ({q0,q1}, 0) = {q0,q1}
δ({q0,q1}, 1) = {q0,q1,q2}
δ({q0,q2}, 0) = {q0,q1}
δ({q0,q2}, 1) = {q0}
δ({q1,q2}, 0) = {q1}
δ({q1,q2}, 1) = {q1,q2}
δ({q0,q1,q2}, 0) = {q0,q1}
δ({q0,q1,q2}, 1) = {q0,q1,q2}
Somit bildet die Potenzmengenkonstruktion `Potenzmenge * |Σ|` zeichen ab in diesem fall `8 * 2`
da `Σ = {0,1}` und somit die Anzahl der Elemente in `|Σ| = 2` sind.
Daraus ergibt sich folgendes Zustandsdiagramm:

Relevant sind beim Abbilden des Automates lediglich die Zustände, die Startzustand aus erreicht werden können.
<span style="color:red">**!!! WICHTIG !!!**</span>
<span style="color:red">**Zu beachten ist, sollte sich ein Endzustand in der Teilmenge befinden, so wird die Teilmenge automatisch auch zu einem Endzustand!**</span>
# Kontextfreie Grammatik (KfG)
Eine Kontextfreie ist eien formale Grammatik, die Ersetzungsregeln enthält. Sie wird oft im Zusammenhang der Berechenbarkeitstheorie sowie in im Compilerbau verwendet. Mit einer KfG kann beispielsweise innerhalb eines Quellcodes feststellen ob eine offene Klammer auch geschlossen wird und dass ganz ohne Abhängigkeiten zu dem was dazwischen steht:
Beispiel:
``` bash
S -> { X }
X -> .....
```
die geschweiften Klammern sind Terminalsymbole und erzwingen dass vor der Eingabe von X, was eine Variable ist und unendlich erweitert werden kann. Somit stellt die gegebene Grammatik sicher, dass eine offene Klammer zu jedem Zeitpunkt auch eine passende geschlossene hat. Vorrausgesetzt X gibt nix anderes vor!
Definition wird eine Grammatik wie folgt:
G = (V, Σ, S, P)
Q - endliche Menge von Variablensymbolen
Σ - ein Alphabet von Terminalymbolen
S - ein ausgezeichnetes Startsymbol S ∈ V
P - eine Menge von Regeln P ⊆ (V ∪ Σ)* x (V ∪ Σ)* .
und kontextfrei falls P ⊆ V x (V ∪ Σ)*
Beispiel:
Sei eine Sprache `L = { a^n b^2n+1 | n >= 1 }` gegeben, zu der eine kontext freie Grammatik entwickelt werden soll.
Diese Sprache lässt sich mit einer einzigen Zeile representieren
```S -> aSbb | abbb```
,da durch dass abbb das kleinste Wort sichergestellt ist und somit auch die `+1` auf der b Seite welche dazu führt, dass das b eine ungerade Menge von b folgen hat. Durch `aSbb` ist widerum sichergestellt, dass für alle natürlichen Zahlen >=1 die Sprache immer vollständig ist, denn das Terminalsymbol `a` wird immer `n` mal produziert, wohingegen `b` durch die Regelanwendung zwei mal Produziert wird. Damit gilt automatisch, dass `b` doppelt so oft produziert wird wie a und somit `bb` gewährleistet, dass b^2 erfüllt ist.
Da alle Komponenten dazu führen, dass alle Wörter der Sprache representierbar sind, ist die Sprache vollständig. Da offensichtlich durch die Anwendung der Regeln kein anderes Wort als `abbb` und `aSbb`, darstellen kann und `aSbb` offensichtlich eine Rekursion ist, wird auch kein Wort außerhalb der Sprache durch die Grammatik representiert. Dadurch ist die Grammatik ebenso korrekt.
### Ableiten einer Grammatik
Eine Grammatik wird abgeleitet indem ein gegebenes wort, durch die Regelanwendung der Grammatik erzeugt wird. Hierbei ist lediglich zu beachten, dass die Schritte einzeln abzubilden sind.
Beispiel:
Gegeben ist die Grammatik: `S -> aSbb | abbb`
Aufgabe: Erstellen Sie die Ableitung für das Wort `aaabbbbbbb`
Nun wird beginnend bei der Variable S wird das Wort Schritt für Schritt abgeleitet.
S => aSbb => aaSbbb => aaabbbbbbb
Der dazugehörige Ableitungsbaum sieht wie folgt aus:
```
S
/ | \
a S bb
/ | \
a S bb
|
abbb
```
Und spiegelt das abgeleitete Word annhand der Blätter ausgehend von links oben, nach unten bis hin wieder nach rechts oben wieder.
# Klausurinhalte und Organisation
Zu beginn eine kurze Besprechung der Klausur
- 2 Seiten lang
- Handschriftliche Lösung
- Studienausweis in die Kamera halten
- handschriftliche Lösungen
- Antworten per e-Mail (von HS Adresse)
- 90 Minuten bearbeitungszeit
- [email protected]
# KlausurInhalte:
#### Aufgabe 1 DEA(10 Punkte)
Gegeben: Zustandsdiagramm (4 Zustände)
a) (4 Punkte) Aufgabe: Formal als 5 Tupel aufschreiben (auf runde und geschweifte Klammern achten) etc.
b) (3 Punkte) Aufgabe: DeltaDach ausrechnen vom Startzustand aus
c) (3 Punkte) Aufgabe: Multiple Choice 6 Stück (zb. Automat akzeptiert Wort ... )
#### Aufgabe 2 DEA (10 Punkte)
Gegeben: zwei Sprachen L1 und L2.
Aufgabe: Entwickle für einen der beiden Sprachen einen Automaten
#### Aufgabe 3: NEA (10 Punkte)
Gegeben: Formalisierung gegeben
a) NEA auf Basis der gegebenen Formalisierung zeichnen
b) Zeichnen Sie den Suchbaum dazu
c) Potenzmengenkonstruktion
#### Aufgabe 4: NEA (10 Punkte)
Gegeben: zwei Sprachen L1 und L2
Aufgabe: Zeichne NEA zu der Sprache
#### Aufgabe 5: KFG (14 Punkte)
Gegeben: Formaliesierter KFG
a) Ableitung von dem Wort ist (3 Punkte)
b) Ableitungsbaum von den Mengen (5 Punkte)
c) herausfinden welche Sprache erzeugt wird, begründen Sie Vollständigkeit und Korrektheit (6 Punkte)
3 Nichtterminale, 2 Terminalsymbole (a,b), 7 Regeln
#### Aufgabe 6: KFG (6 Punkte)
Entwicklung einer KFG der eine Bestimmte Sprache erkennt
|
Python
|
UTF-8
| 983 | 2.671875 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
# coding=utf-8
from django.test import TestCase
from django.test.utils import override_settings
from oscar.core import utils
sluggish = lambda s: s.upper()
class TestSlugify(TestCase):
def test_uses_custom_mappings(self):
mapping = {'c++': 'cpp'}
with override_settings(OSCAR_SLUG_MAP=mapping):
self.assertEqual('cpp', utils.slugify('c++'))
def test_uses_blacklist(self):
blacklist = ['the']
with override_settings(OSCAR_SLUG_BLACKLIST=blacklist):
self.assertEqual('bible', utils.slugify('The Bible'))
def test_handles_unicode(self):
self.assertEqual('konig-der-strasse',
utils.slugify(u'König der Straße'))
def test_works_with_custom_slugifier(self):
for fn in [sluggish, 'tests.integration.core.test_utils.sluggish']:
with override_settings(OSCAR_SLUG_FUNCTION=fn):
self.assertEqual('HAM AND EGGS', utils.slugify('Ham and eggs'))
|
Swift
|
UTF-8
| 1,064 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
//
// Date+Extensions.swift
// Ogrenich iOS Framework
//
// Created by Andrey Ogrenich on 13/06/2017.
// Copyright © 2017 Andrey Ogrenich. All rights reserved.
//
import Foundation
public extension Date {
public static func from(string: String,
with format: String = "yyyy-MM-dd'T'HH:mm:ss.SSSX") -> Date? {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = format
return formatter.date(from: string)
}
public static func string(from date: Date?,
with format: String = "yyyy-MM-dd'T'HH:mm:ss.SSSX",
context: Formatter.Context = .standalone) -> String? {
guard let date = date else {
return nil
}
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = format
formatter.formattingContext = context
return formatter.string(from: date)
}
}
|
Java
|
UTF-8
| 1,157 | 2.6875 | 3 |
[] |
no_license
|
package com.exilant.day1;
public class PriorityCustomer {
private int customerId;
private String customerName;
private String customerType;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
@Override
public String toString() {
return "PriorityCustomer [customerId=" + customerId + ", customerName=" + customerName + ", customerType="
+ customerType + "]";
}
public PriorityCustomer(int customerId, String customerName, String customerType) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.customerType = customerType;
}
public PriorityCustomer() {
super();
}
public PriorityCustomer(int customerId, String customerName) {
super();
this.customerId = customerId;
this.customerName = customerName;
}
}
|
Python
|
UTF-8
| 1,337 | 3.921875 | 4 |
[] |
no_license
|
import jieba.analyse
"""
文字檔案的編碼格式與文字檔讀取方法
讀取檔案三部曲
1. 所有資源放在專案底下
2. 檔案路徑: 相對路徑
r 指唯讀 W 指可寫
3. 檔案編碼: 最好使用 utf-8 , 避免有難字、亂碼等情況出現
"""
print('--- 檔案的處理 START ---\n')
# 打開檔案
"""
1. open('檔名1.txt')
2. open('/data/檔名2.txt')
3. open('./data/檔名3.txt')
4. open('../data/檔名4.txt')
5. open('C:\\user\\檔名5.txt')
"""
BasicFile = open("./txtFile/BasicFileProcess.txt", "r", encoding="utf-8")
# 把檔案內容放置 變數內
article = BasicFile.read()
# 記得要關閉檔案
BasicFile.close()
# print(article)
# 設定一個 Dictionary 來做記錄
result = {}
for c in article:
# 對: 我們第二次以上選到
print("檔內字:", c)
if c in result:
result[c] = result[c] + 1
print("第 N 次出現:", result)
# 錯: 我們第一次遇到
else:
result[c] = 1
print("第一次出現:", result)
print(result)
# Open a file
NewArticle =''
fo = open("./txtFile/NewBasicFileProcess.txt", "w+" , encoding="utf-8")
for c in result:
if c in result:
NewArticle = NewArticle + c + ":" + str(result[c]) + "|"
print(NewArticle)
fo.write(NewArticle)
fo.close()
print('\n--- 檔案的處理 END ---\n')
|
C++
|
UTF-8
| 225 | 2.765625 | 3 |
[] |
no_license
|
class Solution {
public:
int trailingZeroes(int n) {
int t =5;
int count5 = 0;
while(n/t != 0){
count5 += n/t;
t = t*5;
}
return count5;
}
};
|
Java
|
UTF-8
| 2,632 | 1.820313 | 2 |
[] |
no_license
|
package com.example.airbag.airbag.fragments;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.airbag.airbag.R;
import com.example.airbag.airbag.activities.Popup2;
import com.example.airbag.airbag.classes.Bag;
import com.example.airbag.airbag.models.bagdetailspostmodel.BagDetailsPostModel;
import com.example.airbag.airbag.models.getotpmodel.GetOtpModel;
import com.example.airbag.airbag.rest.ApiClient;
import com.example.airbag.airbag.rest.ApiInterface;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Rishabh Jain on 3/22/2017.
*/
public class MainFragment extends Fragment {
String TicketNumber,BagType,BagName,BagColor,BagBrand,mobile;
EditText et_TicketNumber,et_BagType,et_BagName,et_BagColor,et_BagBrand;
Button finalSaveButton;
ImageButton FloatingButton,fab;
PopupWindow pw;
List<Bag> bags;
SharedPreferences shared;
View rootview;
Context mcontext;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_main,container,false);
bags=new ArrayList<Bag>();
et_TicketNumber= (EditText) rootview.findViewById(R.id.et_ticketNumber);
FloatingButton= (ImageButton) rootview.findViewById(R.id.floatingActionButton);
mcontext=getContext();
FloatingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TicketNumber=et_TicketNumber.getText().toString();
shared=getContext().getSharedPreferences("MyPrefrences",0);
SharedPreferences.Editor editor=shared.edit();
editor.putString("TicketNumber",TicketNumber);
editor.commit();
Intent intent=new Intent(getContext(), Popup2.class);
startActivity(intent);
}
});
return rootview;
}
}
|
PHP
|
UTF-8
| 2,980 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
namespace Mix\Udp\Server;
use Swoole\Coroutine\Socket;
use Mix\Concurrent\Coroutine;
/**
* Class UdpServer
* @package Mix\Udp\Server
* @author liu,jian <[email protected]>
*/
class UdpServer
{
/**
* @var int
*/
public $domain = AF_INET;
/**
* @var string
*/
public $address = '127.0.0.1';
/**
* @var int
*/
public $port = 9504;
/**
* @var bool
*/
public $reusePort = false;
/**
* @var callable
*/
protected $handler;
/**
* @var Socket
*/
public $swooleSocket;
/**
* UdpServer constructor.
* @param int $domain
* @param string $address
* @param int $port
* @param bool $reusePort
*/
public function __construct(int $domain, string $address, int $port, bool $reusePort = false)
{
$this->domain = $domain;
$this->address = $address;
$this->port = $port;
$this->reusePort = $reusePort;
}
/**
* Handle
* @param callable $callback
*/
public function handle(callable $callback)
{
$this->handler = $callback;
}
/**
* Start
*/
public function start()
{
$socket = $this->swooleSocket = new Socket($this->domain, SOCK_DGRAM, 0);
if ($this->reusePort) {
$socket->setOption(SOL_SOCKET, SO_REUSEPORT, true);
}
$result = $socket->bind($this->address, $this->port);
if (!$result) {
throw new \Swoole\Exception($socket->errMsg, $socket->errCode);
}
while (true) {
$peer = null;
$data = $socket->recvfrom($peer);
if ($socket->errCode == 104) { // shutdown
return;
}
if ($data === false) {
continue;
}
Coroutine::create($this->handler, $data, $peer);
}
}
/**
* Send
* @param string $data
* @param int $port
* @param string $address
*/
public function send(string $data, int $port, string $address)
{
$len = strlen($data);
$size = $this->swooleSocket->sendto($address, $port, $data);
if ($size === false) {
throw new \Swoole\Exception($this->swooleSocket->errMsg, $this->swooleSocket->errCode);
}
if ($len !== $size) {
throw new \Swoole\Exception('The sending data is incomplete for unknown reasons.');
}
}
/**
* Shutdown
*/
public function shutdown()
{
if (!$this->swooleSocket->close()) {
$errMsg = $this->swooleSocket->errMsg;
$errCode = $this->swooleSocket->errCode;
if ($errMsg == '' && $errCode == 0) {
return;
}
if ($errMsg == 'Connection reset by peer' && $errCode == 104) {
return;
}
throw new \Swoole\Exception($errMsg, $errCode);
}
}
}
|
Shell
|
UTF-8
| 6,341 | 3.59375 | 4 |
[] |
no_license
|
#!/bin/bash
# fonctionnement:
# il récupere les hosts depuis Ganglia en s'aidant du script /usr/share/ganglia-webfrontend/nagios/get_hosts.php se trouvant sur la machine Gmetad
# il récupere les hosts depuis l'API Centreon aprés l'authentification et l'obtention d'un jeton
# test si les hosts de Ganglia existe déja sur Centron:
# si ce n'est pas le cas, il ajoute les hosts a Centreon
# cette fonctionsera utilisé à la fin
function list_include_item {
local list="$1"
local item="$2"
if [[ $list =~ (^|[[:space:]])"$item"($|[[:space:]]) ]] ; then
# yes, list include item
result=0
else
result=1
fi
return $result
}
# host_type : dockerhost / api
host_type=$1
if [ "$host_type" == "api" ];then
filter="?hreg=^api\."
else
filter="?hreg=^(core\d*|coredb\d*|geoserver\d*|modelrunner\d*)\."
fi
GANGLIA_URL="https://ganglia.forcity.io/ganglia/nagios/get_hosts.php"
# retrieve hosts from ganglia
# -s pour mode silence
HOSTS=$(curl -s "${GANGLIA_URL}${filter}")
echo $HOSTS
# authenticate against Centreon (needs user test_user/test_password with Reach API rights)
# -s : silence
# -XPOST : X pour pouvoir utiliser le mode POST
# --data pour remplire le post
# | : pipe, la sortie de la 1ere commande devient l'entree de la 2eme commande
# jq -r pour transformer le resultat json en string: ".authToken" pour avoir la valeur de la clé authToken
token=$(curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=authenticate' --data "username=test_user&password=test_password" |jq -r ".authToken")
# echo "token=$token"
# retrieve existing hosts from Centreon
# voir doc: https://documentation.centreon.com/docs/centreon/en/2.8.x/api/api_rest/index.html#list-hosts
# besoin de:
# Body : --data '{"action": "show","object": "host"}'
# Header: -H "Content-Type:application/json" -H "centreon_auth_token:$token" ,centreon_auth_token appel la variable $token qui contient la clé d'auth
# |jq -r ".result[].name" : transforme du jsson en string et prend le la valeur de la clé name ( des hosts)
KNOWNHOSTS=$(curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' \
--data '{
"action": "show",
"object": "host"
}' \
-H "Content-Type:application/json" \
-H "centreon_auth_token:$token" |jq -r ".result[].name")
echo $KNOWNHOSTS
# echo curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' --data '{"action": "show","object": "host"}' -H "Content-Type:application/json" -H "centreon_auth_token:$token"
# compare entre les hosts de ganglia et les hosts de centreon, si un host ganglia n'existe pas dans centreon, il sera ajouté
# list_include_item() : fonction qui compare et retourne 0 si host existe et 1 sinon
# || : it will evaluate the right side only if the left side exit status is nonzero, c-a-d qu'on ajoute le host dans centreon si list_include_item() retourne 1
# voir doc : https://documentation.centreon.com/docs/centreon/en/2.8.x/api/api_rest/index.html#add-host
# necessite:
# Body : --data
# Header : -H:
# 1 : host name
# 2 : alias
# 3 : ip
# 4 : host template (doit etre déja ajouté a centreon), ici c'est ganglia-host
# 5 : poller
# 6 : host group (doit etre déja ajouté a centreon), ici c'est docker-hosts
# for each host in ganglia
need_restart=
for host in $HOSTS; do
if [[ $host = *[!\ ]* ]]; then #test si $host est vide
if [ "$host_type" == "api" ];then
api_host=$(echo $host|sed -r 's/^.+?\.(.+\.forcity\.io)$/\1/')
geoserver_host=$(echo $api_host |sed -r 's/\.forcity\.io/-geoserver.forcity.io/')
# check if hosts already exist in centreon hosts list; if not, add host to centreon (needs work on values field; needs ganglia-host template, and docker-hosts host group)
if [ ! $(list_include_item "$KNOWNHOSTS" "$api_host") ]; then
curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' \
--data "{
\"action\": \"add\",
\"object\": \"host\",
\"values\": \"$api_host;$api_host;$api_host;api-host;central;api-hosts\"
}" \
-H "Content-Type:application/json" \
-H "centreon_auth_token:$token"
ip=$(dig +short $geoserver_host |tr -d ' ')
if [ "$ip" == "" ]; then
geoserver_host=$api_host
curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' \
--data "{
\"action\": \"addhostgroup\",
\"object\": \"host\",
\"values\": \"$geoserver_host;geoserver-hosts\"
}" \
-H "Content-Type:application/json" \
-H "centreon_auth_token:$token"
else
if [ ! $(list_include_item "$KNOWNHOSTS" "$geoserver_host") ]; then
curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' \
--data "{
\"action\": \"add\",
\"object\": \"host\",
\"values\": \"$geoserver_host;$geoserver_host;$geoserver_host;api-host;central;geoserver-hosts\"
}" \
-H "Content-Type:application/json" \
-H "centreon_auth_token:$token"
fi
fi
fi
need_restart=1
else
# check if hosts already exist in centreon hosts list; if not, add host to centreon (needs work on values field; needs ganglia-host template, and docker-hosts host group)
if [ ! $(list_include_item "$KNOWNHOSTS" "$host") ]; then
curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' \
--data "{
\"action\": \"add\",
\"object\": \"host\",
\"values\": \"$host;$host;$host;ganglia-host;central;docker-hosts\"
}" \
-H "Content-Type:application/json" \
-H "centreon_auth_token:$token"
need_restart=1
fi
fi
fi
done
# redemarage du pooler
if [ "$need_restart" == "1" ]; then
curl -s -XPOST 'http://127.0.0.1/centreon/api/index.php?action=action&object=centreon_clapi' \
--data '{"action": "APPLYCFG", "values": "1"}' \
-H "Content-Type:application/json" \
-H "centreon_auth_token:$token"
fi
|
C++
|
UTF-8
| 2,078 | 3.0625 | 3 |
[] |
no_license
|
/* Written by Brian Sun
* Date: August 1, 2020
* An obstacle detecting robot that produces sound
*/
#include <NewPing.h> // include the NewPing library for this program
#include <Servo.h>
Servo myservo; //create servo object to control a servo
#define VCC_PIN 13
#define TRIGGER_PIN 12 // sonar trigger pin will be attached to Arduino pin 12
#define ECHO_PIN 11 // sonar echo pint will be attached to Arduino pin 11
#define GROUND_PIN 10
#define buzzer 5
#define MAX_DISTANCE 200 // maximum distance set to 200 cm
#define threshold 12 //distance set for object detection in cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // initialize NewPing
void detectObject(void);
void setup(){
Serial.begin(9600); // set data transmission rate to communicate with computer
pinMode(ECHO_PIN, INPUT) ;
pinMode(TRIGGER_PIN, OUTPUT) ;
pinMode(GROUND_PIN, OUTPUT); // tell pin 10 it is going to be an output
pinMode(VCC_PIN, OUTPUT); // tell pin 13 it is going to be an output
pinMode(buzzer, OUTPUT);
digitalWrite(GROUND_PIN,LOW); // tell pin 10 to output LOW (OV, or ground)
digitalWrite(VCC_PIN, HIGH) ; // tell pin 13 to output HIGH (+5V)
pinMode(8,INPUT_PULLUP); //pin 8 forced to HIGH when there is no external input
myservo.attach(9); //attaches the servo on pin 9 to the servo object
myservo.write(0); //tells servo to go to 0 degree position
}
void loop(){
int pos;
int num;
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
myservo.write(pos);
detectObject();
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 0 degrees to 180 degrees
myservo.write(pos);
detectObject();
}
}
void detectObject(void){ //senses for objects within threshold distance
int DISTANCE_IN_CM = sonar.ping_cm();
printMes(DISTANCE_IN_CM);
if(DISTANCE_IN_CM <= threshold && DISTANCE_IN_CM != 0){ // makes sound
digitalWrite(buzzer, HIGH);
} else{
delay(20);
digitalWrite(buzzer,LOW);
}
}
|
Ruby
|
UTF-8
| 694 | 3.015625 | 3 |
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../models/card_game')
require_relative('../models/card')
class CardGameTest < MiniTest::Test
def test_check_for_ace
card_game = CardGame.new()
card = Card.new('ace', 1)
assert_equal(true, card_game.check_for_ace(card))
end
def test_highest_card
card_game = CardGame.new()
card1 = Card.new('three', 3)
card2 = Card.new('two', 2)
assert_equal(card1, card_game.highest_card(card1, card2))
end
def test_cards_total
card1 = Card.new('three', 3)
card2 = Card.new('two', 2)
cards = [card1, card2]
assert_equal("You have a total of 5", CardGame.cards_total(cards))
end
end
|
Java
|
UTF-8
| 1,166 | 2.421875 | 2 |
[] |
no_license
|
package com.vida.sushi.domains.aquariums;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.time.LocalDateTime;
/**
* Aquarium domain. This domain is embedded into profile,
* because is a small list and when the profile is read, we need
* read all aquariums domains by profile. Improves performance
*
* @author [email protected]
*/
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@TypeAlias("aqm")
@Document()
public class Aquarium {
@Id
private String id;
@Field("n")
private String name;
public enum AquariumType {
saltWater,
freshWater
}
@Field("t")
private AquariumType type;
@Field("cd")
private LocalDateTime creationDate;
@Field("h")
private float high;
@Field("w")
private float width;
@Field("d")
private float deep;
@Field("c")
private float capacity;
public void setName(String value) {
name = value;
}
}
|
C#
|
UTF-8
| 755 | 3.09375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Assignment_1
{
public class Problem4
{
public int NumJewelsInStones(string jewels, string stones)
{
int ans = 0;
Dictionary<char, Int16> ht = new Dictionary<char, Int16>();
foreach (char j in jewels)
{
if (!ht.ContainsKey(j))
ht.Add(j, 0);
}
foreach (char s in stones)
{
if (ht.ContainsKey(s))
{
ans++;
continue;
}
}
return ans;
}
}
}
|
Markdown
|
UTF-8
| 4,074 | 2.5625 | 3 |
[] |
no_license
|
# Curated List of Javascript Podcasts
There are lots of great podcasts coming out these days. I wanted to compile a list of some of the great ones. This list contains only currently running podcasts (atleast 1 episode in the past month). I have also included some tangentially related podcasts that you may find interesting. You can find a Word Cloud Visualization associated with each podcast, which will hopefully give you an idea about the podcast contents. I hope you find this list useful :-)
## JS Party
### Latest Episode:
Title: JavaScript is the CO2 of the web

## Real Talk JavaScript
### Latest Episode:
Title: Episode 37: Founding the dev.to platform - Ben Halpern

## Javascript to Elm
### Latest Episode:
Title: Elixir with Phoenix

## JavaScript – Software Engineering Daily
### Latest Episode:
Title: WebAssembly Compilation with Till Schneidereit

## CodeNewbie
### Latest Episode:
Title: S8:E8 - What it's like to be in a computer science class (David Malan)

## Andrew Koper
### Latest Episode:
Title: JavaScript - Regular Expressions

## Software Engineering Daily
### Latest Episode:
Title: Niantic Real World with Paul Franceus

## devMode.fm
### Latest Episode:
Title: Una Kravets on Google Material Design & web trends
## brightonSEO's podcast
### Latest Episode:
Title: Jon Quinton - How to Extract Meaningful Data from Facebook Ad Manager

## The BaseCode Podcast
### Latest Episode:
Title: 5: Breaking up long blocks of code.
## Command Line Heroes
### Latest Episode:
Title: Introducing Season 3 of Command Line Heroes

## Channel 9
### Latest Episode:
Title: An introduction to Azure Tips and Tricks | Azure Friday

## Coder Radio
### Latest Episode:
Title: 361: ZEEEE Shell!

## A Question of Code
### Latest Episode:
Title: 24: Should you write about what you've learnt?

## My Angular Story
### Latest Episode:
Title: MAS 081: Eric Simons, Albert Pai and Tomek Sulkowski

## airhacks.fm podcast with adam bien
### Latest Episode:
Title: Transactions, J2EE, Java EE, Jakarta EE, MicroProfile and Quarkus

## Merge Conflict
### Latest Episode:
Title: 153: Building Machine Learning Robots!

## Legacy Code Rocks
### Latest Episode:
Title: Kindness in Coding with Coraline Ada Ehmke

## How to Instructional Podcast on the Tech Podcast Network
### Latest Episode:
Title: PowerPress and Community Podcast: Podcasting Future Valuations

## My Ruby Story
### Latest Episode:
Title: MRS 090: Charles Max Wood

## Learn to Code in One Month
### Latest Episode:
Title: How I Built Product Hunt, Dash and more with Nathan Baschez

## The InfoQ Podcast
### Latest Episode:
Title: Johnny Xmas on Web Security & the Anatomy of a Hack

## Machine Learning – Software Engineering Daily
### Latest Episode:
Title: Niantic Real World with Paul Franceus

|
Java
|
UTF-8
| 1,188 | 2.609375 | 3 |
[] |
no_license
|
package com.example.myjsondemo;
/**
* Created by peacock on 5/9/16.
*/
public class Employee {
private String name;
private String destination;
private String pay;
private String Lanline;
private String mobile;
Employee(String name,String destination,String pay,String lanline,String mobile){
this.name=name;
this.destination=destination;
this.pay=pay;
this.Lanline=lanline;
this.mobile=mobile;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getDestination() {
return destination;
}
public void setPay(String pay) {
this.pay = pay;
}
public String getPay() {
return pay;
}
public void setLanline(String lanline) {
this.Lanline = lanline;
}
public String getLanline() {
return Lanline;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMobile() {
return mobile;
}
}
|
Java
|
UTF-8
| 1,016 | 2.359375 | 2 |
[] |
no_license
|
package com.ifoodtest.giolo.playlist;
/**
* Configurações de cache
*
* @author <a href="mailto:[email protected]">Mario Eduardo Giolo</a>
*
*/
public final class Caches {
private Caches() {
}
public static final String WEATHER_BY_CITY = "weather_by_city";
public static final String WEATHER_BY_GPS = "weather_by_gps";
public static final String GENRE_BY_WEATHER = "genre_by_weather";
//Podemos trabalhar com diferentes formas de cache, ou mesmo diferentes formas de implementar,
//
// Esta é uam configuração simples em memória apenas, só para exercitarmos a ideía de ter cache
// na aplicação, não necessariamente esta é a melhor abordagem para produção, onde devemos levar
// outros fatores em consideração, como escalabilidade, dispnibilidade, volume,
// possibilidade de cache centralizado (que sriva para N instancia da aplicação..)
//, nao consumir a propria memória da aplicação, etc..
// um bom ex para produção, seria utilizar um cluster de redis (com lettuce) como cache.
}
|
PHP
|
UTF-8
| 1,620 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
<?php
/*
* This file is part of the PhpM3u8 package.
*
* (c) Chrisyue <http://chrisyue.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Chrisyue\PhpM3u8\Tag;
class ProgramDateTimeTag extends AbstractTag
{
use SingleValueTagTrait;
const TAG_IDENTIFIER = '#EXT-X-PROGRAM-DATE-TIME';
/**
* @var string Absolute date and/or time of the first sample of the Media Segment in ISO_8601 format
*/
private $programDateTime;
/**
* @param \DateTime $programDateTime
*
* @return self
*/
public function setProgramDateTime(\DateTime $programDateTime)
{
$this->programDateTime = $programDateTime;
return $this;
}
/**
* @return \DateTime
*/
public function getProgramDateTime()
{
return $this->programDateTime;
}
/**
* @return string
*/
public function dump()
{
if (null === $this->programDateTime) {
return;
}
if (version_compare(phpversion(), '7.0.0') >= 0) {
return sprintf('%s:%s', self::TAG_IDENTIFIER, $this->programDateTime->format('Y-m-d\TH:i:s.vP'));
}
$dateString = substr($this->programDateTime->format('Y-m-d\TH:i:s.u'), 0, -3);
return sprintf('%s:%s%s', self::TAG_IDENTIFIER, $dateString, $this->programDateTime->format('P'));
}
/**
* @param string $line
*/
protected function read($line)
{
$this->programDateTime = new \DateTime(self::extractValue($line));
}
}
|
JavaScript
|
UTF-8
| 2,229 | 3.625 | 4 |
[] |
no_license
|
// Il software deve generare casualmente le statistiche di gioco di 100 giocatori di basket per una giornata di campionato.
// In particolare vanno generate per ogni giocatore le seguenti informazioni, facendo attenzione che il numero generato abbia senso:
// - Codice Giocatore Univoco (formato da 3 lettere maiuscole casuali e 3 numeri)
// - Numero di punti fatti
// - Numero di rimbalzi
// - Falli
// - Percentuale di successo per tiri da 2 punti
// - Percentuale di successo per da 3 punti
// Una volta generato il “database”, il programma deve chiedere all’utente di inserire un Codice Giocatore e il programma restituisce le statistiche.
// creo un array vuoto
var giocatori = [];
//ciclo for per popolare l'array dei 100giocatori
for(var i = 1; i <= 100; i++) {
var giocatore = {
'giocatoreUnivoco': univoco(),
'numeroPunti': getRandomNumber(1, 50),
'numeroRimbalzi': getRandomNumber(1, 50),
'falli': getRandomNumber(1, 10),
'percentuale2punti': getRandomNumber(15, 90) + '%',
'percentuale3punti': getRandomNumber(15, 90) + '%'
};
// console.log('giocatore ' + i + ' ' +giocatore);
giocatori.push(giocatore);
}
console.log(giocatori);
// document.writeln('Player '+ giocatori[key]);
function getRandomNumber(min, max) {
var newNumeroRandom = Math.floor(Math.random() * (max - min + 1) + min);
return newNumeroRandom;
}
// creo una funzione che mi restituisca tre lettere maiuscole e tre numeri randomici
function univoco() {
var gUnivoco = '';
var lettere_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numeri_list = '0123456789';
for(var i=0; i < 3; i++ ) {
gUnivoco += lettere_list.charAt(Math.floor(Math.random() * lettere_list.length));
}
for(var i=0; i < 3; i++ ) {
gUnivoco += numeri_list.charAt(Math.floor(Math.random() * numeri_list.length));
}
if (i < 3){
console.log(gUnivoco);
}
return gUnivoco;
}
var codiceUtente = prompt('inserisci il Codice Giocatore');
for(var i = 0; i < giocatori.length; i++) {
var giocatore = giocatori[i];
if (codiceUtente == giocatore){
for(var key in giocatore){
document.writeln(key + ': ' + giocatore[key] + '</br>')
}
}
else {
prompt('Il codice inserito non esite... Riprova');
}
}
|
Rust
|
UTF-8
| 898 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
use glium::glutin::{ElementState, KeyboardInput, VirtualKeyCode};
use rustyboy_core::hardware::joypad::{Button, Input, InputType};
pub fn keymap(input: KeyboardInput) -> Option<Input> {
let key_code = input.virtual_keycode?;
let button = match key_code {
VirtualKeyCode::Up => Button::Up,
VirtualKeyCode::Down => Button::Down,
VirtualKeyCode::Left => Button::Left,
VirtualKeyCode::Right => Button::Right,
VirtualKeyCode::Return => Button::Start,
VirtualKeyCode::Space => Button::Select,
VirtualKeyCode::X => Button::B, // TODO: use scancode for those so keymaps dont change the position
VirtualKeyCode::Z => Button::A,
_ => return None,
};
let input_type = if input.state == ElementState::Pressed {
InputType::Down
} else {
InputType::Up
};
Some(Input { input_type, button })
}
|
Java
|
UTF-8
| 5,108 | 1.703125 | 2 |
[] |
no_license
|
package org.edec.main.model.dao;
public class UserRoleModuleESOmodel {
private boolean groupLeader = false;
private boolean readonly = true;
private boolean student = false;
private boolean teacher = false;
private boolean parent = false;
private Integer formofstudy;
private Integer formofstudystudent;
private Integer type;
private Long idChair;
private Long idDepartment;
private Long idHum;
private Long idInstitute;
private Long idInstituteMine;
private Long idModule;
private Long idParent;
private String fio;
private String fulltitle;
private String groupname;
private String imagePath;
private String institute;
private String moduleName;
private String roleName;
private String shorttitle;
private String startPage;
private String url;
private Integer qualification;
public UserRoleModuleESOmodel () {
}
public boolean isGroupLeader () {
return groupLeader;
}
public void setGroupLeader (boolean groupLeader) {
this.groupLeader = groupLeader;
}
public boolean isReadonly () {
return readonly;
}
public void setReadonly (boolean readonly) {
this.readonly = readonly;
}
public Integer getFormofstudy () {
return formofstudy;
}
public void setFormofstudy (Integer formofstudy) {
this.formofstudy = formofstudy;
}
public Long getIdHum () {
return idHum;
}
public void setIdHum (Long idHum) {
this.idHum = idHum;
}
public String getFio () {
return fio;
}
public void setFio (String fio) {
this.fio = fio;
}
public String getImagePath () {
return imagePath;
}
public void setImagePath (String imagePath) {
this.imagePath = imagePath;
}
public String getModuleName () {
return moduleName;
}
public void setModuleName (String moduleName) {
this.moduleName = moduleName;
}
public String getRoleName () {
return roleName;
}
public void setRoleName (String roleName) {
this.roleName = roleName;
}
public String getUrl () {
return url;
}
public void setUrl (String url) {
this.url = url;
}
public boolean isStudent () {
return student;
}
public void setStudent (boolean student) {
this.student = student;
}
public Long getIdChair () {
return idChair;
}
public void setIdChair (Long idChair) {
this.idChair = idChair;
}
public Long getIdDepartment () {
return idDepartment;
}
public void setIdDepartment (Long idDepartment) {
this.idDepartment = idDepartment;
}
public Long getIdInstitute () {
return idInstitute;
}
public void setIdInstitute (Long idInstitute) {
this.idInstitute = idInstitute;
}
public Integer getFormofstudystudent () {
return formofstudystudent;
}
public void setFormofstudystudent (Integer formofstudystudent) {
this.formofstudystudent = formofstudystudent;
}
public Long getIdParent () {
return idParent;
}
public void setIdParent (Long idParent) {
this.idParent = idParent;
}
public String getFulltitle () {
return fulltitle;
}
public void setFulltitle (String fulltitle) {
this.fulltitle = fulltitle;
}
public String getGroupname () {
return groupname;
}
public void setGroupname (String groupname) {
this.groupname = groupname;
}
public String getInstitute () {
return institute;
}
public void setInstitute (String institute) {
this.institute = institute;
}
public Long getIdInstituteMine () {
return idInstituteMine;
}
public void setIdInstituteMine (Long idInstituteMine) {
this.idInstituteMine = idInstituteMine;
}
public String getShorttitle () {
return shorttitle;
}
public void setShorttitle (String shorttitle) {
this.shorttitle = shorttitle;
}
public Integer getType () {
return type;
}
public void setType (Integer type) {
this.type = type;
}
public String getStartPage () {
return startPage;
}
public void setStartPage (String startPage) {
this.startPage = startPage;
}
public boolean isTeacher () {
return teacher;
}
public void setTeacher (boolean teacher) {
this.teacher = teacher;
}
public Long getIdModule () {
return idModule;
}
public void setIdModule (Long idModule) {
this.idModule = idModule;
}
public boolean isParent () {
return parent;
}
public void setParent (boolean parent) {
this.parent = parent;
}
public Integer getQualification () {
return qualification;
}
public void setQualification (Integer qualification) {
this.qualification = qualification;
}
}
|
JavaScript
|
UTF-8
| 2,246 | 2.625 | 3 |
[] |
no_license
|
import React, { useCallback, useEffect } from "react";
import data from "./mock";
import "./App.css";
import Switch from "./components/switch";
import usePersistedState from "./use-persisted-state";
import { getDayNumbers, getDaysBetween } from "./utils";
import AuntCalender from "./components/aunt-calender";
function App() {
const [periods, setPeriods] = usePersistedState([], "periods");
const filterRecords = () => {
const records = [];
data.forEach((item) => {
const { yearmonth } = item;
const year = parseInt(yearmonth.substring(0, 4));
const month = parseInt(yearmonth.slice(4));
const totalDays = getDayNumbers(year, month);
for (let i = 1; i < totalDays + 1; i++) {
if (!!item[`D${i}`]) {
records.push({ year, month: month + 1, day: i });
}
}
});
return records;
};
const createSection = (records) => {
let i = 0;
const periods = [];
while (i < records.length) {
const period = [];
let j = i;
let prev = records[j];
let next = records[j + 1];
while (
next &&
getDaysBetween(
new Date(prev.year, prev.month - 1, prev.day),
new Date(next.year, next.month - 1, next.day)
) === 1
) {
!period.length && period.push(prev);
j++;
prev = records[j];
next = records[j + 1];
}
period.push(prev);
periods.push(period);
i = j + 1;
}
return periods;
};
const getPeriods = useCallback(() => {
const records = filterRecords();
const periods = createSection(records);
setPeriods(periods);
// setPeriods(periods.map((period) => ({ className: "red", group: period })));
}, [setPeriods]);
useEffect(() => {
getPeriods();
}, [getPeriods]);
const handleMonthChange = ({ year, month }) => {
console.log(year, month);
};
const handleDaySelect = (no) => {
console.log(no);
};
return (
<div>
<AuntCalender
periods={periods}
onMonthChange={handleMonthChange}
onDaySelect={handleDaySelect}
/>
<div className="bar">
<p>大姨妈走喽</p>
<Switch />
</div>
</div>
);
}
export default App;
|
Java
|
UTF-8
| 528 | 1.96875 | 2 |
[] |
no_license
|
package com.investMessage.config.data;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("postgres-local")
public class PostgresLocalDataSourceConfig extends AbstractDataSourceConfig {
@Bean
public DataSource dataSource() {
return createDataSource("jdbc:postgresql://localhost/customers", "org.postgresql.Driver", "postgres",
"postgres");
}
}
|
JavaScript
|
UTF-8
| 600 | 3.9375 | 4 |
[] |
no_license
|
// long running function
function waitforThreeSeconds(){
var ms = 10000+new Date().getTime();
while(new Date() < ms){
// time waisting loop
}
console.log('Execution Stack Event ONE, Finished Function !!!')
}
// this is asynchronous function , will execute once all the stack items get clear
document.addEventListener('click',()=>{
console.log('Asynchronous function is Executed from Event Queuee, once Execuation STACK popped up all events');
})
waitforThreeSeconds();
console.log('Execution Stack Event TWO, Finishes Execution and Cleared All STACK ITEMS !!');
|
PHP
|
UTF-8
| 5,521 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace controllers;
use models\Task;
use app\UserAuth;
use app\View;
use helpers\Url;
use helpers\Validator;
use helpers\Strings;
// EXPLAIN: ...
class TaskController extends BaseController
{
const PAGE_FIRST = 1;
const PAGE_LIMIT = 3;
// EXPLAIN: ...
public $prepared;
private $args;
private $countAll;
private $sortInvert;
// EXPLAIN: ...
public function __construct()
{
$this->countAll = (int)Task::countAll();
}
// EXPLAIN: ...
private function processGet() : void
{
// EXPLAIN: ...
$toSesssion = [
'sort' => Task::SORT_DEFAULT,
'page' => self::PAGE_FIRST,
];
// EXPLAIN: ...
if (empty($_GET['page']))
{
$toSession['page'] = self::PAGE_FIRST;
}
else
{
$toSession['page'] = $_GET['page'];
}
// EXPLAIN: ...
if (!empty($_GET['sort']))
{
$toSession['sort'] = $_GET['sort'];
$this->sortInvert = boolval(strpos($_GET['sort'], '-') === false);
// EXPLAIN: ...
if (!$this->sortInvert && ltrim($_GET['sort'], '-') !== ltrim($_SESSION['args']['sort'], '-'))
{
$toSession['page'] = intval($_SESSION['page-amount']);
}
}
elseif (!empty($_SESSION['args']['sort']))
{
$toSession['sort'] = $_SESSION['args']['sort'];
}
else
{
$toSession['sort'] = Task::SORT_DEFAULT;
}
// EXPLAIN: ...
if (isset($_SESSION['args']) && empty(array_diff($toSession, $_SESSION['args'])))
{
// TODO: Remove
// var_dump($toSession);
// var_dump($_SESSION);
}
else
{
$_SESSION['args'] = $toSession;
$query = '?r=task&sort=' . $toSession['sort'] . '&page=' . $toSession['page'];
$this->redirect($query);
}
}
// EXPLAIN: Default
public function index() : void
{
// EXPLAIN: ...
$this->processGet();
$limit = self::PAGE_LIMIT;
$offset = $limit * ((int)$_SESSION['args']['page'] - 1);
$orderBy = Strings::prepareOrderBy($_SESSION['args']['sort'], Task::SORT_DEFAULT);
$this->prepared = Task::getSlice($orderBy, $limit, $offset);
// EXPLAIN: ...
$pages = intval($this->countAll / self::PAGE_LIMIT) + intval($this->countAll % self::PAGE_LIMIT > 0 ? 1 : 0);
$_SESSION['page-amount'] = $pages;
// EXPLAIN: ...
$data = array(
'pages' => $pages,
'tasks' => $this->prepared,
'page' => $_SESSION['args']['page'],
'sort' => ltrim($_SESSION['args']['sort'], '-'),
'message' => empty($_SESSION['flash']['message']) ? null : $_SESSION['flash']['message'],
'inout_string' => UserAuth::isUserAuthenticated() ? 'out' : 'in',
'sort_invert' => $this->sortInvert ? '-' : '',
'current_path' => Url::getCurrentPath(),
'base_path' => Url::getBasePath(),
);
$this->view('list', $data);
}
// EXPLAIN: Create new task
public function create() : void
{
// EXPLAIN: ...
if (!empty($_POST) && $this->validate())
{
$task = new Task();
if ($task->create($_POST))
{
$_SESSION['flash']['message'] = 'Task has been successfully created';
$_SESSION['args']['sort'] = '-id';
$this->redirect();
}
}
// EXPLAIN: ...
$data = [
'message' => empty($_SESSION['flash']['message']) ? null : $_SESSION['flash']['message'],
'form_action' => Url::getCurrentPath(),
'basepath' => Url::getBasePath(),
];
$this->view('create', $data);
}
// EXPLAIN: ...
public function update() : void
{
// EXPLAIN: ...
if (UserAuth::isUserAuthenticated())
{
// EXPLAIN: ...
if (!empty($_GET['id']))
{
$task = Task::get($_GET['id']);
// EXPLAIN: ...
if (!empty($task) && !empty($_POST) && $this->validate())
{
if ($_POST['task_text'] === $task->getText())
{
$_SESSION['flash']['message'] = 'Nothing changed, not updated';
$this->refresh();
}
if ($task->update($_POST))
{
$_SESSION['flash']['message'] = 'Task has been successfully updated';
$this->refresh();
}
}
// EXPLAIN: ...
$data = array(
'task' => $task,
'message' => empty($_SESSION['flash']['message']) ? null : $_SESSION['flash']['message'],
'form_action' => Url::getCurrentPath() . '&id=' . $task->getId(),
'basepath' => Url::getBasePath(),
);
$this->view('update', $data);
}
else
{
$_SESSION['flash']['message'] = 'ID provided is bad';
$this->redirect();
}
}
else
{
$_SESSION['flash']['message'] = 'You do not have enough rights';
$this->redirect();
}
}
// EXPLAIN: ...
public function finalize() : void
{
if (UserAuth::isUserAuthenticated())
{
// EXPLAIN: ...
if (!empty($_POST['id']) && ($task = Task::get($_POST['id'])))
{
// EXPLAIN: ...
if ($task->update(['task_status' => Task::STATUS_COMPLETED]))
{
$_SESSION['flash']['message'] = 'Task #' . $task->getId() . ' has been successfully completed';
}
}
}
else
{
$_SESSION['flash']['message'] = 'You do not have enough rights';
}
}
// EXPLAIN: ...
protected function validate() : bool
{
if (empty($_POST['task_usermail']) || empty($_POST['task_name']) || empty($_POST['task_text']))
{
$_SESSION['flash']['message'] = 'Please, fill in all fields.';
return false;
}
if (!Validator::is_email($_POST['task_usermail']))
{
$_SESSION['flash']['message'] = 'Email seems to be invalid, - please, check if you spell it correctly.';
return false;
}
if (!Validator::is_alnum($_POST['task_name']))
{
$_SESSION['flash']['message'] = 'Task name must contain letters and digits only.';
return false;
}
return true;
}
}
|
JavaScript
|
UTF-8
| 1,087 | 4.78125 | 5 |
[] |
no_license
|
// Chapter 5 - Linked Lists
// Setting up/Assumptions:
// Function for creating a new node:
function ListNode(value){
this.val = value;
this.next = null;
}
// Function for creating a new list:
function List(){
this.head = null;
}
// Call to list function to instantiate a new list object
myList = new List();
// create 4 new nodes
newNode = new ListNode(8);
newNode1 = new ListNode(9);
newNode2 = new ListNode(10);
newNode3 = new ListNode(11);
// set head to equal newNode (val = 8)
myList.head = newNode;
// chain other nodes together in linked list
newNode.next = newNode1;
newNode1.next = newNode2;
newNode2.next = newNode3;
function reverse(list){
var first = list.head;
var second = first.next;
// first
var temp = second.next;
second.next = first;
first = second;
second = temp;
// second
temp = second.next;
second.next = first;
first = second;
second = temp;
// third
temp = second.next;
second.next = first;
first = second;
second = temp;
// break loop
list.head.next = null;
list.head = first;
console.log(list.head.next)
}
reverse(myList);
|
Python
|
UTF-8
| 616 | 2.921875 | 3 |
[] |
no_license
|
from gamesprite import GameSprite
from settings import Settings
class Background(GameSprite):
"""背景精灵组,让背景图移动起来"""
def __init__(self, is_alt=False):
super().__init__("images/backgroud.png")
if is_alt:
self.rect.y = -self.rect.height
self.settings = Settings()
def update(self):
# 调用父类的update方法
super().update()
# 判断是否移出屏幕,如果移出屏幕,将图像设置到屏幕的上方
if self.rect.y >= self.settings.SCREEN_RECT.height:
self.rect.y = -self.rect.height
|
Markdown
|
UTF-8
| 498 | 3.375 | 3 |
[] |
no_license
|
### Lectura por teclado
Para que el usuario pueda igresar los datos se utiliza:
```
input()
```
Para convertir los valores basta con:
```
str = input("Ingresa un valor --> ")
15
Si queremos sumar un valor a ese 15, tendremos un error. Debemos convertir ese valor.
str = int(valor)
str + 45 #60
De ser necesario puede utilizarse:
float()
```
Para especificar un valor desde el input, puede realizarse de la sig manera:
```
entero = int(input("Ingresa un número entero --> "))
```
|
Java
|
UTF-8
| 621 | 2.09375 | 2 |
[] |
no_license
|
package casestudy.javaweb.persistence.repository;
import casestudy.javaweb.persistence.entity.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ServiceRepository extends PagingAndSortingRepository<Service,Long> {
Page<Service> findByServiceType_Name(String name, Pageable pageable);
Page<Service> findByNameContaining(String name, Pageable pageable);
List<Service> findAll();
}
|
Java
|
UTF-8
| 645 | 3.3125 | 3 |
[] |
no_license
|
public abstract class Education
{
private String code;
private String title;
public Education(String code, String title) {
this.code = code;
this.title = title;
}
public String getCode() {
return code;
}
public String getTitle() {
return title;
}
public boolean equals (Object o) {
if (!(o instanceof Education)) {
return false;
} else {
Education other = (Education) o;
return other.code.equals(code) && other.title.equals(title);
}
}
public String toString() {
return "Education [code=" + code + ", title=" + title + "]";
}
}
|
Java
|
UTF-8
| 1,634 | 2.484375 | 2 |
[] |
no_license
|
package cloudSearch.search;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
/**
* Created by dan.houseman on 9/14/16.
*/
public class Hit {
public String id;
public Map<String, String> fields = new HashMap<String, String>();
public Integer getIntegerField(String field) {
Integer result = null;
if(fields.containsKey(field)) {
result = Integer.parseInt(fields.get(field));
}
return result;
}
public Long getLongField(String field) {
Long result = null;
if(fields.containsKey(field)) {
result = Long.parseLong(fields.get(field));
}
return result;
}
public Double getDoubleField(String field) {
Double result = null;
if(fields.containsKey(field)) {
result = Double.parseDouble(fields.get(field));
}
return result;
}
public String getField(String field) {
return fields.get(field);
}
public List<String> getListField(String field) throws JSONException {
List<String> result = null;
if(fields.containsKey(field)) {
String value = fields.get(field);
JSONArray array = new JSONArray(value);
if(array.length() > 0) {
result = new ArrayList<String>();
for(int i = 0; i < array.length(); i++) {
result.add(array.getString(i));
}
}
}
return result;
}
}
|
Java
|
UTF-8
| 230 | 2.015625 | 2 |
[] |
no_license
|
/*
* Cameron Boyd
* CECS 444
* Baby Scanner
*/
import java.io.IOException;
public class MyScannerClass {
public static void main(String[] args) throws IOException{
ScannerClass List = new ScannerClass();
List.initUI();
}
}
|
C++
|
UTF-8
| 1,035 | 3.5625 | 4 |
[] |
no_license
|
#include <iostream>
/*
Rat in a Maze - Backtracking
+------>(x)
|
|
v (y)
*/
const int SIZE = 4;
const int maze[SIZE][SIZE] = { { 1,1,0,1 },
{ 0,1,1,1 },
{ 0,0,0,1 },
{ 0,1,0,1 } };
bool isLegal(int x, int y) {
if (maze[x][y] == 0 || (x > SIZE || x < 0 || y < 0 || y > SIZE)) {
return false;
}
return true;
}
bool solveMaze(int x, int y, int sol[SIZE][SIZE]) {
if (x == (SIZE - 1) && y == (SIZE - 1)) { // Goal
sol[x][y] = 1;
return true;
}if (isLegal(x, y)) {
sol[x][y] = 1;
if (solveMaze(x + 1, y, sol))return true;
if (solveMaze(x, y + 1, sol))return true;
sol[x][y] = 0;//Backtrack
}
return false;
}
int main() {
int x = 0, y = 0;
int sol[SIZE][SIZE] = { { 0,0,0,0 },
{ 0,0,0,0 },
{ 0,0,0,0 },
{ 0,0,0,0 } };
if (!solveMaze(x, y, sol)) {
std::cout << "Impossible to solve" << std::endl;
}
else {
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
std::cout << sol[x][y];
}
std::cout << std::endl;
}
}
std::cin.get();
}
|
C++
|
UTF-8
| 11,115 | 3.15625 | 3 |
[] |
no_license
|
#include "cartelera.h"
Cartelera::Cartelera()
{
}
Cartelera::~Cartelera()
{
}
//Ingresa peliculas a la cartelera
void Cartelera::setCartelera(int _id, Pelicula _pelicula)
{
cartelera.insert(make_pair(_id, _pelicula));
}
//Retorna la cartelara con las peliculas
map<int, Pelicula> Cartelera::getCartelera()
{
return cartelera;
}
//Guarda la informacion de los puestos comprados para luego guardarla en un archivo
void Cartelera::setPuestosComprados(int _id, string _puestos)
{
map<int,vector<string>>::iterator iter;
bool oper = false; //Mira si el id ya existe en el mapa
for (iter = puestos_comprados.begin();iter!= puestos_comprados.end();iter++) {
if(iter->first == _id){
vector<string> temp = iter->second;
temp.push_back(_puestos);
puestos_comprados[_id] = temp; //Agrega un puesto a una pelicula ya registrada en el papa
oper = true;
}
}
if (oper == false){
vector<string> temp;
temp.push_back(_puestos);
puestos_comprados.insert(make_pair(_id, temp)); //Agrega una nueva pelicula con nuevos puestos reservados
}
}
//Iguala otra cartelera modificada
void Cartelera::actualizarCartelera(map<int, Pelicula> _temp)
{
cartelera = _temp;
}
//Muestra la cartelera de peliculas
void Cartelera::showCartelera()
{
map<int, Pelicula>::iterator iter;
string aux(100, '-');
string aux1(100, '*');
/*
cout<<aux<<endl;
cout<<" | ID | Nombre | Genero | Duracion | Sala | Hora | Asientos Disponibles | Clas. | Formato | ";
cout<<aux<<endl;
for(iter= cartelera.begin(); iter != cartelera.end();iter++){
cout<<" | "<<iter->first<<" | "<<iter->second.getNombre()<<" | "<<iter->second.getGenero()
<<" | "<<iter->second.getDuracion()<<" | "<<iter->second.getSala()<<" | "<<iter->second.getHora()
<<" | "<<iter->second.getAsientDisponible()<<"/"<<iter->second.getAsientTotal()<<" | "<<iter->second.getClasificacion()
<<" | "<<iter->second.getFormato()<<" |"<<endl;
}
*/
cout<<aux<<endl<<" | CARTELERA | "<<endl;
cout<<aux<<endl<<endl;
cout<<aux1<<endl<<endl;
for (iter = cartelera.begin(); iter != cartelera.end();iter++) {
cout<<aux<<endl;
cout<<" | ID | "<<iter->first<<" |"<<endl<<aux<<endl
<<" | Nombre | "<<iter->second.getNombre()<<" |"<<endl<<aux<<endl
<<" | Genero | "<<iter->second.getGenero()<<" |"<<endl<<aux<<endl
<<" | Duracion | "<<iter->second.getDuracion()<<" |"<<endl<<aux<<endl
<<" | Sala | "<<iter->second.getSala()<<" |"<<endl<<aux<<endl
<<" | Hora | "<<iter->second.getHora()<<" |"<<endl<<aux<<endl
<<" | Asientos Disponibles/Totales | "<<iter->second.getAsientDisponible()<<"/"<<iter->second.getAsientTotal()<<" |"<<endl<<aux<<endl
<<" | Clasificacion | "<<iter->second.getClasificacion()<<" |"<<endl<<aux<<endl
<<" | Formato | "<<iter->second.getFormato()<<" |"<<endl<<aux<<endl;
cout<<endl<<endl;
cout<<aux1<<endl;
}
}
//Elimina la pelicula seleccionada de acuerdo al id
void Cartelera::deletePelicula(int _id)
{
cartelera.erase(_id);
/*
map<int, Pelicula>::iterator iter;
for(iter= cartelera.begin(); iter != cartelera.end();iter++){
if(iter->first == _id){
cartelera.erase(_id);
}
}
*/
}
//Ingresa el nombre de los archivos donde se guarda el estado de la cartelera
void Cartelera::setDirArchivos(string _archivoCartelera, string _archivoPuestos)
{
archivoCartelera = _archivoCartelera;
archivoPuestos = _archivoPuestos;
}
//Guarda en archivos la informacion de la cartelera y los puestos comprados
void Cartelera::guardarEstadoCartelera()
{
ofstream archivoCartel;
archivoCartel.open(archivoCartelera.c_str(), ios::app);
if (archivoCartel.fail()){
cout<<"El archivo de la cartelera no se pudo abrir."<<endl;
exit(1);
}
string peli;
//unsigned int cont_map=1;
map<int, Pelicula>::iterator iter;
//LLena el string con la informacion que va en el archivo
for(iter= cartelera.begin(); iter != cartelera.end();iter++){
peli += to_string(iter->first) + ";" + iter->second.getNombre() + "/" + iter->second.getGenero() + "," + iter->second.getDuracion() + "," +
to_string(iter->second.getSala()) + "," + iter->second.getHora() + "," + to_string(iter->second.getAsientDisponible()) +
"," + to_string(iter->second.getAsientTotal()) + "," + iter->second.getClasificacion() + "," + iter->second.getFormato()
+":" + to_string(iter->second.getFila()) + "." + to_string(iter->second.getColumna()) + ".";
archivoCartel <<peli<<endl; //Guarda la informacion en el archivo
peli = "";
}
//cout<<"Se ha guardado la informacion de la cartelera con exito."<<endl;
archivoCartel.close();
}
void Cartelera::cargarEstadoCartelera()
{
int idd, sala=0, asien_dispon=0, asien_totales=0, fila = 0, columna = 0 ;
string nombre, genero, duracion, hora, clasificacion, formato;
ifstream archivoCar;
archivoCar.open(archivoCartelera.c_str(), ios::in);
if (archivoCar.fail()){
cout<<"No se pudo abrir el archivo con la cartelera."<<endl;
exit(1);
}
string linea;
while(!archivoCar.eof()){ //mientras no sea final del archivo.
getline(archivoCar,linea);
if (linea != ""){ //Comprueba que la linea no este vacia
unsigned int pos = linea.find(";");
idd = stoi(linea.substr(0,pos));
unsigned int postemp = linea.find("/");
nombre = linea.substr(pos+1,postemp-(pos+1));
pos = linea.find("/");
unsigned int i = pos+1;
int cont_coma = 0, cont_punto = 0; //Cuenta las ',' y los '.' para establecer los atributos
while (i < linea.size()){
if (linea[i] == ','){
unsigned int pos2 = i;
cont_coma++;
if (cont_coma == 1) genero = linea.substr(pos+1,pos2-(pos+1));
else if (cont_coma == 2) duracion = linea.substr(pos+1,pos2-(pos+1));
else if (cont_coma == 3) sala = stoi(linea.substr(pos+1,pos2-(pos+1)));
else if (cont_coma == 4) hora = linea.substr(pos+1,pos2-(pos+1));
else if (cont_coma == 5) asien_dispon = stoi(linea.substr(pos+1,pos2-(pos+1)));
else if (cont_coma == 6) asien_totales = stoi(linea.substr(pos+1,pos2-(pos+1)));
if (cont_coma == 7){
clasificacion = linea.substr(pos+1,pos2-(pos+1));
pos = pos2;
pos2 = linea.find(":");
formato = linea.substr(pos+1,pos2-(pos+1));
pos = pos2;
}else {
pos = i;
}
i++;
}
else if (linea[i] == '.') {
unsigned int pos2 = i;
cont_punto++;
if (cont_punto == 1) fila = stoi(linea.substr(pos+1,pos2-(pos+1)));
else if (cont_punto == 2) columna = stoi(linea.substr(pos+1,pos2-(pos+1)));
pos = i;
i++;
}
else {
i++;
}
}
Pelicula peli_temp (nombre, genero, sala, hora, fila, columna, duracion, clasificacion, formato);
//peli_temp.setAsientDisponible(asien_dispon);
cartelera.insert(make_pair(idd, peli_temp));
}
}
}
void Cartelera::guardarPuestos()
{
ofstream archivoPuesto;
archivoPuesto.open(archivoPuestos.c_str(), ios::app);
if (archivoPuesto.fail()){
cout<<"El archivo de la cartelera no se pudo abrir."<<endl;
exit(1);
}
string puestos;
map<int, vector<string>>::iterator iter;
//LLena el string con la informacion que va en el archivo
//unsigned int cont_map = 1;
for( iter= puestos_comprados.begin(); iter != puestos_comprados.end();iter++){
puestos += to_string(iter->first) + ";" ;
for (unsigned int i=0;i<iter->second.size();i++) {
puestos += iter->second[i] + ",";
}
archivoPuesto <<puestos<<endl; //Guarda la informacion en el archivo
puestos = "";
}
//cout<<"Se ha guardado la informacion de la cartelera con exito."<<endl;
archivoPuesto.close();
}
void Cartelera::cargarPuestos()
{
int idd=0, columna=0;
string fila;
ifstream archivoPues;
archivoPues.open(archivoPuestos.c_str(), ios::in);
if (archivoPues.fail()){
cout<<"No se pudo abrir el archivo con los puestos reservados."<<endl;
exit(1);
}
string linea;
while(!archivoPues.eof()){ //mientras no sea final del archivo.
getline(archivoPues,linea);
if(linea != ""){ //Comprueba que la linea no este vacia
unsigned int pos = linea.find(";"); //Toma la posicion entre el inicio y el ";" como el id de la pelicula
idd = stoi(linea.substr(0,pos));
unsigned int i = pos+1;
while (i < linea.size()){
if (linea[i] == ','){
unsigned int pos2 = i;
string lineatemp = linea.substr(pos+1, pos2-(pos2+1)); //Hace una sublinea con la fila y la conexion
unsigned int postemp = lineatemp.find(":");
fila = lineatemp.substr(0,postemp);
columna = stoi(lineatemp.substr(postemp+1));
pos = i;
i++;
//Reserva la el asiento que va encontrando con fila y columna
map<int,Pelicula>::iterator iter;
for (iter = cartelera.begin(); iter != cartelera.end();iter++) {
if(iter->first == idd){ //Busca que la pelicula exista
iter->second.reservar(fila,columna); //Hace la reservacion
string puesto = fila + ":" + to_string(columna);
setPuestosComprados(idd, puesto); //Guarda el puesto que se cargo como comprado
}
}
}
else {
i++;
}
}
}
}
}
|
Shell
|
UTF-8
| 7,192 | 3.9375 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
function info() {
datetime=`date "+%Y-%m-%d %H:%M:%S |"`
echo -e "\033[1;94m${datetime} INFO |\033[0m\033[0;94m $@ \033[0m"
}
function error() {
datetime=`date "+%Y-%m-%d %H:%M:%S |"`
echo -e "\033[1;91m${datetime} ERROR |\033[0m\033[1;91m $@ \033[0m" >&2
}
readonly DIR="$(cd $(dirname $(dirname $0)); pwd)"
if [ ! -f ${DIR}/bin/env.sh ] ; then
error "can not find file env.sh! exit process!"
exit 1
fi
source ${DIR}/bin/env.sh
if [ x"${HEALTH_KEY_WORDS}" = x ] ; then
error "application detecting key words must be defined! exit process!"
exit 1
fi
function find_jdk() {
target_jdk=""
max_build_version=0
for file in $(ls ${JDK_DIR})
do
if [ -d $(readlink ${file}) ] && [[ ${file} == ${JDK_VERSION}* ]] ; then
build_version=${file##${JDK_VERSION}_}
if [ "${build_version}" -gt "${max_build_version}" ] ; then
target_jdk=${file}
max_build_version=${build_version}
fi
fi
done
return 0
}
function check_env() {
info "check environment......"
JAVA_VERSION=$(java -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }')
if [[ ${JAVA_VERSION} == 1.8.0* ]] ; then
info "check JDK version successfully, jdk version: ${JAVA_VERSION}"
return 0
fi
find_jdk
if [ -z "${target_jdk}" ] ; then
if [ x"${DOWNLOAD_JDK}" = x"true" ]; then
info "downloading jdk package from repository......"
rm -rf ${DOWNLOAD_JDK_DIR}
mkdir -p ${DOWNLOAD_JDK_DIR}
curr_pwd=`pwd`
cd ${DOWNLOAD_JDK_DIR}
# Get Thirdparty Library (JDK1.8, Maven3.5.0 and Custom settings.xml)
# wget
tar -xzf ${DOWNLOAD_JDK_DIR}/output/${DOWNLOAD_JDK_PKG_NAME} -C ${JDK_DIR}
rm -rf ${DOWNLOAD_JDK_DIR}
cd ${curr_pwd}
find_jdk
fi
if [ -z "${target_jdk}" ] ; then
error "check environment failed, do not exist required ${JDK_VERSION} in dedicated directory ${JDK_DIR}"
return 1
fi
fi
info "setup JDK 1.8.0 environment......"
export JAVA_HOME=${JDK_DIR}/${target_jdk}
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:${PATH}
return 0
}
function check_running() {
info "check application whether in running......"
ps -ef | grep "${HEALTH_KEY_WORDS}" | grep -v 'grep' | grep -vq "${SUPERVISOR}"
return $?
}
function help_info() {
info "usage: ${0} <start | stop | restart | shutdown | status | install | help>"
}
function kill_process() {
info "kill processes......"
spids=$(ps -eo pid,command | grep "${SUPERVISOR}" | grep -v 'grep'| awk '{print $1}')
for spid in ${spids}
do
kill -9 ${spid}
if [ $? -ne 0 ] ; then
error "kill supervisor process(pid=${spid}) failed"
else
info "kill supervisor process(pid=${spid}) successfully"
fi
done
sleep 2
pids=$(ps -eo pid,command | grep "${HEALTH_KEY_WORDS}" | grep -v 'grep'| awk '{print $1}')
for pid in ${pids}
do
kill -9 ${pid}
if [ $? -ne 0 ] ; then
error "kill process(pid=${pid}) failed"
else
info "kill process(pid=${pid}) successfully"
fi
done
}
function term_process() {
info "terminate processes......"
spids=$(ps -eo pid,command | grep "${SUPERVISOR}" | grep -v 'grep'| awk '{print $1}')
for spid in ${spids}
do
kill -SIGTERM ${spid}
if [ $? -ne 0 ] ; then
error "terminate supervisor process(pid=${spid}) failed"
else
info "terminate supervisor process(pid=${spid}) successfully"
fi
done
sleep 2
pids=$(ps -eo pid,command | grep "${HEALTH_KEY_WORDS}" | grep -v 'grep'| awk '{print $1}')
for pid in ${pids}
do
kill -SIGTERM ${pid}
if [ $? -ne 0 ];then
error "terminate process(pid=${pid}) failed"
else
info "terminate process(pid=${pid}) successfully"
fi
done
}
function start()
{
if [ x"${START_CMD}" = x ] ; then
error "application start command must be defined! exit starting!"
exit 1
fi
install
info "start application......"
check_running
if [ $? -eq 0 ]; then
info "application is running"
return 0
fi
check_env
if [ $? -ne 0 ]; then
error "check environment failed"
return 1
fi
# start application
info "exec application process......"
if [ "x${SUPERVISOR}" = "x" ] ; then
exec ${START_CMD} >> ${LOG_DIR}/start.log
else
(setsid ${SUPERVISOR} >/dev/null 2>&1 &)
fi
sleep 5
for i in {1..10}
do
check_running
if [ $? -eq 0 ];then
break
else
if [ ${i} -eq 5 ];then
error "start application failed"
return 1
fi
sleep 10
fi
done
info "start application successfully"
return 0
}
function stop()
{
info "stop application......"
check_running
if [ $? -ne 0 ]; then
info "application is not running"
return 0
fi
for i in {1..10}
do
kill_process
sleep 1
check_running
if [ $? -ne 0 ]; then
info "stop application successfully"
return 0
fi
done
error "stop application failed"
return 1
}
function restart() {
stop
if [ $? -ne 0 ] ; then
return 1
fi
sleep 2
start
}
function shutdown() {
info "shutdown application......"
check_running
if [ $? -ne 0 ]; then
info "application is not running"
return 0
fi
for i in {1..10}
do
term_process
sleep 1
check_running
if [ $? -ne 0 ]; then
info "shutdown application successfully"
return 0
fi
done
error "shutdown application failed"
return 1
}
function status() {
info "get application status......"
check_running
if [ $? -eq 0 ]; then
info 'application is running'
return 0
else
info 'application is not running'
return 1
fi
}
function install() {
if [ "$(type -t install_internal)" == function ]; then
info "install appllication package......"
install_internal
fi
}
function main() {
cd ${HOME_DIR}
case "$1" in
start)
start
exit $?
;;
stop)
stop
exit $?
;;
restart)
restart
exit $?
;;
shutdown)
shutdown
exit $?
;;
status)
status
exit $?
;;
install)
install
exit $?
;;
help)
help_info
exit $?
;;
*)
help_info
exit 1
;;
esac
}
main $@
|
PHP
|
UTF-8
| 458 | 2.703125 | 3 |
[] |
no_license
|
<?php
require_once 'Harimau.php';
require_once 'Elang.php';
class Hewan{
public $nama,
$darah=50,
$jumlahKaki,
$keahlian;
public function atraksi(){
return $this->nama."Sedang".$this->keahlian;
}
}
echo $Harimau->atraksi();
echo "<br>";
echo $Elang->atraksi();
// $laricepat=$Harimau->nama.'sedang menyerang'.$Elang->nama;
// echo $laricepat;
?>
|
PHP
|
UTF-8
| 253 | 2.890625 | 3 |
[] |
no_license
|
<?php
namespace MrMe\Util;
class StringFunc
{
public static function GetX()
{
return ">>x<<";
}
public static function startWith($haystack, $needle)
{
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}
}
?>
|
Ruby
|
UTF-8
| 319 | 2.953125 | 3 |
[] |
no_license
|
class Frequency
def format(freq_pool,min,max)
output = []
freq_pool.each do |entry|
if entry < min
output << min
elsif
entry > max
output << max
else
output << entry
end
end
return output
end
end
|
Markdown
|
UTF-8
| 10,866 | 3.21875 | 3 |
[] |
no_license
|
# [Kaggle] New York texi-trip duration
*<div style="text-align: center;" markdown="1">`EDA` `regression` `clustering` `scikit-learn` `numpy` `pandas`</div>*
## Introduction
This is the [competition](https://www.kaggle.com/c/nyc-taxi-trip-duration) of the machine learning. The data is the travel information for the New York texi. The prediction is using the **regression** method to predict the trip duration depending on the given variables. The variables contains the locations of pickup and dropoff presenting with latitude and longitude, pickup date/time, number of passenger etc.... The design of the learning algorithm includes the preprocess of feature explaration and data selection, modeling and validation. To improve the prediction, we have done several test for modeling and feature extraction. Here we give the summery of the results.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/SESNTXJ.jpg" height="250"></div>
## Techniques
The procedure in this study includes the [feature exploration](#1-feature-exploration), [clustering](#2-clustering) and [modeling](#3-modeling). The feature selection is dealing with the noice which is possible to contaminate the prediction. Since less of the domain knowledges, the data was selected by visiulizing the data and observed the distribution of each features. The following figuresshows the pickup location from the training data.
### 1. Feature exploration
The features in dataset are actually less, and some of them are noisy during the data-taking. Before training the model, it is better to explore the much useful feature and veto the noise. However, we believe those relevant information is hiding behind the data, e.g. the distance, direction or density, we made several statistical studies to extract those additional features. Except for searching from the original data, the extra knowledge is also added for the model trianing which is from the other studies by the expert of this domain. These studies, called ***explanatory data analysis (EDA)*** , improve the final prediction of the trained model. The summerized selection is as following list, and the details are described in the subsections.
- 300 < Trip duration < 7200 (sec.)
- Veto date : 2016.01.20 ~ 2016.01.25
- 0.6 < Distance < 11 (Km)
- 5 < speed < 120 (Km/hr)
- 1 < Number of passenger < 7
#### 1.1. Time and duration
The pickup datatime is recored in both training and test dataset, while the dropoff and duration are only shown in training dataset. We analyzed the datetime by observing the distribution of month, week, day and the clock. The distrubtion of date shows the strange drop between January 20th to 25th, since the big snow was in New York which course the trafic problem.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/wE36EGn.png" height="200"></div>
On the other hand, the training data with the large duration is discarded by the observation, since we believe those data are the outlier from the prediction for New York City. The selection is set larger than 2 minute and lower than 2 hours.
#### 1.2. Distance, speed and direction
The locations, speed and direction are expected to be strongly correlated to duration, especially the distance. We can use the coordinates of each pickup and dorpoff to overlook the scattering map of New York City. The important feature quickly shown up is the densities of pickup and dropoff location.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/LcXLVn1.png" height="300"></div>
The most of dense regions are in the city center and two airports. The direction from pickup to dropoff may point out the popular locations, especailly bewteen city center to airport, which can effect the duration prediction. Thus, we estimated the direction as
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/5BQDR2i.png" height="300"></div>
Moreover, the distance between dropoff and pickup are calculated with *haversine* distance, i.e.
$$
d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\ ,
$$
where it presents the distance between point 2 to 1. From the distrubtion, we found that a few of training data are out of the New York city, and the distance are extremely large. Thus, we only consider the data containing the distance in the coverage of 95% of the training dataset, assuming the distribution of distance is the gaussian distribution. In the end, there are duration information in training dataset, we simply calculated the average speed. The speed information provide the information of the noisy data. The data containing the speed between 5 and 120 (km/hr) are only used for training.
#### 1.3. Passenger
According the distrubtion of passengers, it appears the overcounting issue which is out of the normal texi's capacity. Thus, the data has to be appilied the selection of passengers between above 0 and less than 7.
#### 1.4. Extra feature - right/left turns
By adding the extra data, [Open Source Routing Machine (OSRM)](https://www.kaggle.com/oscarleo/new-york-city-taxi-with-osrm/kernels), it gives the additional information about the traffic for each route of data. Here we use the steps of the turns during the texi driving for model training, i.e. the number of right and left turns. The turn is expected to affect duration, since the time cost for right and left turn is different. For the *right-hand traffic (RHT)* city, e.g. New York City and Taipei, the right turn is much efficient than the left turn, hence the duration with less left turns is much smaller with respect to the same distance.
### 2. Clustering
We have studied the different clustering algorithms to quantify or labelize the pickup and dropoff locations, e.g. the ***k-means*** algorithm and ***density pixels*** which made by statistical studies. Since the limited competition dateline and manpower, the ***density pixels*** wasn't compeletily finished, the performance is similar with *k-mean* algorithm for the choosen training model. Thus, the final prediction is using *k-means* to do feature extraction.
#### 2.1. K-means
The ***k-means*** algorithm one of choise to ensemble the data and labelizes the locations. The important feature of the algorithm is it is clustering the data by looking for the *k* clusters (sets), which the data in the set has the minimum error with respect to set's mean. In the case for clustering the locations by the coordinates, it can represent the *k* regions having different density. However, we didn't optimize the number of cluster, the value of regions is set 100. The following left-hand figure shows the coverage regions in prediction. The left-hand figure shows the clustering results applied to data.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/vZH0haY.png" height="300"><img src="https://i.imgur.com/rS8uXYG.png" height="320"></div>
#### 2.2. Density pixels
The method is trying to give the meaningful value for training models instead of labelizing. By using the physics sence, we caculate the density from the pickup and dropoff cooredinates with respect to the fixed bin sizes of maps, we call they are *"pixels"*. Each pixel has different value which present how often the texi pickup and dropoff in the region. The results can be shown as heat map as following figure; the right-hand figures present in the linear scale, while the left-hands present log scale; the top figures are for the pickup cases, while the bottoms are for the dropoff cases.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/XBYu30C.png" height="500"></div>
Of course, the bin size can optimize as a supper parameter of clustering. We can expected either the large or the small bin sizes may give the missleading of the model training. The interesting feature we have found, the density difference between pickup and dropoff presnt with nomal distrubtion as following figure.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/QiHLVpR.png" height="250"></div>
It shows there is the certain frequence of trips between two regions. Thus, we take the absolute value of the difference and comparing the duration as the following figure.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/ySW9vxr.png" height="300"></div>
The correlation tells the story, which can be easily understood, the long duration is most from the city center to not popular region, while the short duration can be inside the city center where the densities almost in common. On the orther hand, we also cauclate the average speed in each region which the average speed can give the expectation of the duration. However, this method is pushing to human learning by statistical analysis instead of the machine learning, we didn't go deep in the end.
### 3. Modeling
Since the dimension of provided features in data is not many, and the data is noisy, we decided use the ***tree*** learning algorithm as the training model. Two tree algorithms, **random forest** and **boosted decision tree (BDT)**, have been compared, BDT is used for our final fit. As metioned in begin of [clustering](#2-Clustering), the *k-means* algorithm is used for location imformation, since labelization algorithm does not need to be apllied one-hot-code for tree algorithm. It make the [*k-means*](#21-K-means) is much easier to be implemented than *density pixel* method.
The public ***RMSLE*** score of the model without applying the [*OSRM*](#14-Extra-feature---rightleft-turns) is 0.39, and it is improved to 0.38 after the application. The *RMSLE* score, i.e. *Root Mean Squared Logarithmic Error*, is defined as
$$
\epsilon_{RMSLE}=\sqrt{\frac{1}{n}\sum_{i=1}^n\left(\ln(p_i+1)-\ln(a_i-1)\right)^2}\ ,
$$
where $n$ is the total number of observations in the dataset; $p_i$ is the prediction, while $a_i$ is the actual value.
The model is validated by checking the learning curve between test and training dataset with **n-fold cross validation**, it shows no overfitting issue exist. The training epoch is shown in following figure.
<div style="text-align: center;" markdown="1"><img src="https://i.imgur.com/iv1MYmF.png" height="400"></div>
<!-- kernel svm regression + stokastic -->
## Results
The final $\epsilon_{RMSLE}$ on Kaggle private dataset is 0.37. The score is in the top %8 of 1257 teams. Obviously, the results still can be improved by modeling or feature exploration.
## Reference
- [Kaggle - New York City Taxi Trip Duration](https://www.kaggle.com/c/nyc-taxi-trip-duration)
- Team Github : https://github.com/yennanliu/NYC_Taxi_Trip_Duration
- Personal Github : https://github.com/juifa-tsai/NYC_Taxi_Trip_Duration
- [Calculate distance, bearing and more between Latitude/Longitude points](https://www.movable-type.co.uk/scripts/latlong.html)
|
JavaScript
|
UTF-8
| 4,534 | 3.359375 | 3 |
[] |
no_license
|
var cars = [];
var picture = []; // an array for the objects
var frogPos;
let state = -1;
let timer = 0;
let img1;
let img2;
let bubbles;
let gamebg;
let song1, song2, song3;
let maxBirds = 10;
let font;
function preload() {
song1 = loadSound("assets/1.mp3");
song2 = loadSound("assets/2.mp3");
song3 = loadSound("assets/3.mp3");
song1.loop();
song1.loop();
song1.loop();
song1.pause();
song2.pause();
song3.pause();
// font = loadFont("assets/.......") ;
}
function setup() {
// createCanvas(446, 311);;
createCanvas(892, 622);;
// textFont(font, 16);
img1 = loadImage("assets/2.jpeg");
img2 = loadImage("assets/1.jpg");
bubbles = loadImage("assets/bubbles.png");
gamebg = loadImage("assets/gamebg.png");
//
picture[0] = loadImage("assets/hmbb.png");
picture[1] = loadImage("assets/zyg.png");
// spawn the objects
for (let i = 0; i < maxBirds; i++) {
cars.push(new Car()); // put the objects onto the cars array
}
frogPos = createVector(width / 2, height - 120);
rectMode(CENTER);
ellipseMode(CENTER);
imageMode(CENTER);
}
function draw() {
switch (state) {
case -1:
song1.play();
state = 0;
break;
case 0:
background('grey');
image(img2, width / 2, height / 2, width, height);
fill('black');
text("welcome to my game!", 150, 200);
break;
case 1: //game state
game();
timer++;
if (timer > 500) {
state = 3;
stopTheSongs();
song3.play();
timer = 0;
}
break;
case 2:
background('pink');
image(img2, width / 2, height / 2, width, height); // put image here
fill('black');
text("You won!!!", 150, 200);
break;
case 3:
background('blue');
image(img1, width / 2, height / 2, width, height); // put image here
fill('black');
text("Sorry,you are lost,try again!", 150, 200);
break;
}
}
function reset() {
cars = [];
timer = 0;
// spawn the objects
for (let i = 0; i < maxBirds; i++) {
cars.push(new Car()); // put the objects onto the cars array
}
}
function stopTheSongs() {
song1.pause();
song2.pause();
song3.pause();
}
function resetTheGame() {
cars = [];
// spawn cars!!!
for (var i = 0; i < maxBirds; i++) {
cars.push(new Car());
}
timer = 0;
}
function mouseReleased() {
switch (state) {
case 0: // click to go to the game state
stopTheSongs();
song2.play();
state = 1;
break;
case 2: // the win state!
stopTheSongs();
resetTheGame();
state = -1;
break;
case 3: // the lose myState
stopTheSongs();
resetTheGame();
state = -1;
break;
}
}
function game() {
background('white');
image(gamebg, width / 2, height / 2, width, height);
// iterate through the array, display them, update them
for (let i = 0; i < cars.length; i++) {
cars[i].display();
cars[i].update();
if (cars[i].pos.dist(frogPos) < 50) {
cars.splice(i, 1); //delate a car
}
}
// check if therenare any cars left
if (cars.length == 0) {
state = 2; //go to win state}
}
// draw a "frog" here
fill('green');
// ellipse(frogPos.x, frogPos.y, 70, 70) ;
image(picture[0], frogPos.x, frogPos.y, 70, 70);
// checkForKeys() ;
frogPos.x = mouseX;
frogPos.y = mouseY;
}
function checkForKeys() {
if (keyIsDown(LEFT_ARROW)) frogPos.x -= 5;
if (keyIsDown(RIGHT_ARROW)) frogPos.x += 5;
if (keyIsDown(UP_ARROW)) frogPos.y -= 5;
if (keyIsDown(DOWN_ARROW)) frogPos.y += 5;
}
// this is the Car class!
class Car {
constructor() {
// attributes
this.pos = createVector(random(width), random(height)); // where it starts
this.vel = createVector(random(-3, 3), random(-3, 3)); // direction
this.r = random(255);
this.g = random(255);
this.b = random(255);
this.a = random(255);
}
// methods
display() { // this displays the object
// fill(this.r, this.g, this.b, this.a);
// ellipse(this.pos.x, this.pos.y, 30, 30);
image(bubbles, this.pos.x, this.pos.y, 100, 100);
}
update() { // this moves the object
this.pos.add(this.vel); // add the velocity to the position
// loop the objects around the screen
if (this.pos.x > width) this.pos.x = 0;
if (this.pos.x < 0) this.pos.x = width;
if (this.pos.y > height) this.pos.y = 0;
if (this.pos.y < 0) this.pos.y = height;
}
}
function touchStarted() {
getAudioContext().resume();
}
|
C++
|
UHC
| 375 | 2.734375 | 3 |
[] |
no_license
|
// 3_ ø Ȱ
#include <iostream>
//
template<typename T> struct xremove_pointer
{
typedef T type;
};
template<typename T> struct xremove_pointer<T*>
{
//typedef T type;
typedef typename xremove_pointer<T>::type type;
};
int main()
{
xremove_pointer<int***>::type n;
std::cout << typeid(n).name() << std::endl;
}
|
Python
|
UTF-8
| 2,700 | 3.890625 | 4 |
[] |
no_license
|
"""
https://leetcode.com/problems/minimum-window-substring/
"""
import collections
import unittest
from typing import Counter
class Solution:
def minWindow(self, s: str, t: str) -> str:
"""
need : 필요한 문자 각각의 개수
missing : 필요한 문자의 전체 개수
left : 슬라이딩 윈도우의 왼쪽 index
right : 슬라이딩 윈도우의 오른쪽 index
start : 정답 왼쪽 index
end : 정답 오른쪽 index
"""
need: Counter = collections.Counter(t)
missing: int = len(t)
left: int = 0
start: int = 0
end: int = 0
# 오른쪽 포인터 이동
# enumerate(s, 1)은 1부터 인덱스가 시작한다는 뜻
for right, char in enumerate(s, 1):
"""
오른쪽 포인터(right) 값을 계속 늘려 나간다.
슬라이딩 윈도우의 크기가 점점 더 커지는 형태가 된다.
먄약 현재 문자가 필요한 문자 need[char]에 포함되어 있다면
필요한 문자의 전체 개수 missing을 1 감소하고,
해당 문자의 필요한 개수 need[char]도 1 감소한다.
"""
missing -= need[char] > 0
need[char] -= 1
"""
필요 문자가 0이면 왼쪽 포인터 이동 판단
왼쪽 포인터가 불필요한 문자를 가리키고 있다면 분명 음수일 것이고,
0을 가리키는 위치까지 왼쪽 포인터를 이동한다.
다시 슬라이딩 윈도우의 크기가 점점 더 줄어드는 형태가 된다.
missing이 0이 될 때까지의 오른쪽 포인터와 need[s[left]]가 0이 될 때까지의
왼쪽 포인터를 정답으로 정한다.
더 작은 값을 찾을 때까지 유지하다가 가장 작은 값인 경우,
정답으로 슬라이싱 결과를 리턴한다.
"""
if missing == 0:
while left < right and need[s[left]] < 0:
need[s[left]] += 1
left += 1
if not end or right - left <= end - start:
start, end = left, right
need[s[left]] += 1
missing += 1
left += 1
return s[start:end]
class TestSolution(unittest.TestCase):
def test_result(self):
s = Solution()
self.assertEqual(s.minWindow(s="ADOBECODEBANC", t="ABC"), "BANC")
self.assertEqual(s.minWindow(s="a", t="a"), "a")
self.assertEqual(s.minWindow(s="a", t="aa"), "")
if __name__ == "__main__":
unittest.main()
|
Java
|
UTF-8
| 5,269 | 3.328125 | 3 |
[] |
no_license
|
import java.io.*;
import java.util.HashMap;
public class WikiParser {
// Assume default encoding.
private static FileWriter fileWriter;
private static FileWriter fileWriter2;
// Always wrap FileWriter in BufferedWriter.
private static BufferedWriter bufferedWriter;
private static BufferedWriter bufferedWriter2;
private static HashMap<String,String> pagesThatHasCategory = new HashMap<String, String>();
public static void main(final String[] args) throws IOException {
//Oppretter en fil for alle artiklene og en for kantene
fileWriter = new FileWriter("articles.txt");
fileWriter2 = new FileWriter("edges.txt");
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter2 = new BufferedWriter(fileWriter2);
//Setter opp headeren i hver fil
fileNodeDefSetup(bufferedWriter);
fileEdgeDefSetup(bufferedWriter2);
final int[] nameKey = {1};
XMLManager.load(new PageProcessor(){
@Override
public void process(Page page){
//Lagrer kun sider som har rett kategori
if (page.getTitle() != null && page.getCategories().size() > 0) {
writeArticleToFile(nameKey[0], page);
for (String link : page.getLinks()) {
writeArticleEdgeToFile(page.getTitle(), link);
}
pagesThatHasCategory.put(page.getTitle(), page.getTitle());
nameKey[0]++;
}
}
});
bufferedWriter.close();
//Setter samme de to forrige filene til en GDF fil
createGDFFile();
}
private static void createGDFFile() throws IOException {
FileReader fileReader = new FileReader("articles.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileReader fileReader2 = new FileReader("edges.txt");
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
FileWriter fileWriter = new FileWriter("wikipediaGraph.gdf");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String articleLine = bufferedReader.readLine();
while(articleLine != null){
bufferedWriter.write(articleLine);
bufferedWriter.newLine();
articleLine = bufferedReader.readLine();
}
String edgeLine = bufferedReader2.readLine();
int teller = 0;
while(edgeLine != null){
//Henter ut nodeinformasjonene
String[] felt = edgeLine.split(",");
if(felt.length > 2) {
//Viss vi er på første linje, så skal vi skrive infoen (teller == 0)
//Ellers må node2 være en side som har rett kategori
if ((teller == 0 || pagesThatHasCategory.containsKey(felt[1]))){
bufferedWriter.write(edgeLine);
bufferedWriter.newLine();
teller++;
}
}
edgeLine = bufferedReader2.readLine();
}
}
private static void fileEdgeDefSetup(BufferedWriter bufferedWriter) {
try {
bufferedWriter.write("edgedef>node1 VARCHAR,node2 VARCHAR,directed BOOLEAN");
bufferedWriter.newLine();
}catch (Exception e){
e.printStackTrace();
}
}
private static void fileNodeDefSetup(BufferedWriter bufferedWriter) {
try {
bufferedWriter.write("nodedef>name VARCHAR,label VARCHAR,category1 VARCHAR," +
"category2 VARCHAR,category3 VARCHAR");
bufferedWriter.newLine();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* Skriver en artikkel med gitt artikkelnummer til filen articles.txt
* Skriver i rett format, der hver side kan ha alt fra 1 - 3 kategorier
*
*/
public static void writeArticleToFile(int articleNr, Page page){
try {
if(page.getCategories().size() == 1){
bufferedWriter.write("article" + articleNr + "," + page.getTitle() + "," + page.getCategories().get(0)
+ ", , ");
}else if(page.getCategories().size() == 2){
bufferedWriter.write("article" + articleNr + "," + page.getTitle() + "," + page.getCategories().get(0)
+ "," + page.getCategories().get(1) + ", ");
}else{
bufferedWriter.write("article" + articleNr + "," + page.getTitle() + "," + page.getCategories().get(0)
+ "," + page.getCategories().get(1) + "," + page.getCategories().get(2));
}
bufferedWriter.newLine();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
/**
* Tar inn to noder og skriver det til filen edge.txt på rett format
* Setter at dette er en directed kant
*
*/
public static void writeArticleEdgeToFile(String node1, String node2){
try{
bufferedWriter2.write(node1 + "," + node2 + "," + "true");
bufferedWriter2.newLine();
}catch (Exception e){
e.printStackTrace();
}
}
}
|
Markdown
|
UTF-8
| 994 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
## vddl-handle
在`vddl-nodrag`元素中使用`vddl-handle`组件,以便允许拖动该元素。 因此,通过组合`vddl-nodrag`和`vddl-handle`,您能制定自定义的句柄元素(handle)拖动`vddl-draggable`元素。
#### 基本用法
```html
<vddl-draggable v-for="(item, index) in list" :key="item.id"
:draggable="item"
:index="index"
:wrapper="list"
effect-allowed="move">
<vddl-nodrag class="nodrag">
<vddl-handle
:handle-left="20"
:handle-top="20"
class="handle">
</vddl-handle>
<div>{{item.label}}</div>
</vddl-nodrag>
</vddl-draggable>
```
#### 属性
使用`handle-left`或`handle-top`属性可以帮助你自定义拖动项的位置。
> Internet Explorer 将把 handle 元素显示为拖动图像而不是`vddl-draggable`元素。 您可以通过在拖动时对句柄元素进行不同的样式设计来解决此问题。 使用CSS选择器`.vddl-dragging:not(.vddl-dragging-source).vddl-handle`。
|
C
|
UTF-8
| 1,857 | 2.671875 | 3 |
[] |
no_license
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <errno.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while (0);
int main(int argc, char const *argv[])
{
int sock;
if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
ERR_EXIT("socket");
}
struct sockaddr_in server_addr;
int srvlen;
memset(&server_addr, 0, sizeof server_addr);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5188);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
struct sockaddr_in localaddr;
socklen_t addrlen = sizeof localaddr;
if (getsockname(sock, (struct sockaddr*)&localaddr, &addrlen) < 0)
{
ERR_EXIT("getsockname");
}
printf("id = %s, ", inet_ntoa(localaddr.sin_addr));
printf("port = %d\n", ntohs(localaddr.sin_port));
char sendbuf[1024];
char recvbuf[1024];
int ret;
while (fgets(sendbuf, sizeof sendbuf, stdin) != NULL)
{
srvlen = sizeof server_addr;
sendto(sock, sendbuf, sizeof(sendbuf), 0, (struct sockaddr *)&server_addr, srvlen);
// cout << sendbuf << endl;
ret = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, NULL, NULL);
if (ret == -1) {
if (errno == EINTR) {
continue;
}
ERR_EXIT("recvfrom")
}
else if (ret > 0)
{
fputs(recvbuf, stdout);
// sendto(sock, recvbuf, n, 0, (struct sockaddr *)&peeraddr, peerlen);
}
memset(sendbuf, 0, sizeof sendbuf);
memset(recvbuf, 0, sizeof recvbuf);
}
return 0;
}
|
Java
|
UTF-8
| 1,245 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
package teamOD.armourReborn.common.leveling;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
/**
* This interface is to be implemented by all armour items that are levelable.
* @author MightyCupcakes
* @see ItemModArmour
*
*/
public interface ILevelable {
public static final String TAG_LEVEL = "ArmourLevel" ;
public static final String TAG_EXP = "ArmourExp" ;
public static final int MAX_LEVEL = ModLevels.getMaxLevel() ;
/**
* Associates the base EXP and LEVEL tags to this armour
* @param tag
*/
public void addBaseTags (NBTTagCompound tag) ;
public boolean isMaxLevel (NBTTagCompound tags) ;
/**
* This SETS the exp of an Ilevelable owned by player to armourXP
* @param armour
* @param player
* @param armourXP
*/
public void setExp (ItemStack armour, EntityPlayer player, int armourExp) ;
public void addExp (ItemStack armour, EntityPlayer player, int armourExp) ;
public int getLevel (ItemStack armour) ;
/**
* Levels the armour up after meeting some requirements set by the above functions
* @param armour
* @param player
*/
public void levelUpArmour (ItemStack armour, EntityPlayer player) ;
}
|
Go
|
UTF-8
| 3,090 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package helpers
import (
"github.com/aerogear/mobile-security-service/pkg/models"
"github.com/google/uuid"
)
//GetMockUser returns a dummy user
func GetMockUser() *models.User {
user := &models.User{
Username: "TestUser",
Email: "[email protected]",
}
return user
}
// GetMockAppList returns some dummy apps
func GetMockAppList() []models.App {
apps := []models.App{
models.App{
ID: "7f89ce49-a736-459e-9110-e52d049fc025",
AppID: "com.aerogear.mobile_app_one",
AppName: "Mobile App One",
},
models.App{
ID: "7f89ce49-a736-459e-9110-e52d049fc026",
AppID: "com.aerogear.mobile_app_three",
AppName: "Mobile App Two",
},
models.App{
ID: "7f89ce49-a736-459e-9110-e52d049fc027",
AppID: "com.aerogear.mobile_app_three",
AppName: "Mobile App Three",
},
}
return apps
}
//GetMockApp returns a dummy app
func GetMockApp() *models.App {
versionlist := GetMockAppVersionList()
app := &models.App{
ID: "7f89ce49-a736-459e-9110-e52d049fc027",
AppID: "com.aerogear.mobile_app_one",
AppName: "Mobile App One",
DeployedVersions: &versionlist,
}
return app
}
// GetMockAppVersionList returns some dummy app versions
func GetMockAppVersionList() []models.Version {
versions := []models.Version{
models.Version{
ID: "55ebd387-9c68-4137-a367-a12025cc2cdb",
Version: "1.0",
AppID: "com.aerogear.mobile_app_one",
DisabledMessage: "Please contact an administrator",
Disabled: false,
NumOfAppLaunches: 2,
},
models.Version{
ID: "59ebd387-9c68-4137-a367-a12025cc1cdb",
Version: "1.1",
AppID: "com.aerogear.mobile_app_one",
Disabled: false,
NumOfAppLaunches: 0,
},
models.Version{
ID: "59dbd387-9c68-4137-a367-a12025cc2cdb",
Version: "1.0",
AppID: "com.aerogear.mobile_app_two",
Disabled: false,
NumOfAppLaunches: 0,
},
}
return versions
}
//Get version strut for the disable all.
func GetMockAppVersionForDisableAll() models.Version {
return models.Version{
DisabledMessage: "Please contact an administrator",
}
}
// GetMockDevice returns a mock device
func GetMockDevice() *models.Device {
return &models.Device{
ID: uuid.New().String(),
VersionID: uuid.New().String(),
AppID: "com.aerogear.testapp",
DeviceID: uuid.New().String(),
DeviceVersion: "8.1",
DeviceType: "Android",
}
}
// GetMockVersion returns a mock version
func GetMockVersion() *models.Version {
return &models.Version{
ID: uuid.New().String(),
Version: "1.0",
AppID: "com.aerogear.mobile_app_one",
DisabledMessage: "Please contact an administrator",
Disabled: false,
NumOfAppLaunches: 10000,
}
}
// GetMockDevices generates a slice of Devices
func GetMockDevices(number int) []models.Device {
var devices []models.Device
for i := 0; i < number; i++ {
d := GetMockDevice()
devices = append(devices, *d)
}
return devices
}
|
C#
|
UTF-8
| 833 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Web;
namespace Projector.Core.Logic.Utilities.MyLinq
{
public class MyList<T> : List<T>
{
public void ForEach(Action<T> action)
{
foreach(var item in this)
{
action(item);
}
var enumerator = this.GetEnumerator();
while (this.GetEnumerator().MoveNext())
{
var currentItem = this.GetEnumerator().Current;
action(this.GetEnumerator().Current);
}
}
public IEnumerable<TResult> Select<TResult>(Func<T,TResult> select)
{
return null;
}
//public TSelect Select(this IEnumerable<out T> list, Func<T,TSelect> selectFunc)
//{
//}
}
}
|
Python
|
UTF-8
| 1,089 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
from collections import defaultdict
import sys
import re
def extract(s):
return [int(x) for x in re.findall(r'\d+', s)]
def main(args):
data = sorted([extract(s) for s in sys.stdin])
i = 0
sleep_time = defaultdict(int)
most_common = defaultdict(lambda: defaultdict(int))
while i < len(data):
times = data[i]
guard = times[-1]
i += 1
while True:
if i >= len(data) or len(data[i]) == 6:
break
start = data[i][4]
stop = data[i+1][4]
sleep_time[guard] += (stop - start)
for j in range(start, stop):
most_common[guard][j] += 1
i += 2
amount, sleepy = max(((v, k) for k, v in sleep_time.items()))
amount, minute = max(((v, k) for k, v in most_common[sleepy].items()))
print(minute * sleepy)
amount, sleepy, minute = max((v, guard, minute) for guard, d in most_common.items() for minute, v in d.items())
print(minute * sleepy)
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
JavaScript
|
UTF-8
| 588 | 3.109375 | 3 |
[] |
no_license
|
module.exports = { isDateLower, isDateBetween, addDays };
function isDateLower(date1, date2) {
return new Date(date1).getTime() < new Date(date2).getTime();
}
function isDateBetween(date, dateFrom, dateTo) {
const date1 = new Date(date).getTime();
return (
date1 >= new Date(dateFrom).getTime() && date1 <= new Date(dateTo).getTime()
);
}
function addDays(date, nbDays) {
const result = new Date(
new Date(date).getTime() + nbDays * 24 * 60 * 60 * 1000
);
return dateToString(result);
}
function dateToString(date) {
return date.toISOString().split('T')[0];
}
|
Markdown
|
UTF-8
| 788 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
DarvinCrawlerBundle
===================
This bundle provides console command that detects broken links on your website.
## Sample configuration
```yaml
# config/packages/dev/darvin_crawler.yaml
darvin_crawler:
default_uri: https://example.com # Default value of command's "uri" argument
blacklists:
parse: # Content from URIs matching these regexes will not be parsed
- '/\/filtered\//'
visit: # URIs matching these regexes will not be visited
- '/\/filtered\//'
```
## Usage
Crawl default URI:
```shell
$ bin/console darvin:crawler:crawl
```
Crawl specified URI:
```shell
$ bin/console darvin:crawler:crawl https://example.com
```
Display all visited links:
```shell
$ bin/console darvin:crawler:crawl https://example.com -v
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.