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 |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 1,504 | 3.109375 | 3 | [] | no_license | import numpy as np
import pandas as pd
import itertools
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
df = pd.read_csv('news.csv')
# print(df.shape, df.head(), df.columns)
# (6335, 4) Index(['Unnamed: 0', 'title', 'text', 'label'], dtype='object')
x = df['text']
y = df['label']
# spliting data to 0.8 train 0.2 test
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.2, random_state=7)
# creating tfidfVectorizer with 0.7 to ignore terms with a higher document frequency will be discarded
tfidf_vectorizer = TfidfVectorizer(stop_words='english', max_df=0.7)
tfidf_train = tfidf_vectorizer.fit_transform(x_train)
tfidf_test = tfidf_vectorizer.transform(x_test)
# building PassiveAggressiveCalssifier model
pac = PassiveAggressiveClassifier(max_iter=50)
pac.fit(tfidf_train,y_train)
prediction = pac.predict(tfidf_test)
score = accuracy_score(y_test, prediction)
# Accuracy around 92.6%
print(f'Accuracy: {round(score*100, 2)}%\n')
# Confusion Matrix to gain insight into the number of false and true negatives and positives
con_matrix = confusion_matrix(y_test, prediction, labels=['FAKE', 'REAL'])
print(f'True Positive:\t{con_matrix[0][0]}')
print(f'False Positive:\t{con_matrix[0][1]}')
print(f'True Negative:\t{con_matrix[1][0]}')
print(f'False Negative:\t{con_matrix[1][1]}') |
SQL | ISO-8859-1 | 1,273 | 4.1875 | 4 | [] | no_license | # a) Listar todos os livros publicados aps 2014
SELECT * FROM LIVRO WHERE YEAR(Publicacao) > 2014;
# b) Listar os 10 livros mais caros
SELECT Valor FROM LIVRO ORDER BY Valor DESC LIMIT 10;
# c) Listar as 5 editoras que mais tem livros na biblioteca
SELECT
CodEditora, Nome,
(SELECT
COUNT(L.Editora) FROM LIVRO L
WHERE L.Editora = E.CodEditora) AS CONTADOR
FROM EDITORA E
GROUP BY CodEditora ORDER BY CONTADOR DESC LIMIT 5;
# d)Listar a quantidade de publicaes de cada autor
SELECT
CodAutor, Nome,
(SELECT COUNT(*) FROM LIVRO L
WHERE L.Autor = A.CodAutor) AS CONTADOR
FROM AUTOR A
ORDER BY CodAutor;
# e)Listar a quantidade de publicaes de cada editora
SELECT
CodEditora, Nome,
(SELECT COUNT(*) FROM LIVRO L
WHERE L.Editora = E.CodEditora) AS CONTADOR
FROM EDITORA E
ORDER BY CodEditora;
#f) Listar qual o autor com mais publicaes
SELECT
CodAutor, Nome,
(SELECT COUNT(*) FROM LIVRO L
WHERE L.Autor = A.CodAutor) AS PUBLICACOES
FROM AUTOR A
ORDER BY PUBLICACOES DESC LIMIT 1;
#g) Listar qual o autor com menos ou nenhuma publicao
SELECT A.CodAutor, A.Nome, 0 publicacoes FROM AUTOR A
WHERE A.CodAutor NOT IN(SELECT L.Autor FROM LIVRO L)
|
Java | UTF-8 | 680 | 3.265625 | 3 | [] | no_license | import java.util.Scanner;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args){
Scanner teclado = new Scanner(System.in);
DecimalFormat teclado2 = new DecimalFormat("0.00");
int codigo1, numpecas1, codigo2, numpecas2;
double valorpeca1, valorpeca2, valort;
codigo1 = teclado.nextInt();
numpecas1 = teclado.nextInt();
valorpeca1 = teclado.nextDouble() * numpecas1;
codigo2 = teclado.nextInt();
numpecas2 = teclado.nextInt();
valorpeca2 = teclado.nextDouble() * numpecas2;
valort = valorpeca1 + valorpeca2;
System.out.println("VALOR A PAGAR: R$ " +teclado2.format(valort));
}
}
|
Python | UTF-8 | 567 | 3.25 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 2 20:02:52 2016
@author: Matthew
"""
from lxml import html
import requests
input_word = input('Enter Word to Define: ')
page = requests.get('http://www.urbandictionary.com/define.php?term=' + input_word)
tree = html.fromstring(page.content)
word_meanings = tree.xpath('//div[@class="meaning"]/text()')
# Clear screen easy way
print("\n" * 100)
print('Resultant Definitions for "' + input_word + '"')
print(' ')
for definition_line in word_meanings:
print(definition_line.strip())
|
Java | UTF-8 | 3,903 | 2.140625 | 2 | [] | no_license | package com.gui.product;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ConnectionPool;
import com.ads.Collaboration.UserRateModel;
import com.ads.user.UserModel;
import com.library.Utilities;
import com.object.*;
/**
* Servlet implementation class ProductRating
*/
@WebServlet("/ProductRating")
public class ProductRating extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String CONTENT_TYPE = "text/html; charset=utf-8";
/**
* @see HttpServlet#HttpServlet()
*/
public ProductRating() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
response.setContentType(CONTENT_TYPE);
String user_id_now = "";
// TODO Auto-generated method stub
ServletContext application = getServletConfig().getServletContext();
// tim bo quan ly ket noi
ConnectionPool cp = (ConnectionPool) application.getAttribute("cpool");
// cp null ...
// Tao doi tuong thuc thi chuc nang
UserRateModel ur = new UserRateModel(cp);
// vi cp null thi basic se tu tao ra cp moi .
// Lay lai cp tu ben control.
if (cp == null) {
application.setAttribute("cpool", ur.getConnectionPool());
}
UserObject userlogined = (UserObject) request.getSession().getAttribute("userLogined");
Visitor visitorNow = (Visitor) request.getSession().getAttribute("VisitorNow");
if (userlogined == null && visitorNow == null) {
UserModel um = new UserModel(cp);
String nextVisitorID = um.getNextVisitorId();
Visitor visitor = new Visitor();
visitor.setVisitor_id(nextVisitorID);
visitor.setVisitor_prefix("V");
visitor.setVisitor_created_date(Utilities.getStringDateNow());
visitor.setVisitor_IP("local");
if (um.addVisitor(visitor)) {
request.getSession().setAttribute("VisitorNow", visitor);
}
}
if (userlogined != null) {
user_id_now = userlogined.getUserId();
request.getSession().setAttribute("user_id_now", user_id_now);
request.getSession().removeAttribute("VisitorNow");
} else {
visitorNow = (Visitor) request.getSession().getAttribute("VisitorNow");
user_id_now = visitorNow.getVisitor_id();
request.getSession().setAttribute("user_id_now", user_id_now);
}
//ratting
UserRateObject ratting = new UserRateObject();
String product_id = (String) request.getSession().getAttribute("product_id");
String user_id = user_id_now;
String rate = request.getParameter("rdoRate");
String comment = request.getParameter("comment");
ratting.setProduct_id(Integer.parseInt(product_id));
ratting.setUser_id(user_id);
ratting.setUser_rate_point(Integer.parseInt(rate));
ratting.setUser_rate_comment(comment);
ur.addUserRate(ratting);
// tra lai ket noi cho he thong
ur.releaseConnection();
out.println(Utilities.getMessageRedict(
"Cảm ơn bản đã đánh giá sản phẩm ",
request.getContextPath() + "/"));
response.sendRedirect(request.getContextPath() + "/frontend/page.jsp?paction=detail&prid="+product_id);
}
}
|
Java | UTF-8 | 411 | 2.171875 | 2 | [] | no_license | package frc.robot.movements;
import edu.wpi.first.wpilibj.command.TimedCommand;
import frc.robot.TechnoTitan;
public class Yeet extends TimedCommand {
public Yeet() {
super(1.75);
requires(TechnoTitan.drive);
}
@Override
protected void execute() {
TechnoTitan.drive.set(0.80);
}
@Override
protected void end() {
TechnoTitan.drive.stop();
}
}
|
Python | UTF-8 | 1,368 | 4.5 | 4 | [] | no_license | # Tristan Kang
# Dec 12th, 2017
# Function Practice
# Mr. Allan
import math
# Chez
def cheese():
'''Makes a screen full of I like cheeses!'''
print ("I like cheese!" * 200)
cheese()
# Volume of Sphere
def volume_sphere(radius):
'''Calculates the volume of a sphere radius is an integer oor float'''
volume = (4/3)*math.pi*r**3
print("Calculating.")
print("Calculating..")
print("Calculating...")
print("Calculating.")
print("Calculating..")
print("Calculating...")
return volume
r = input("Please enter a radius of a sphere: ")
r = float(r)
v_sphere = volume_sphere(r)
print(v_sphere)
# Fahrenheit to Celsius
def temp_C(temp_F):
'''Converts a temperature in Fahrenheit to Celsius temp_F is the
temperature (float) in Fahrenheit'''
#(T(F) - 32) x 5/9
answer = (temp_F - 32) * (5/9)
return answer
t_in_F = input("Please enter a temperature in Fahrenheit: ")
t_in_F = float(t_in_F) #Converting the input to a float "52.0 --> 52.0
t_in_C = temp_C(t_in_F)
print("That temperature in Celsius is",t_in_C)
# Cam Newton Touchdowns
def cam_newton_TDS(TDS):
cam_newton_TDS = TDS * 7*4*math.pi+6
return cam_newton_TDS
TDS_guess = input("Enter how many TDS you think Cam Newton has: ")
TDS_guess = float(TDS_guess)
print("WRONG! He has:")
print(cam_newton_TDS(TDS_guess))
print("TDS")
|
Java | UTF-8 | 2,387 | 2.28125 | 2 | [] | no_license | package com.zz.splitting.config.redis;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Bean(name = "stringRedisTemplate")
public RedisTemplate<String, String> stringRedisTemplate() {
final RedisTemplate<String, String> template = new RedisTemplate<>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// template.setEnableTransactionSupport(true);
template.setEnableTransactionSupport(false);
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(stringRedisSerializer);
template.setDefaultSerializer(stringRedisSerializer);//如果泛型是Object 就要用RedisObjectSerializer
template.setConnectionFactory(generateDevConnectionFactory());
return template;
}
private RedisConnectionFactory generateDevConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setUsePool(true);
factory.setConvertPipelineAndTxResults(true);
JedisPoolConfig poolConfig = generatePoolConfig();
factory.setPoolConfig(poolConfig);
factory.setTimeout(5000);
factory.afterPropertiesSet();
return factory;
}
private JedisPoolConfig generatePoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMinIdle(50);
poolConfig.setMaxTotal(500);
poolConfig.setMaxWaitMillis(5000);
poolConfig.setTestOnBorrow(true);
return poolConfig;
}
}
|
Java | UTF-8 | 1,018 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | import java.util.Scanner;
/**
* @author alpha
* @date 2017/10/17
*/
public class Solution {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arrayNumber = new int[n][n];
for (int i=0; i<n; i++){
for (int j=0; j<=i; j++){
arrayNumber[i][j] = sc.nextInt();
if (0 < i){
if (0 == j){
arrayNumber[i][j] += arrayNumber[i-1][j];
} else if (i > j){
arrayNumber[i][j] += Math.max(arrayNumber[i-1][j-1], arrayNumber[i-1][j]);
} else {
arrayNumber[i][j] += arrayNumber[i-1][j-1];
}
}
}
}
int ans = 0;
for (int j=0; j<n; j++){
if (ans < arrayNumber[n-1][j]){
ans = arrayNumber[n-1][j];
}
}
System.out.println(ans);
}
}
|
Markdown | UTF-8 | 510 | 3.15625 | 3 | [] | no_license | ---
title: 测试公式
date: 2018-08-04 23:12:07
tags:
mathjax: true
---
$f(x_1) = sin(x_1)^2$
$$f(x)=
\begin{cases}
0& \text{x=0}\\\\
1& \text{x!=0}
\end{cases}$$
$$
\sum_{i=0}^N\int_{a}^{b}g(t,i)\text{d}t
$$
$$\begin{bmatrix}
{a_{11}}&{a_{12}}&{\cdots}&{a_{1n}}\\\\
{a_{21}}&{a_{22}}&{\cdots}&{a_{2n}}\\\\
{\vdots}&{\vdots}&{\ddots}&{\vdots}\\\\
{a_{m1}}&{a_{m2}}&{\cdots}&{a_{mn}}\\\\
\end{bmatrix}$$
$$\begin{cases}
a_1x+b_1y+c_1z=d_1\\\\
a_2x+b_2y+c_2z=d_2\\\\
a_3x+b_3y+c_3z=d_3\\\\
\end{cases}
$$ |
C++ | UTF-8 | 521 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Sprite2D.h"
class AnimationSprite : public Sprite2D
{
public:
AnimationSprite(std::shared_ptr<Models> model, std::shared_ptr<Shaders>
shader, std::shared_ptr<Texture> texture, int numFrames, float frameTime, bool isRepeating);
~AnimationSprite();
void Init();
void Draw();
void Update(GLfloat deltatime);
void Destroy();
bool IsActive();
void Reset();
protected:
int m_numFrames;
float m_frameTime;
int m_currentFrame;
float m_currentTime;
bool m_IsRepeating;
bool m_IsActive;
};
|
C# | UTF-8 | 1,482 | 3.171875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustumGenerics.Structures
{
public class Node<T>
{
public Node<T> left;
public Node<T> right;
Node<T> parent;
public T Value;
int number;
/// <summary>
/// Nodo del arbol avl
/// </summary>
/// <param name="value"></param> este parametro es para almacenamiento
/// <param name="left"></param> define al nodo izquierdo
/// <param name="right"></param> define al nodo derecho
/// <param name="parent"></param> define al nodo padre
/// <param name="number"></param> define la altura
#region Constructor
public Node(T value, Node<T> left, Node<T> right)
{
this.Value = value;
this.left = left;
this.right = right;
this.parent = null;
this.number = 0;
}
public Node(T value) : this (value, null, null) { }
public int Number
{
get
{
return number;
}
set
{
number = value;
}
}
public Node <T> Parent
{
get
{
return parent;
}
set
{
this.parent = value;
}
}
#endregion
}
}
|
Python | UTF-8 | 2,506 | 3.046875 | 3 | [
"MIT"
] | permissive | # Author: https://github.com/AYMENJD (AYMEN Mohammed telegram.me/K6KKK).
from time import gmtime, sleep, strftime, time
import threading
from typing import Optional
class Stopwatch:
def __init__(self) -> None:
self.timer = 0
self._pause = False
self._stop = False
self._saved = []
self.thread = threading.Thread(target=self._counter, daemon=True)
def start(self) -> bool:
"""start timing"""
if self.thread.is_alive() == False:
self.thread.start()
elif self._stop == True:
self.thread = threading.Thread(target=self._counter, daemon=True)
self._stop = False
self.thread.start()
else:
self._pause = False
return True
def pause(self) -> bool:
"""pause timing"""
self._pause = True
return True
def save(self) -> bool:
"""save the current timing to list"""
self._saved.append(self.timer)
return True
def saved(self) -> list:
"""returns a list of timings that saved using save() method"""
return self._saved
def current(self) -> int:
"""current timing"""
return self.timer
def format(self, num: Optional[int] = None, format: Optional[str] = "%M:%S") -> str:
"""time formater
Args:
num (`int`): Optional, number of seconds to format.
format (`str`): Optional, format code.
"""
num = self.timer if num is None else num
return strftime(format, gmtime(num))
def stop(self):
"""stop timer"""
self._stop = True
self._pause = True
if self.thread.is_alive():
self.thread.join(1)
def reset(self, restart=True):
"""Reset timer data
Args:
restart (`bool`): if True, restart timer.
"""
if self.thread.is_alive() == True:
self._stop = True
self._pause = True
self.thread.join(1)
self.timer = 0
self._pause = False
self._stop = False
self._saved = []
self.thread = threading.Thread(target=self._counter, daemon=True)
if restart:
self.thread.start()
def _counter(self) -> None:
while self._stop == False:
while self._pause == False:
# now = time()
# sleep(1)
# self.timer += time() - now
sleep(1)
self.timer += 1
|
JavaScript | UTF-8 | 1,970 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const { pruneSourcemaps } = require('../src')
const args = process.argv.slice()
args.shift() // node
args.shift() // prune-sourcemaps
function printHelp(err=false) {
const meth = err ? 'error' : 'log'
console[meth]('Usage: npx prune-sourcemaps <directory>')
console[meth]('Recursively deletes sourcemap files and sourcemap comments under <directory>')
process.exit(err ? 1 : 0)
}
function error(msg) {
console.error(`Error: ${msg}`)
process.exit(1)
}
let confirm = true
let directory
for (const arg of args) {
if (arg === '-h' || arg === '--help') {
printHelp()
} else if (arg === '-y' || arg === '--yes') {
confirm = false
} else if (!directory) {
directory = arg
} else {
console.error(`Unexpected argument: "${arg}"`)
printHelp(true)
}
}
if (!directory) {
printHelp(true)
}
// we do this twice so we don't ask for confirmation before these simple checks
const dirPath = path.resolve(process.cwd(), directory)
if (!fs.existsSync(dirPath)) {
error(`Directory not found -- ${dirPath}`)
}
const st = fs.statSync(dirPath)
if (!st.isDirectory()) {
error(`Not a directory -- ${dirPath}`)
}
function doPrune() {
pruneSourcemaps(dirPath).then(pruned => {
console.log(`Successfully pruned ${pruned.size} sourcemaps`)
pruned.forEach(sourcemap => console.log(` - ${sourcemap}`))
}).catch(err => {
console.error(err)
process.exit(1)
})
}
if (!confirm) {
doPrune()
} else {
const { stdin } = process
if (!stdin.isTTY) {
error('TTY is not available, use -y option to disable confirmation')
}
process.stdout.write(`Prune sourcemaps under ${directory}? [y/N] `)
stdin.setRawMode(true)
stdin.setEncoding('utf8')
stdin.resume()
stdin.on('data', k => {
stdin.pause()
console.log()
if (k === 'y') {
return doPrune()
}
console.log('Did not confirm, aborting')
process.exit(0)
})
}
|
Java | UTF-8 | 1,031 | 3.421875 | 3 | [
"MIT"
] | permissive | package leetcode_problems.medium;
import java.util.HashSet;
import java.util.Set;
public class CheckIfStringContains_1461 {
// Time complexity: O(2^k). Space complexity: O(n)
public boolean hasAllCodes1(String s, int k) {
Set<String> set = new HashSet<>();
for (int i = 0; i < s.length() && k + i <= s.length(); i++) set.add(s.substring(i, k + i));
for (int i = 0; i < Math.pow(2, k); i++) {
String binary = Integer.toBinaryString(i);
binary = "0".repeat(k - binary.length()) + binary;
if (!set.contains(binary)) return false;
}
return true;
}
// Time complexity: O(n). Space complexity: O(n)
public boolean hasAllCodes2(String s, int k) {
Set<String> substrings = new HashSet<>();
for (int i = 0; i < s.length() && k + i <= s.length(); i++) {
substrings.add(s.substring(i, k + i));
if (substrings.size() == 1 << k /* Math.pow(2, k)*/) return true;
}
return false;
}
} |
Markdown | UTF-8 | 1,160 | 2.984375 | 3 | [
"MIT"
] | permissive | # Correlations Discovered Between Health Risks, Age, And Income
## Demo - [Click here](http://jennylynnramz.com/health_risk_dashboard/)

## Description
* This project explores correlation between health risks, age, and income.
* This project creates an animated and interactive scatter plot using Javascript/D3 to [represent CSV data](https://github.com/jennylynnramz/health_risk_dashboard/blob/master/assets/data/data.csv).
* The plot changes based on the demographics selected on the X and Y status.
* More information is available when hovering above each individual circle.
## Built With
* [D3](https://d3js.org/) - JavaScript library for manipulating documents based on data.
* [Bootstrap](https://getbootstrap.com/) - Library used to generate HTML UI.
* [Github Pages](https://pages.github.com/) - Service used to host this project.
## Authors
* **Jennifer Ramsey** - [jennylynnramz](https://github.com/jennylynnramz)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
|
C++ | UTF-8 | 861 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include "HubCom.h"
void HubCom::run() {
//receive();
ioService.run();
}
void HubCom::receive() {
socket.async_receive_from(
boost::asio::buffer(data, max_length), serverEndpoint,
[this](std::error_code ec, std::size_t bytes_recvd) {
if (!ec && bytes_recvd > 0) {
std::cout << data << std::endl;
//send(bytes_recvd);
} /*else {
receive();
}*/
});
}
void HubCom::send(char* data, std::size_t length) {
socket.async_send_to(
boost::asio::buffer(data, length), serverEndpoint,
[this](std::error_code ec, std::size_t bytes_sent) {
std::cout << "sent " << ec << " " << +bytes_sent << std::endl;
//receive();
});
}
|
C++ | UTF-8 | 401 | 3.25 | 3 | [
"BSD-3-Clause"
] | permissive | #include "CreditCard.h"
CreditCard::CreditCard(int number, int month, int year) : validDate(year, month)
{
this->setNumber(number);
}
void CreditCard::setNumber(int number) throw(const string&)
{
if (number < MIN_NUMBER || number > MAX_NUMBER)
{
throw "Invalid credit card number input.";
}
this->number = number;
}
const int CreditCard::getNumber()
{
return this->number % FOUR_DIGITS;
}
|
SQL | UTF-8 | 1,123 | 4.15625 | 4 | [] | no_license | -- Get titles of indivduals near retirement
SELECT e.emp_no,
e.first_name,
e.last_name,
ti.title,
ti.from_date,
ti.to_date
-- INTO retirement_titles
FROM employees as e
INNER JOIN titles as ti
ON (e.emp_no = ti.emp_no)
WHERE (e.birth_date BETWEEN '1952-01-01' AND '1955-12-31')
ORDER BY (e.emp_no);
-- Use Dictinct with Orderby to remove duplicate rows
SELECT DISTINCT ON (emp_no) emp_no,
first_name,
last_name,
title
--INTO unique_titles
FROM retirement_titles
ORDER BY emp_no, to_date DESC;
--Retrieve number of retiring employees by title
SELECT COUNT (emp_no),
title
--INTO retiring_titles
FROM unique_titles
GROUP BY title
ORDER BY count DESC;
-- Eligible for mentorship program 1/1/1965-12/31/1965
SELECT DISTINCT ON (e.emp_no)
e.emp_no,
e.first_name,
e.last_name,
e.birth_date,
de.from_date,
de.to_date,
ti.title
-- INTO mentorship_eligibility
FROM employees as e
INNER JOIN dept_emp as de
ON (e.emp_no = de.emp_no)
INNER JOIN titles as ti
ON (e.emp_no = ti.emp_no)
WHERE (e.birth_date BETWEEN '1965-01-01' AND '1965-12-31')
AND (de.to_date = '9999-01-01')
ORDER BY e.emp_no; |
Java | UTF-8 | 5,831 | 1.84375 | 2 | [] | no_license | package com.walmart.gshop.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.pubnub.api.Callback;
import com.pubnub.api.Pubnub;
import com.walmart.gshop.Constants;
import com.walmart.gshop.MyApplication;
import com.walmart.gshop.adapters.ChannelsRecyclerViewAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import me.kevingleason.pubnubchat.R;
public class ChannelListActivity extends AppCompatActivity implements View.OnClickListener, ChannelsRecyclerViewAdapter.MyClickListener {
private final static String LOG_TAG = "ChannelListActivity";
private SharedPreferences mSharedPrefs;
private Pubnub mPubNub;
CoordinatorLayout coordinatorLayout;
private RecyclerView mRecyclerView;
private ChannelsRecyclerViewAdapter mAdapter;
List<String> channelList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_channels);
mPubNub = ((MyApplication) getApplication()).getmPubNub();
mSharedPrefs = getSharedPreferences(Constants.CHAT_PREFS, MODE_PRIVATE);
if (!mSharedPrefs.contains(Constants.CHAT_USERNAME)) {
Intent toLogin = new Intent(this, LoginActivity.class);
startActivity(toLogin);
return;
}
mPubNub.setUUID(mSharedPrefs.getString(Constants.CHAT_USERNAME, "Anonymous"));
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewChannels);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ChannelsRecyclerViewAdapter(new ArrayList<String>());
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(this);
channelList = new ArrayList<>();
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbarChannelList);
setSupportActionBar(mToolbar);
whereNow();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabAddChannel);
fab.setOnClickListener(this);
}
public void whereNow() {
mPubNub.whereNow(mPubNub.getUUID(), new Callback() {
@Override
public void successCallback(String channel, Object response) {
try {
JSONObject json = (JSONObject) response;
Log.i("Where now response", json.toString());
final JSONArray channels = json.getJSONArray("channels");
Log.d("JSON_RESP", "Where Now: " + json.toString());
for (int i = 0; i < channels.length(); i++) {
channelList.add(channels.getString(i));
}
ChannelListActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.updateData(channelList);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fabAddChannel:
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.channel_change, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String newChannel = userInput.getText().toString();
if (newChannel.equals("")) return;
Intent i = new Intent(getBaseContext(), ChatActivity.class);
i.putExtra(Constants.CHAT_ROOM, newChannel);
startActivity(i);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
break;
}
}
@Override
public void onItemClick(int position, View v) {
Intent i = new Intent(getBaseContext(), ChatActivity.class);
i.putExtra(Constants.CHAT_ROOM, channelList.get(position));
startActivity(i);
}
}
|
C# | UTF-8 | 1,040 | 3.109375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ThreadingExampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnHello_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
public async Task<string> GetDataForTextBox()
{
string result = "";
await Task.Run(() =>
{
for (int i = 1; i < 101; i = i + 10)
{
Thread.Sleep(1000);
result += i + " ";
}
});
return result;
}
private async void btnStart_Click(object sender, EventArgs e)
{
txtData.Text = await GetDataForTextBox();
}
}
}
|
JavaScript | UTF-8 | 221 | 2.671875 | 3 | [] | no_license | $(document).ready(function() {
var $loader = $(".loader");
// Remove our loader from page.
// Force it to appear at least 5 seconds.
setTimeout(function() {
$loader.fadeOut(300);
}, 5000);
}); |
Markdown | GB18030 | 10,052 | 2.84375 | 3 | [] | no_license | <a name="1" target="_blank"></a>
<h1>ũȥũܾ</h1>
<img src="http://i.epochtimes.com/assets/uploads/2006/05/605160839441124-594x400.jpg" />
```diff
- 1968ףëɢƵй̸ǣʼɽ磬ƶũѧϰĹ̡йʮϡһЩ˵ڻũ塣(AFP/Getty Images)
```
<hr>
<p>ڳл60%ʱйʼ˸֡ũȥᶯԱ뷢ȣ뷢չйȣν⡣ԭʵ2005꿪ʼĿٳл̣һҵٳл</p>
<h2><strong>˶ƶٳл</strong></h2>
<p>л̶ַһ֣л˿ռһ˿֮ȣɸл֣һڶdzл䶯ʣһָʱԤƵƽл䶯ʡڶַҪ֮רҵʿۣʹõһַ</p>
<p>Ӣ翪ʼҵĹңҲ翪ʼлĹҡӢɹҵᾭýٷչΣΪңлˮƽ90%Ӣ֮ŷ½ķ¹ԼĴǡôȹҲ̿ʼҵƶлֽ̡ΣЩҵijлˮƽ80%ϡ</p>
<p>չйֱ20ڲſʼл̣Ŀǰлˮƽദ50%-65%֮䡣йΪڶ壬侭ͳңڳлˮƽϣԶڷң2018ijлˮƽԼΪ59.58%ڷչйҾеˮƽ</p>
<p>ѧͨԷչйҳлıȽϣһᾭ÷չˮƽлˮƽӦͻлˮƽᾭ÷չˮƽΪͺллˮƽᾭ÷չˮƽΪٳлЩڷչйҡУٳлҪ͢ȹǵũڳҵɾܱͣ߳Ϊƶ֮ء</p>
<p>й2005꿪ʼ롰ٳлΣʱйͨ˶ƽйijлΪҪˣʱȡũҵ˰طٲԴרԤ⣬ÿһٷֵζǧ˽УоͶͬʱо˿ÿһٷֵ㣬ɴ1.6%Ϊƽлйȫؿչֵġ˶</p>
<h2><strong>й˶ʼĩ</strong></h2>
<p>йִ£עܿ챻תƣӶ²ܿ챻2005ϰӹȨһڼġ˶һ</p>
<p>Դͷ˵ļdzĻݹо߿֤20041021գԺ·ĸϸعľũ彨õõҪũ彨õؼҹΪũûõָ꿪˷ͨ2006꣬ȷ罨õҹԵʡݣɽաĴʡбΪһԵ㡣20086°䲼ˡ罨õҹ취˺20082009ֱ19ʡҹԵ㡣2008ף4ھǫ̼֮̂Ƴһϵдʩ֮ϣΪҪǼӴ˳罨õҹתָꡣ</p>
<p>νҹָΪصũ彨õصؿ飨ɵؿ飩ڳĵؿ飨µؿ飩ͬɽ²Ŀڱ֤ĿڸƽĻϣʵӸЧԼԼýõأõزָĿꡱ˵䣬Ҫ¾ɵؿ顰ͬɽ²Ŀ˵ˣνҹǹԴŵĻ£Ϊ˷طҵءӽõָɷѿһͨ취طñԶũһЩֲʳʻĵأ˸أþ÷ijǮЩָ꣬زõء֮Ϸʵʾǹĸľ˵ģģתָ꣬ǹIJԣΪӦԸõѹɲء</p>
<p>ˡ罨õҹ취ٵͨȫز£һģƴġ˶ϯȫй20ʡǧػׯ֮й½ʧطһͬĿ꣺ũլظѣӵĸأȡõָꡣ</p>
<p>ڡ岢ӡ˳ϯ֮£ũ¥ǶʱڣȫýƵƵعش岢ӵġ˶Լũڡ˶Сжٴׯұվӻϸݡٶ˶Ĵɲꡣ㷺õһɽǣƱȫȡǧȻ䡢1249ϲΪ20870ũڸסϴ壬20085µף924ҹԵʡݽ˿ٵУ˲⣬1996꣬йĸά19.51Ķ˺11䣬йؼ1.25Ķȫȫ˾Ҳ1.59Ķ1.39Ķձ鵣ģļٶȣйĸػܲйˣ2008 Ժйؿظѣٵи£ͻȻӣϷڱ֮С</p>
<h2><strong>ٳлزĭũ</strong></h2>
<p>ڵطҪũǿи¥νлչйҳֵġٳл֡ٳл</p>
<p>һȶľҵ뱾ũ˿תƵȾйٳлǰũ˿ڽ½ijСסȴûܵõµľҵλΪʣͶǰްڷز߷ʱڣũʣͶ뷿زҵرǽҵ20073133.720093900ˣռũ17.3%ƺ̫ءزҵһ˳ũʧҵ</p>
<p>ز߶ĭ201812£ϲƾѧйͥڵоķ2017йס÷棬ָй߳סʷֱΪ22.2%21.8%Զһ߳е16.8%סУƷĿλӵһҳʳƣ26.6%һЩʡΪ˹ũòʽũ罭ǨԥСĴϳءʡɽصȵأũΪ</p>
<p>ũ廧ϸŵҪ80%ũԸũ廧ЩһǸسаȨլأԽסЩڳдͳǽũʱɶһɾ棬غʹгнũ廧ԶԶлһ㣬<a href="https://github.com/szzd1/djy/blob/master/gb/tag/%E4%B8%8A%E5%B1%B1%E4%B8%8B%E4%B9%A1.md">ɽ</a>˶ܷҪԭΪԸũȥһҲûС</p>
<p>йڳֻ59.58%ʱȴˡũȥҪũ磩лƣֻ˵ǵٳлķɡйóУҵڶ״̬൱һʱڡΪ͡սԡġ䴫ɡ<a href="https://github.com/szzd1/djy/blob/master/gb/tag/%E4%B8%8A%E5%B1%B1%E4%B8%8B%E4%B9%A1.md">ɽ</a>ǹɽʹ༯䡢ʧҵءũ硢ڶϰƽëȸΡصĻϲ</p>
<p>Ԫת辭Ȩ</p>
<p>α༭ӱ</p>
<p>ԭĵַ <a href="http://cn.epochtimes.com/gb/19/4/16/n11189490.htm">http://cn.epochtimes.com/gb/19/4/16/n11189490.htm</a> <a href="https://git.io/fjmgJ">ǽ</a>ܷʣ</p>
|
Python | UTF-8 | 2,359 | 2.671875 | 3 | [] | no_license |
import tkinter as tk
from database import DataBase, verify
FT = "Arial 14 bold"
class Password(tk.Toplevel):
def __init__(self):
tk.Toplevel.__init__(self)
self.geometry("248x280")
self.resizable(0, 0)
self.sizefrom(who="user")
self.title("Recuperation d'identifiant")
self.configure(background="#fff")
self.mydb = DataBase()
self.error = tk.Label(self, anchor="w", font="Arial 10 bold", fg="red", bg="#fff")
self.error.pack(expand=1, fill="both", padx=10, pady="5 0", ipady=5, ipadx=5)
lb1 = tk.Label(self, text="Nom", anchor="w", font=FT, bg="#c7e0f7", fg="#05f")
lb1.pack(expand=1, fill="both", padx=10, pady="5 0", ipady=5, ipadx=5)
self.nom = tk.Entry(self, font=FT, bg="#fff", fg="grey", justify="center")
self.nom.pack(expand=1, fill="both", padx=10, ipady=5, ipadx=5)
lb1 = tk.Label(self, text="Contact", anchor="w", font=FT, bg="#c7e0f7", fg="#05f")
lb1.pack(expand=1, fill="both", padx=10, pady="5 0", ipady=5, ipadx=5)
self.contact = tk.Entry(self, font=FT, bg="#fff", fg="grey", justify="center")
self.contact.pack(expand=1, fill="both", padx=10, ipady=5, ipadx=5)
self.info = tk.Label(self, font="Arial 12 bold", bg="#fff", fg="grey")
self.info.pack(expand=1, fill="both", padx=10, pady=5, ipady=5, ipadx=5)
self.info.bind("<1>", self.copy)
btn = tk.Button(self, text="Rechercher", font=FT, bg="#c7e0f7", fg="#05f", relief="flat", command=self.search)
btn.pack(expand=1, fill="both", side="right", padx=10, pady=5)
def copy(self, _):
self.master.clipboard_clear()
self.master.clipboard_append(self.info["text"])
self.master.bell()
def search(self):
valide = verify([self.nom, self.contact])
if not valide:
self.error.config(text="Touts les champs sont obligatoires")
self.info["text"] = ""
else:
self.error.config(text="")
result = self.mydb.recuva(self.nom.get().strip().upper(), self.contact.get().strip())
if not result:
self.info.config(fg="red", text="Aucune correspondance !")
else:
self.info.config(fg="green", text=result)
if __name__ == "__main__":
Password().mainloop() |
C++ | UTF-8 | 228 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
string X, Y;
cin >> X >> Y;
if (X < Y) cout << "<";
else if (X > Y) cout << ">";
else cout << "=";
cout << endl;
return 0;
}
|
C++ | UTF-8 | 364 | 2.65625 | 3 | [] | no_license | #ifndef _D_TRAPEZOID_H_
#define _D_TRAPEZOID_H_
#include "figure.h"
class trapezoid : public figure {
public:
trapezoid() = default;
trapezoid(std::istream& is);
double area() const override;
point center() const override;
std::ostream& print(std::ostream& os) const override;
private:
point a1, a2, a3, a4;
};
#endif // _D_TRAPEZOID_H_
|
Swift | UTF-8 | 405 | 2.671875 | 3 | [] | no_license | //
// DistanceModel.swift
// GoogleMap
//
// Created by Duy Liêm on 10/30/19.
// Copyright © 2019 DuyLiem. All rights reserved.
//
import Foundation
import ObjectMapper
struct DistanceModel: Mappable {
var text: String?
var value: Int?
init?(map: Map) {
}
mutating func mapping(map: Map) {
text <- map["text"]
value <- map["value"]
}
}
|
Python | UTF-8 | 2,916 | 2.78125 | 3 | [] | no_license | global N
N = 8
global threat_list
global board
board = [[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
threat_list=[[1, 0, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 0, 1]
]
placed = [0,0,0,0,4,0,0,0]
def validate_attack(board, row, col):
for j in range(N):
if(board[row][j] == 1 or board[j][col] == 1):
return True
for i in range(N):
for j in range(N):
if((i+j == row+col) or (i-j == row-col)):
if(board[i][j] == 1):
return True
return False
def find_initial_threats():
for i in range(N):
row_list=[]
for j in range(N):
if(validate_attack(board,i,j)):
row_list.append(1)
else:
row_list.append(0)
threat_list.append(row_list)
return threat_list
def print_board(board):
string = ""
for i in range(N):
for j in range(N):
string += str(board[i][j])+"\t"
string += "\n"
print(string)
def solve(board, col):
if(col == N):
return True
for i in range(N):
if(threat_list[i][col] == 0):
placed[col] = i
add_threats(i, col)
if(validate(col)):
solve(board, col+1)
remove_threats(i, col)
return False
def determine_threats(modifier, row, col):
for j in range(1,N-col):
if(threat_list[row][col+j]!=1):
threat_list[row][col+j] += modifier # horizontal threats
if(row+j < N):
if(threat_list[row+j][col+j]!=1):
threat_list[row+j][col+j] += modifier # diagonal threats
if(row-j >= 0):
if(threat_list[row-j][col+j]!=1):
threat_list[row-j][col+j] += modifier # diagonal threats
def add_threats(row, col):
determine_threats(1, row, col)
def remove_threats(row, col):
determine_threats(-1, row, col)
def validate(col):
for i in range(col+1, N):
can_place = False
for row in range(N):
if(can_place):
break
if(threat_list[row][i] == 0):
can_place = True
if(can_place == False):
return False
return True
def main():
#print("Init",find_initial_threats())
if(solve(board, 0) == False):
print("Solution Does not Exist!!!")
return False
print_board(board)
return True
if __name__ == "__main__":
main()
|
Shell | UTF-8 | 197 | 2.890625 | 3 | [] | no_license | #!/bin/bash
#
echo "sisesta arv suvaline taisarv"
read a
jaak=$(( $a % 2 )) #arvutab jaaki 2ga jamaisle
if [ $jaak -eq 0 ] #kui jaak on null
then echo "$a on paaris"
else echo "$a on paaritu"
fi
#
|
C++ | UTF-8 | 4,909 | 2.59375 | 3 | [] | no_license | String formularioConfiguracion(){
String tex = "";
int n = WiFi.scanNetworks();
tex += "<p><a href=\"/configuracion/estado\">Estado</a> | <a href=\"/login?DISCONNECT=YES\">Logout</a></p>";
tex += "<fieldset class=\"configuracion\"><legend>Local</legend>";
if (WiFi.status() == WL_CONNECTED) {
String currAP = WiFi.SSID();
tex += "<h2>Conectado a " + currAP + "</h2>";
}else{
tex += "<h2>No conectado</h2>";
}
if (n == 0) {
tex += "</p>No se encontraron redes inalámbricas</p>";
} else {
tex += "<p>Redes inalámbricas encontradas</p>";
tex += "<form action=\"/configuracion/coneccion-ap\" method=\"post\">";
int anotadas = 0;
for (int i = 0; i < n; ++i)// 10=n
{
//if((WiFi.RSSI(i)>-70)&&(i<7)){
if((WiFi.RSSI(i)>-80)&&(anotadas<7)){
// Print SSID and RSSI for each network found
tex += "<p>" + String(i + 1);
tex += ": ";
tex += WiFi.SSID(i)+" ";
tex += "<label>Ssid</label> <input type=\"radio\" name=\"ssid-selected[]\" value=\"" + String(WiFi.SSID(i)) + "\">";
tex += "<label>Pass</label> <input type=\"password\" name=\"ssid-pass[]\" value=\"\">";
tex += " (";
tex += WiFi.RSSI(i);
tex += ")";
tex += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*";
tex += "</p>";
anotadas++;
delay(10);
}
}
tex += "<input type=\"submit\" value=\"Enviar\">";
tex += "</form>";
/*tex += "<form action=\"/configuracion/set-puerto\" method=\"post\">";
tex += "<p><label>Puerto</label> <input type=\"text\" name=\"puerto\" value=\"\"></p> ";
tex += "<input type=\"submit\" value=\"Enviar\">";
tex += "</form>";*/
tex += "<form action=\"/configuracion/reset-pass\" method=\"post\">";
tex += "<p><label>Clave</label> <input type=\"password\" name=\"new-pass\" value=\"\"></p> ";
tex += "<p><label>Confirma clave</label> <input type=\"password\" name=\"confirm-new-pass\" value=\"\"></p>";
tex += "<input type=\"submit\" value=\"Enviar\">";
tex += "</form>";
tex += "<form action=\"/configuracion/set-ubicacion\" method=\"post\">";
tex += "<p class=\"form-comment\">La dirección guardada es : ";
tex += estaVacio(stored_location.addr)?"sin datos":stored_location.addr;
tex += "</p>";
tex += "<p><label>Dirección</label> <input type=\"text\" name=\"ubicacion-direccion\" value=\"\"></p> ";
tex += "<input type=\"submit\" value=\"Enviar\">";
tex += "<p class=\"form-comment advertencia\">Mapa disponible solo con conección a internet</p>";
tex += "</form>";
tex += "</fieldset>";
tex += "<fieldset class=\"configuracion\"><legend>Remoto</legend>";
tex += "<form action=\"/configuracion/set-estacion\" method=\"post\">";
tex += "<p class=\"form-comment\">La estación guardada es : ";
tex += estaVacio(stored_estacion.id)?"sin datos":stored_estacion.id;
tex += ", ";
tex += estaVacio(stored_estacion.nombre)?"sin datos":stored_estacion.nombre;
tex += "</p>";
tex += "<div id=\"estaciones\">ninguna estación</div>";
tex += "<input type=\"submit\" value=\"Enviar\">";
tex += "<p class=\"form-comment advertencia\">Remoto solo disponible con conección a internet</p>";
tex += "</form>";
tex += "</fieldset>";
tex += "<fieldset class=\"configuracion\"><legend>Display</legend>";
tex += "<form action=\"/configuracion/set-display\" method=\"post\">";
tex += "<p class=\"form-comment\">La configuración guardada es : modo > ";
tex += estaVacio(stored_display.dmode)?"sin datos":stored_display.dmode;
tex += ", prioridad > ";
tex += estaVacio(stored_display.dpriority)?"sin datos":stored_display.dpriority;
tex += "</p>";
tex += "<p>Modo: <label><input type=\"radio\" value=\"mostrar-solo-principal\" name=\"display-mode\">Mostrar solo principal</label> ";
//tex += "<label><input type=\"radio\" value=\"Mostrar solo remoto\" name=\"display-mode\">Mostrar solo remoto</label> ";
tex += "<label><input type=\"radio\" value=\"mostrar-ambos\" name=\"display-mode\">Mostrar ambos</label></p>";
tex += "<p>Prioridad: <label><input type=\"radio\" value=\"Principal local - secundario remoto\" name=\"display-priority\">Principal local - secundario remoto</label> ";
tex += "<label><input type=\"radio\" value=\"Principal remoto - secundario local\" name=\"display-priority\">Principal remoto - secundario local</label></p>";
tex += "<input type=\"submit\" value=\"Enviar\">";
tex += "<p class=\"form-comment advertencia\">Remoto solo disponible con conección a internet</p>";
tex += "</form>";
tex += "</fieldset>";
tex += "";
tex += "</form>";
tex += "</fieldset>";
}
return tex;
}
|
Java | UTF-8 | 204 | 1.859375 | 2 | [] | no_license | package com.example.unittestservicelayermockito.service;
import java.util.List;
public interface GenericService<T, U> {
List<T> findAll();
T save(T t) throws Exception;
void delete(U u);
}
|
Java | UTF-8 | 944 | 1.960938 | 2 | [] | 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 com.vz.ids.solutions.data.db;
import lombok.Data;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
/**
*
* @author v086714
*/
@Table("ids_sensor_model")
public class IdsSensorModelObject {
public String getSensorModelName() {
return sensorModelName;
}
public void setSensorModelName(String sensorModelName) {
this.sensorModelName = sensorModelName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@PrimaryKey
private String sensorModelName;
private String type;
private String data;
}
|
C++ | UTF-8 | 647 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct ac
{
int x;
int y;
}a[50010];
int cmp( const void *a , const void *b )
{
struct ac *c = (ac *)a;
struct ac *d = (ac *)b;
if(c->x != d->x) return c->x - d->x;
else return c->y - d->y;
}
int main ()
{
int i,n;
int va,vb;
scanf("%d",&n);
for ( i = 0; i < n; i++ )
scanf("%d%d",&a[i].x,&a[i].y);
qsort(a,n,sizeof(a[0]),cmp);
va = a[0].x;
vb = a[0].y;
int t;
for ( i = 1; i < n; i++ )
{
if ( a[i].x > vb )
{
printf("%d %d\n",va,vb);
va = a[i].x;
vb = a[i].y;
}
else if ( a[i].y > vb )
{
vb = a[i].y;
}
}
printf("%d %d\n",va,vb);
return 0;
} |
JavaScript | UTF-8 | 1,629 | 2.9375 | 3 | [] | no_license | import {
SET_USER_INPUT,
GET_WORDS_ERROR,
GET_WORDS_REQUEST,
GET_WORDS_SUCCESS
} from '../actions/word-actions/getWords';
import {
POST_GUESS_ERROR,
POST_GUESS_REQUEST,
POST_GUESS_SUCCESS
} from '../actions/word-actions/postGuess';
const initialState = {
words: [],
correctOrIncorrect: '',
error: null,
loading: false
};
export default function wordReducer(state = initialState, action) {
if (action.type === SET_USER_INPUT) {
return {
...state,
userInput: action.userInput
};
} else if (action.type === GET_WORDS_REQUEST) {
return {
...state,
loading: false,
error: null
};
} else if (action.type === GET_WORDS_SUCCESS) {
return {
...state,
loading: false,
words: action.words,
correctOrIncorrect: ''
};
} else if (action.type === GET_WORDS_ERROR) {
return {
...state,
loading: false,
error: action.err
};
} else if (action.type === POST_GUESS_REQUEST) {
return {
...state,
loading: false,
error: null
};
} else if (action.type === POST_GUESS_SUCCESS) {
return {
...state,
loading: false,
correctOrIncorrect: action.correctOrIncorrect
};
} else if (action.type === POST_GUESS_ERROR) {
return {
...state,
loading: false,
error: action.err
};
}
return state;
}
//maybe set words to an object?
// initialState = {
// words: [{word:'hola',answer: 'hello'}, {word:'gracias',answer: 'thank you'}]
// }
// {
// Words: { word: 'hola', answer: 'hello', correctCount: 0, incorrectCount: 0, next: null}
// }
|
PHP | UTF-8 | 3,431 | 2.75 | 3 | [] | no_license | <?php
// Includes all objects and services
require_once $_SERVER['DOCUMENT_ROOT'].'/library/includes.php';
// Semi Global veriable that works as a query string to load pages
$action = filter_input(INPUT_POST, 'action');
if ($action == NULL){
$action = filter_input(INPUT_GET, 'action');
if($action == NULL){
$action = 'login_view';
}
}
// Redirects user based on query string sent to action
switch ($action) {
// Renders the login view
case 'login_view':
include $_SERVER['DOCUMENT_ROOT'] .'/views/auth/auth-login.php';
break;
case 'login_process':
// paths based on user status
$userPath = 'Location: /index.php?action=home';
$modrPath = 'Location: /controllers/ctrl-admin.php?action=admin';
$admnPath = 'Location: /controllers/ctrl-admin.php?action=admin';
// We are retrieving the inputs that we need and applying logic
//Inputs from login form
$userIdentity = filter_input(INPUT_POST, 'userIdentity');
$userPass = filter_input(INPUT_POST, 'password');
$infoArr = array('userIdentity'=> $userIdentity,'password'=> $userPass);
// Applying business Logic
$result = $userService->login($infoArr);
// Redirecting user based on Status
switch($result['status']) {
case "user":
header($userPath);
break;
case "moderator":
header($modrPath);
break;
case "admin":
header($admnPath);
break;
case "error":
// Send the appropriate error message
// to the front end
echo json_encode($result);
break;
}
break;
case 'logout_process':
session_destroy();
header('location: /index.php');
break;
case 'register_view':
include $_SERVER['DOCUMENT_ROOT'] .'/views/auth/auth-register.php';
break;
case 'register_process':
// Register Form Inputs
$userEmail = filter_input(INPUT_POST, 'email');
$userPass = filter_input(INPUT_POST, 'password');
$userName = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$userFirst = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
$userLast = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);
$infoArr = array( "email" => $userEmail,
"password" => $userPass,
"name" => $userName,
"firstname" => $userFirst,
"lastname" => $userLast);
// Register Form Logic
$newUser = new User("register", $infoArr);
// If a status is assigned
// Throw the error
if($newUser->errStatus) {
echo json_encode($newUser->$errStatus);
break;
}
$result = $newUser->register();
// success failure alerts
if($result) {
// on success reroute to log user in
header('location: /controllers/ctrl-auth.php?action=login_view');
} else {
// on failure send alert
echo "<h1>error</h1>";
}
break;
default:
include $_SERVER['DOCUMENT_ROOT'] .'/views/auth/auth-login.php';
break;
} |
Ruby | UTF-8 | 2,255 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | require 'chef_backup'
require 'chef/mixin/deep_merge'
require 'optparse'
require 'ostruct'
add_command_under_category 'backup', 'general', 'Backup the Chef Server', 2 do
unless running_config
puts '[ERROR] cannot backup if you haven\'t completed a reconfigure'
exit 1
end
options = OpenStruct.new
options.agree_to_go_offline = false
OptionParser.new do |opts|
opts.banner = 'Usage: chef-server-ctl backup [options]'
opts.on('-y', '--yes', 'Agree to go offline during tar based backups') do
options.agree_to_go_offline = true
end
opts.on('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!(ARGV)
Chef::Mixin::DeepMerge.deep_merge!(stringify_keys(options.to_h), running_config['private_chef']['backup'])
status = ChefBackup::Runner.new(running_config).backup
exit(status ? 0 : 1)
end
add_command_under_category 'restore', 'general', 'Restore the Chef Server from backup', 2 do
options = OpenStruct.new
options.agree_to_cleanse = nil
options.restore_dir = nil
OptionParser.new do |opts|
opts.banner = 'Usage: chef-server-ctl restore $PATH_TO_BACKUP_TARBALL [options]'
opts.on('-d', '--staging-dir [directory]', String, 'The path to an empty directory for use in restoration. Ensure it has enough available space for all expanded data in the backup archive') do |staging_directory|
options.restore_dir = File.expand_path(staging_directory)
end
opts.on('-c', '--cleanse', 'Agree to cleansing all existing state during a restore. THIS WILL COMPLETELY REMOVING EXISTING CHEF DATA') do
options.agree_to_cleanse = 'yes'
end
opts.on('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!(ARGV)
unless ARGV.length >= 3
puts 'ERROR: Invalid command'
puts 'USAGE: chef-server-ctl restore $PATH_TO_BACKUP_TARBALL [options]'
exit 1
end
config = stringify_keys(options.to_h)
config['restore_param'] = normalize_arg(ARGV[3])
status = ChefBackup::Runner.new(config).restore
exit(status ? 0 : 1)
end
def stringify_keys(hash)
hash.keys.each { |k| hash[k.to_s] = hash.delete(k) }
hash
end
def normalize_arg(arg)
arg =~ /^snap-\h{8}$/ ? arg : File.expand_path(arg)
end
|
Markdown | UTF-8 | 2,858 | 2.875 | 3 | [] | no_license | Chapter 5: culture: Travel
--------------------------
[Travel](../category/culture/travel/index.html)
-----------------------------------------------
Eastown Theatre, Detroit – for Perspective
==========================================

<span class="s1">It would be unusual today to find a travel agent recommending a sojourn in Detroit as the ideal vacation. The city is, after all, in decline. There are neighbourhoods full of derelict homes, there are shattered theatres and ruined office buildings that were thriving only a few decades ago.</span>
<span class="s1">Yet the idea of going there is far from unreasonable. It has long been fashionable to visit ruins – but only of a very special kind. Announcing you are off on holiday to see what is left of ancient Ephesus, near Izmir on Turkey’s Aegean coast, will raise no eyebrows. We understand that contemplating the beautiful remains of the Library of Celsus can put one in touch with the instability of all human achievement. In its day, the Library at Ephesus must have seemed indestructible. Now we know what can happen to the finest long-term ambitions and the melancholy, bracing truth – hopefully – hits home. We become, in our own lives, more conscious that time is fleeting, that we must not count on the future, that we cannot count on endless good fortune. </span>
<span class="s1">But time dulls the power of the message. The idea that a civilisation lasted a mere seven hundred years before collapsing is not – if one is honest – a terribly disturbing thought. The thought that Piccadilly Circus might have only another 537 years to go, or that by 2714, Tate Modern will be buried under sand, does not freeze the soul or force a radical reassessment of life. </span>
<span class="s1">That’s why one should head for West Oakman Boulevard or East English Village to contemplate contemporary ruins. Less than ten years ago, these places were filled with hope and life; couples were excitedly choosing paint for the nursery; people were planting trees and upgrading their heating system; they were looking forward to the future. </span>
<span class="s1">You should perhaps attend an auction at which a house that would be greatly prized if it was located in Putney or Morningside is sold for a hundred dollars. It has, effectively, no financial value. It has fallen off the edge of the economic universe. </span>
<span class="s1">The point of such travel is not to make us downcast. It is, rather, to make us attend to the fragility of life. We do not know what five years will bring. The fascinating classical remains in Turkey elegantly preach a lesson about history. Detroit offers a crash course in short-term error. </span>
|
JavaScript | UTF-8 | 2,861 | 3.796875 | 4 | [] | no_license | console.log("Bismillah, calculator coy");
const calculator = {
displayNum: "0",
operator: null,
firstNum: null,
waitSecNum: false,
};
function updateDisplay() {
document.querySelector("#displayNum").innerText = calculator.displayNum;
}
function clearCalculator() {
calculator.displayNum = "0";
calculator.operator = null;
calculator.firstNum = null;
calculator.waitSecNum = false;
}
function inputNum(digit) {
if (calculator.waitSecNum && calculator.firstNum === calculator.displayNum) {
calculator.displayNum = digit;
} else {
if (calculator.displayNum === "0") {
calculator.displayNum = digit;
} else {
calculator.displayNum += digit;
}
}
}
function inverse() {
if (calculator.displayNum === "0") {
return;
}
calculator.displayNum = calculator.displayNum * -1;
}
function handleOperator(operator) {
if (!calculator.waitSecNum) {
calculator.operator = operator;
calculator.waitSecNum = true;
calculator.firstNum = calculator.displayNum;
} else {
alert("Sekali aja coy, clear dulu atuh !!");
}
}
function performCalculation() {
if (calculator.firstNum == null || calculator.operator == null) {
alert("Belum dipakai operatornya cuy!!");
return;
}
let result = 0;
if (calculator.operator === "+") {
result = parseInt(calculator.firstNum) + parseInt(calculator.displayNum);
} else if (calculator.operator === "-") {
result = parseInt(calculator.firstNum) - parseInt(calculator.displayNum);
} else if (calculator.operator === "*") {
result = parseInt(calculator.firstNum) * parseInt(calculator.displayNum);
} else if (calculator.operator === "/") {
result = parseInt(calculator.firstNum) / parseInt(calculator.displayNum);
}
const history = {
firstNum: calculator.firstNum,
secondNum: calculator.displayNum,
operator: calculator.operator,
result: result,
};
putHistory(history);
calculator.displayNum = result;
renderHistory();
}
// assign event pada semua button
const buttons = document.querySelectorAll(".button");
for (let button of buttons) {
button.addEventListener("click", function (event) {
// get object
const target = event.target;
// clear
// class list untuk mencari kata 'clear' dalam class yang ada
if (target.classList.contains("clear")) {
clearCalculator();
updateDisplay();
return;
}
// inverse or negative button
if (target.classList.contains("inverse")) {
inverse();
updateDisplay();
return;
}
if (target.classList.contains("equals")) {
performCalculation();
updateDisplay();
return;
}
if (target.classList.contains("operator")) {
handleOperator(target.innerText);
updateDisplay();
return;
}
inputNum(target.innerText);
updateDisplay();
});
}
|
Java | UTF-8 | 2,274 | 3.359375 | 3 | [] | no_license | package Leet;
import Leet.GenericDataStructure.LinkedList;
import sun.awt.image.ImageWatched;
public class L445 {
public static void main(String[] args) {
new L445().run();
}
private void run() {
LinkedList ll1 = new LinkedList();
// ll1.add(ll1, new LinkedList(9));
// ll1.add(ll1, new LinkedList(9));
ll1.add(ll1, new LinkedList(2));
ll1.add(ll1, new LinkedList(3));
LinkedList ll2 = new LinkedList();
ll2.add(ll2, new LinkedList(9));
ll2.add(ll2, new LinkedList(9));
LinkedList ll = addTwoLinkedList(ll1.next, ll2.next);
ll.printList(ll);
}
private LinkedList addTwoLinkedList(LinkedList head1, LinkedList head2) {
if(head1 == null) {
return head2;
}
else if(head2 == null){
return head1;
}
LinkedList temp1 = head1;
LinkedList temp2 = head2;
int len1 = 0;
int len2 = 0;
while (temp1 != null) {
temp1 = temp1.next;
len1++;
}
while (temp2 != null) {
temp2 = temp2.next;
len2++;
}
if (len2 > len1) {
temp1 = head1;
head1 = head2;
head2 = temp1;
}
temp1 = head1;
int i = 0;
while (i < Math.abs(len1 - len2)) {
temp1 = temp1.next;
i++;
}
addEqualParts(temp1, head2);
if(len1!=len2) {
addRemainingPart(head1, temp1);
}
if(carry>0){
LinkedList newNode = new LinkedList(carry);
newNode.next = head1;
head1 = newNode;
}
return head1;
}
int carry = 0;
private void addEqualParts(LinkedList head1 , LinkedList head2) {
if(head1.next!=null){
addEqualParts(head1.next, head2.next);
}
int sum = head1.data+head2.data+carry;
carry = sum/10;
head1.data = sum%10;
}
private void addRemainingPart(LinkedList head1, LinkedList temp) {
if(head1.next!=temp) {
addRemainingPart(head1.next,temp);
}
int sum = head1.data+carry;
carry = sum/10;
head1.data = sum%10;
}
}
|
Java | UTF-8 | 213 | 1.726563 | 2 | [] | no_license | package com.lifx.Messages.Device;
import com.lifx.Messages.DataTypes.Payload;
public class GetLocation extends Payload {
int code = 48;
public GetLocation() {}
public int getCode() {
return code;
}
}
|
C# | UTF-8 | 3,218 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Core.GoogleChart
{
public interface 图表数据支持接口 : 参数支持接口
{
}
[Serializable]
public abstract class 图表数据 : 参数
{
public 图表数据()
{
_数据列表 = new List<List<double>>();
}
public List<List<double>> 数据列表
{
get
{
return _数据列表;
}
}
private List<List<double>> _数据列表;
protected abstract string 类型代码 { get; }
public override string 唯一参数标识
{
get { return "图表数据"; }
}
public override string 参数类型代码
{
get { return "chd"; }
}
protected override string 生成参数值代码()
{
throw new NotImplementedException();
}
}
[Serializable]
public class 文本编码数据 : 图表数据
{
public 文本编码数据()
: base()
{
}
protected override string 类型代码
{
get { return "t"; }
}
protected override string 生成参数值代码()
{
StringBuilder s = new StringBuilder();
foreach (var f in 数据列表)
{
if (s.Length > 0) s.Append('|');
for (int i = 0; i < f.Count; i++)
{
if (i > 0) s.Append(',');
s.Append(f[i]);
}
}
return string.Format("{0}:{1}", 类型代码, s);
}
}
[Serializable]
public class 带有数据换算的文本编码数据 : 文本编码数据
{
public 带有数据换算的文本编码数据()
: base()
{
_换算标准 = new List<范围限定>();
}
public List<范围限定> 换算标准
{
get
{
return _换算标准;
}
}
private List<范围限定> _换算标准;
protected override string 生成参数值代码()
{
StringBuilder s = new StringBuilder();
foreach (var f in 换算标准)
{
if (s.Length > 0) s.Append('|');
s.Append(f.生成代码());
}
return base.生成参数值代码() + "&chds=" + s;
}
}
[Serializable]
public class 范围限定
{
public double 最小值
{
get
{
return _最小值;
}
set
{
_最小值 = value;
}
}
private double _最小值;
public double 最大值
{
get
{
return _最大值;
}
set
{
_最大值 = value;
}
}
private double _最大值;
public string 生成代码()
{
return 最小值 + "," + 最大值;
}
}
}
|
JavaScript | UTF-8 | 2,374 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* Copyright 2018 AppNexus Inc.; Conversant, LLC; DMG Media Limited; Index Exchange, Inc.;
* MediaMath, Inc.; Oath Inc.; Quantcast Corp.; and, Sizmek, Inc.
* Licensed under the terms of the MIT license. See LICENSE file in project root for terms.
*/
/**
* General utility methods
*/
var utils = (function () {
/**
* Converts query string into object of key/values
*
* @param queryString
* @returns {object}
*/
var parseQuery = function (queryString) {
var query = {};
// strip out leading "?"
if (queryString[0] === '?') {
queryString = queryString.substring(1);
}
var pairs = queryString.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if (pair[0]) {
query[pair[0]] = pair[1];
}
}
return query;
};
/**
* Browser compatible method for logging messages. Some browsers (IE)
* do not support console messages at all times
*
* @param {string} type - "log", "error", or "info"
* @param {*} value - value to
*/
var logMessage = function (type, value) {
if (console && (typeof console[type] === 'function')) {
console[type](value);
}
};
/**
* Browser compatible method for listening for message events
*
* @param {window} win
* @param {function} handler
*/
var addWindowMessageListener = function (win, handler) {
win = win || window;
if (win.addEventListener) {
win.addEventListener('message', handler, false);
} else {
win.attachEvent('onmessage', handler); // for IE
}
};
/**
* Parses data passed via postMessage calls.
*
* @param {string|object} data - json string or object
* @returns {*}
*/
var parsePostMessageData = function (data) {
var json = data;
if (typeof data === "string") {
try {
json = JSON.parse(data);
} catch (e) {
}
}
return json;
};
return {
parseQuery: parseQuery,
logMessage: logMessage,
addWindowMessageListener: addWindowMessageListener,
parsePostMessageData: parsePostMessageData
}
})();
export default utils;
|
Python | UTF-8 | 1,507 | 2.59375 | 3 | [] | no_license | from flask.cli import FlaskGroup
from project import create_app, db
from project.api.models import Team, Club
import csv
app = create_app() # new
cli = FlaskGroup(create_app=create_app) # new
@cli.command()
def recreate_db():
db.drop_all()
db.create_all()
db.session.commit()
@cli.command()
def add_teams_data():
try:
with open('data/teams.csv', mode='r')as file:
data = csv.reader(file)
for row ,line in enumerate(data):
if row == 0: continue
db.session.add(Team(id=line[0],
stam_id=line[1],
suffix=line[2],
colors=line[3]))
db.session.commit()
except Exception as e:
db.session.rollback()
print(repr(e))
@cli.command()
def add_clubs_data():
try:
with open('data/clubs.csv', mode='r')as file:
data = csv.reader(file)
for row ,line in enumerate(data):
if row == 0: continue
db.session.add(Club(stam_id=line[0],
name=line[1],
address=line[2],
zip_code=line[3],
city=line[4],
website=line[5]))
db.session.commit()
except Exception as e:
db.session.rollback()
print(repr(e))
if __name__ == '__main__':
cli() |
C++ | UTF-8 | 617 | 2.671875 | 3 | [] | no_license | /*
class SpriteObject:
for specific sprite funtionality
*/
#pragma once
#include "TemplateDrawableObject.h"
class SpriteObject : public TemplateDrawableObject<sf::Sprite> {
public:
void setTexture(sf::Texture* t, sf::Vector2f pos, sf::IntRect intRect) override;
void setIntRect(sf::IntRect portion) override { m_obj.setTextureRect(portion); }
void flipObj(int dir) override { m_obj.setScale(dir, 1); }
virtual void setColor(sf::Color color, bool) override { m_obj.setColor(color); }
virtual sf::Color getColor() const override { return sf::Color::Transparent; }
private:
}; |
Markdown | UTF-8 | 1,050 | 3.390625 | 3 | [] | no_license | # Class 4 reading notes
## From the Duckett HTML Book
### Chapter 4: "Links" (pg 74-93)
* URL means Uniform Resource Locator
* To link to parent folder from current page:
* `<a href = "..\/pagename.html">Link text</a>`
* To link to grandparent folder from current page:
* `<a href = "..\/..\/pagename.html">Link text</a>`
* The "target" attribute in `<a>` tag opens link page in a new window
* To link within a page, use "ID attributes" in HTML
### Chapter 15: "Layout" (pg 358-404)
* CSS treats each element as if it's in its own box
* Block level elements start on their own new line. (Examples: \<h1>, \<p>, \<ul>, \<li>)
## From the Duckett JS book
### Chapter 3: "Functions, Methods & Objects (pg 86-99 ONLY)
* Functions let you group a series of statements together to perform a specific task
* Also offers a way to STORE the steps needed to achieve a task. Script can ask a function to perform tasks as and when they are required. (i.e. when user clicks a specific element.)
### Article: "6 Reasons For Pair Programming"
|
Java | UTF-8 | 2,560 | 2.1875 | 2 | [] | no_license | package name.ixr.nano.common.context;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.HttpHeaders;
import name.ixr.nano.common.utils.AntPathMatcherUtils;
import name.ixr.nano.common.utils.I18nUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import javax.print.attribute.standard.ReferenceUriSchemesSupported;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* HttpRequest : TODO: yuuji
* yuuji 4:38 PM 11/28/13
*/
public class HttpRequest {
private static final String HTML_SPLIT = ".";
private static final String URI_SPLIT = "/";
private static final String PARAM_BEGIN = "?";
private io.netty.handler.codec.http.HttpRequest source;
private String host;
private String uri;
private String ref;
private Locale locale;
private Map<String, Cookie> cookies = new HashMap<>();
public Cookie getCookie(String name) {
return cookies.get(name);
}
public HttpRequest(io.netty.handler.codec.http.HttpRequest source) {
String language = source.headers().get(HttpHeaders.Names.ACCEPT_LANGUAGE);
this.locale = I18nUtils.toLocale(language);
this.source = source;
this.host = source.headers().get(HttpHeaders.Names.HOST);
this.ref = source.headers().get(HttpHeaders.Names.REFERER);
this.ref = StringUtils.substringAfter(this.ref, this.host);
setUri(source.getUri());
String cookies = source.headers().get(HttpHeaders.Names.COOKIE);
if (StringUtils.isNotBlank(cookies)) {
Set<Cookie> cookieSet = CookieDecoder.decode(cookies);
for (Cookie cookie : cookieSet) {
this.cookies.put(cookie.getName(), cookie);
}
}
}
public HttpRequest(String url) {
setUri(url);
}
public Locale getLocale() {
return locale;
}
public void setUri(String uri) {
this.uri = url(uri);
}
public io.netty.handler.codec.http.HttpRequest getSource() {
return source;
}
public String getHost() {
return host;
}
public String getRef() {
return url(ref);
}
private String url(String url) {
if ("/".equals(url) || AntPathMatcherUtils.match("/index.*", url)) {
return "/pages/index.htm";
} else {
return url;
}
}
public String getUri() {
return uri;
}
}
|
C# | UTF-8 | 3,915 | 3.578125 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Common.ExtensionMethod
{
public static class StringExtension
{
/// <summary>
/// count words in this string
/// </summary>
/// <param name="str">string</param>
/// <returns>int</returns>
public static int WordCount(this string str)
{
return str.Split(new[] {' ', '.', '?', '!'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
/// <summary>
/// get left string of a string
/// </summary>
/// <param name="str">string</param>
/// <param name="count">how many element will take</param>
/// <returns>string</returns>
public static string Left(this string str, int count)
{
return str.Substring(0, count);
}
/// <summary>
/// get right string of a string
/// </summary>
/// <param name="str">string</param>
/// <param name="count">how many element will take</param>
/// <returns>string</returns>
public static string Right(this string str, int count)
{
return str.Substring(str.Length - count, count);
}
public static string Mid(this string str, int index, int count)
{
return str.Substring(index, count);
}
public static string Take(this string str, int count, bool ellipsis = false)
{
var lengthToTake = Math.Min(count, str.Length);
var cutDownString = str.Substring(0, lengthToTake);
if (ellipsis && lengthToTake < str.Length)
cutDownString += "...";
return cutDownString;
}
public static string Skip(this string str, int count)
{
var startIndex = Math.Min(count, str.Length);
var cutDownString = str.Substring(startIndex - 1);
return cutDownString;
}
public static string Reverse(this string str)
{
var chars = str.ToCharArray();
Array.Reverse(chars);
return new String(chars);
}
public static string With(this string str, params object[] args)
{
return string.Format(str, args);
}
public static string StripHtml(this string html)
{
if (string.IsNullOrEmpty(html))
return string.Empty;
return Regex.Replace(html, @"<[^>]*>", string.Empty);
}
public static bool Match(this string str, string pattern)
{
return Regex.IsMatch(str, pattern);
}
public static string[] SplitIntoChunks(this string str, int chunkSize)
{
if (string.IsNullOrEmpty(str))
return new[] {""};
var stringLength = str.Length;
var chunksRequired = (int) Math.Ceiling(stringLength/(decimal) chunkSize);
var stringArray = new string[chunksRequired];
var lengthRemaining = stringLength;
for (var i = 0; i < chunksRequired; i++)
{
var lengthToUse = Math.Min(lengthRemaining, chunkSize);
var startIndex = chunkSize*i;
stringArray[i] = str.Substring(startIndex, lengthToUse);
lengthRemaining = lengthRemaining - lengthToUse;
}
return stringArray;
}
public static string Join(this string str,IEnumerable<object> array)
{
if (array == null)
return "";
return string.Join(str, array.ToArray());
}
public static string Join(this string seperator,object[] array)
{
if (array == null)
return "";
return string.Join(seperator, array);
}
}
} |
PHP | UTF-8 | 2,595 | 2.59375 | 3 | [] | no_license | <?php
//* This file handles pages, but only exists for the sake of child theme forward compatibility.
//* Add custom body class to the head
add_filter( 'body_class', 'thegreenman_body_class_contact' );
function thegreenman_body_class_contact( $classes ) {
$classes[] = 'contact';
return $classes;
}
add_action( 'genesis_entry_header', 'genesis_do_post_title' );
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'contact_fields' );
//* Remove the post content and add our tabbed content
function contact_fields() {
if ( get_theme_mod( 'bwpy_titles' ) == 1 ) :
?> <h1 class="entry-title"> <?php the_title();?> </h1> <?php
else :
endif;
?>
<div class="contact-address one-third first" ><?php
if( get_field('business_name', 'option') ): ?>
<div itemscope itemtype="http://schema.org/LocalBusiness"><a itemprop="url" href=" <?php echo site_url() ?> "></a><div itemprop="name"><strong><?php the_field('business_name', 'option'); ?></strong></div>
<?php endif;
echo '<p>';
echo '<div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">';
echo '<span itemprop="streetAddress">';
if( get_field('street_address', 'option') ):
$street_adress = the_field('street_address', 'option');
echo '</span></br>';
endif;
echo '<span itemprop="addressLocality">';
if( get_field('suburb', 'option') ):
$suburb = the_field('suburb', 'option');
echo '</span></br>';
endif;
echo '<span itemprop="addressRegion">';
if( get_field('state', 'option') ):
$state = the_field('state', 'option');
endif;
echo '<span itemprop="addressCountry">';
if( get_field('country', 'option') ):
$country = the_field('country', 'option');
endif;
echo '</span> <span itemprop="postalCode">';
if( get_field('postcode', 'option') ):
$postcode = the_field('postcode', 'option');
endif;
echo '</span>';
echo '</p>';
echo '<p> P ';
echo '<span property="telephone">';
if( get_field('phone_number', 'option') ): ?>
<?php the_field('phone_number', 'option');
echo '</span>';
endif;
echo '<br > M ';
echo '<span property="telephone">';
if( get_field('mobile_number', 'option') ): ?>
<?php the_field('mobile_number', 'option'); ?></p> <?php
echo '</span>';
endif;
echo '</div>';
?></div> </div>
<div class="two-thirds"> <?php if( get_field('contact_message_above_form', 'option') ):
$postcode = the_field('contact_message_above_form', 'option');
endif;
echo do_shortcode('[contact]' );?>
</div><?php
}
genesis();
|
Markdown | UTF-8 | 503 | 3.421875 | 3 | [] | no_license | ## 183. Customers Who Never Order(Easy)
requirement: all customers who never order anything.
example:
table name : Customers
| Id | Name |
|----|-------|
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
table name : Orders
| Id | CustomerId |
|----|------------|
| 1 | 3 |
| 2 | 1 |
=>
| Customers |
|-----------|
| Henry |
| Max |
### solution:
```
SELECT Name AS 'Customers'
FROM Customers
WHERE Id NOT IN (SELECT CustomerId FROM Orders);
```
|
Java | UTF-8 | 1,498 | 2.328125 | 2 | [] | no_license | package gd.rf.theoneboringmancompany.growham.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import gd.rf.theoneboringmancompany.growham.Main;
import gd.rf.theoneboringmancompany.growham.actors.Back;
import gd.rf.theoneboringmancompany.growham.actors.score.ScoreTable;
import gd.rf.theoneboringmancompany.growham.actors.score.Time;
import gd.rf.theoneboringmancompany.growham.actors.score.Who;
import gd.rf.theoneboringmancompany.growham.tools.MyScreen;
import gd.rf.theoneboringmancompany.growham.tools.Settings;
public class ScoreScreen extends MyScreen {
public final static int NUMBER = 2;
private Music music;
public ScoreScreen(Main main) {
super(main);
}
@Override
public void show() {
main.stage.addActor(new Back(main, MenuScreen.NUMBER));
main.stage.addActor(new ScoreTable(main));
main.stage.addActor(new Who(main));
main.stage.addActor(new Time(main));
music = Gdx.audio.newMusic(Gdx.files.internal(Settings.Path.Audio.Music.SCORES));
music.setLooping(true);
music.setVolume(Settings.MusicAndSound.MUSIC_VOLUME);
music.play();
}
@Override
public void render(float delta) {
super.render(delta);
main.backInput(MenuScreen.NUMBER);
}
@Override
public void hide() {
music.pause();
super.hide();
}
@Override
public void dispose() {
super.dispose();
music.dispose();
}
}
|
Java | UTF-8 | 2,217 | 2.46875 | 2 | [] | no_license | package com.vlms.sjsu.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.vlms.sjsu.service.ServiceProxy;
/**
* Servlet implementation class DeleteMovieAction
*/
public class DeleteMovieAction extends HttpServlet {
private static final long serialVersionUID = 1L;
ServiceProxy proxy = new ServiceProxy();
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteMovieAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
proxy.setEndpoint("http://localhost:8080/VLMS/services/Service");
HttpSession session = request.getSession(true);
String nextJSP = "";
if(null == session.getAttribute("user"))
nextJSP = "/View/accessControl.jsp";
else{
String movieID = request.getParameter("movieID");
String movieName = request.getParameter("movieName");
System.out.println("INSIDE 1 :::::");
String qdone = proxy.deleteMovie(movieID);
if (qdone.equalsIgnoreCase("true")) {
System.out.println("INSIDE 2 :::::");
request.setAttribute("message", "Deleted "+movieName+" from Database!");
}
else{
System.out.println("INSIDE 3 :::::");
request.setAttribute("message",
"Unable to Delete Movie! : " + qdone);
}
nextJSP = "/View/AdminHome.jsp";
}
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}
}
|
JavaScript | UTF-8 | 433 | 2.875 | 3 | [] | no_license | var calculator = function() {
function add(v1, v2) {
return v1 + v2;
};
function subtract(v1, v2) {
return v1 - v2;
};
function multiply(v1, v2) {
return v1 * v2;
};
function divide(v1, v2) {
return v1 / v2 + 0;
}
return {
add: add,
subtract: subtract,
multiply: multiply,
divide: divide
};
};
module.exports = calculator;
|
C# | UTF-8 | 519 | 2.953125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreatingQuaqe
{
class Program
{
static void Main(string[] args)
{
Queue<int> callerIds = new Queue<int>();
callerIds.Enqueue(1);
callerIds.Enqueue(2);
callerIds.Enqueue(3);
callerIds.Enqueue(4);
foreach (var id in callerIds)
Console.Write(id); //prints 1234
}
}
}
|
Markdown | UTF-8 | 1,027 | 2.890625 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "Typography of A. Lange & Söhne"
date: 2017-01-09 01:17:50 -0500
external-url: https://andlarry.com/journal/watch-the-type
tags:
- watches
- design
- typography
---
&Larry has a terrific writeup of the intricate focus on typography that the
A. Lange & Söhne watchmakers employ when designing watches. The design of
watches has always fascinated me for the strikingly limited functionality
of a watch: hours, minutes, and sometimes seconds, days, and so forth. The
most advanced watches have a stopwatch capability, but that is as complex
as I have seen them before.
The discussion centers around typography of this particular brand of
watches, but at the end gets into a more general discussion of how many
companies are more aware of how their typography impacts their brand. The
focus on typography from companies like Apple and Google is interesting. Su
Jia Xian, the author of this piece, calls on designers to learn more about
typography and factor typographic choices into design decisions.
|
PHP | UTF-8 | 3,921 | 2.9375 | 3 | [
"MIT"
] | permissive | <?php
namespace Rakit\Curl;
class Response {
protected $info;
protected $body;
protected $error;
protected $error_message;
protected $header_string;
protected $parsed_headers = array();
protected $cookie = array();
public function __construct(array $info, $response, $errno, $error_message)
{
$this->errno = $errno;
$this->error_message = $error_message;
$this->body = substr($response, $info['header_size']);
$this->header_string = substr($response, 0, $info['header_size']);
$this->info = $info;
$this->parsed_headers = $this->parseHeaderString($this->header_string);
}
public function isNotFound()
{
return $this->getStatus() == 404;
}
public function isRedirect()
{
$status = $this->getStatus();
if(substr($status, 0, 1) == '3') return TRUE;
}
public function error()
{
return $this->errno != 0;
}
public function getErrno()
{
return $this->errno;
}
public function getError()
{
return $this->getErrno();
}
public function getErrorMessage()
{
return $this->error_message;
}
public function getHeader($key, $default = null)
{
$key = strtolower($key);
return isset($this->parsed_headers[$key]) ? $this->parsed_headers[$key] : $default;
}
public function getHeaders()
{
return $this->parsed_headers;
}
public function getCookie()
{
return $this->cookie;
}
public function length()
{
return strlen($this->getbody()) + strlen($this->getHeaderString());
}
public function getStatus()
{
return $this->getInfo('http_code', 0);
}
public function getContentType()
{
return $this->getInfo('content_type', FALSE);
}
public function isHtml()
{
return $this->getContentType() == 'text/html';
}
public function getInfo($key, $default = null)
{
return isset($this->info[$key])? $this->info[$key] : $default;
}
public function getAllInfo()
{
return $this->info;
}
public function getBody()
{
return $this->body;
}
public function getHeaderString()
{
return $this->header_string;
}
public function toArray()
{
$data = array(
'headers' => $this->getHeaders(),
'cookie' => $this->getCookie(),
'body' => $this->getBody()
);
return array_merge($this->info, $data);
}
public function __toString()
{
return (string) $this->getBody();
}
protected function parseHeaderString($header_string)
{
$exp = explode("\n", $header_string);
$headers = array();
foreach($exp as $header) {
$header = trim($header);
if(preg_match('/^HTTP\/(?<v>[^ ]+)/', $header, $match)) {
$headers['http_version'] = $match['v'];
$this->info['http_version'] = $match['v'];
} elseif("" == $header) {
continue;
} else {
list($key, $value) = explode(':', $header, 2);
$key = strtolower($key);
$headers[$key] = trim($value);
if($key == 'set-cookie') {
$this->parseCookie($value);
}
}
}
return $headers;
}
protected function parseCookie($cookie_string)
{
$exp = explode(';', $cookie_string);
$cookie['value'] = array_shift($exp);
foreach($exp as $i => $data) {
$_parse = explode('=', $data, 2);
$key = $_parse[0];
$value = isset($_parse[1])? $_parse[1] : "";
$cookie[trim(strtolower($key))] = trim($value);
}
$this->cookie = $cookie;
}
}
|
JavaScript | UTF-8 | 1,611 | 2.609375 | 3 | [
"MIT"
] | permissive | // use helper method to generate an array of image urls. We have 34 frames in total
var frames = SpriteSpin.sourceArray('slider/images/elephant/DSC_{frame}.jpg', {
frame: [407, 436],
digits: 4
});
// these are the frame numbers that will show a detail bubble
var details = [407, 436];
// the current index in the details array
var detailIndex = 0;
var spin = $('.elephant');
// initialise spritespin
spin.spritespin({
source: frames,
width: 500,
sense: 2,
height: 334,
sizeMode: 'fit',
scrollThreshold: 3000,
frameTime: 100, // Time in ms between updates. 40 is exactly 25 FPS
detectSubsampling: false,
animate: true
});
// get the api object. This is used to trigger animation to play up to a specific frame
var api = spin.spritespin("api");
function buildingSpin(frameToPlayTo, ReverseTF) {
spin.bind("onLoad", function() {
var data = api.data;
console.log('loaded');
$('.rotateButton').css({
opacity: 0,
display: "inline-block"
}).animate({
opacity: 1
}, 'slow');
$('.spinner').css({
opacity: 1,
display: "none"
}).animate({
opacity: 0
}, 'slow');
}).bind("onFrame", function(e, data) {
});
function setDetailIndex(index) {
detailIndex = index;
if (detailIndex < 0) {
detailIndex = details.length - 1;
}
if (detailIndex >= details.length) {
detailIndex = 0;
}
api.playTo(details[detailIndex]);
}
api.playTo(frameToPlayTo);
}
|
JavaScript | UTF-8 | 2,947 | 3.390625 | 3 | [] | no_license | /**
* Module for CardTable.
*
* @author: ProfessorPotatis
* @version 1.0.0
*/
'use strict';
/**
* Creates a JavaScript CardTable instance.
*
* @constructor
* @param {string} pShowHand - Players cards on hand.
* @param {string} pSumCards - Players sum of cards on hand.
* @param {string} dShowHand - Dealers cards on hand.
* @param {string} dSumCards - Dealers sum of cards on hand.
*
*/
function CardTable(pShowHand = '', pSumCards = '', dShowHand = '', dSumCards = '') {
let _pShowHand, _pSumCards, _dShowHand, _dSumCards;
Object.defineProperty(this, 'pShowHand', {
get: function() {
return _pShowHand;
},
set: function(pHand) {
let theHand = pHand;
_pShowHand = theHand;
}
});
Object.defineProperty(this, 'pSumCards', {
get: function() {
return _pSumCards;
},
set: function(pSum) {
let theSum = pSum;
_pSumCards = theSum;
}
});
Object.defineProperty(this, 'dShowHand', {
get: function() {
return _dShowHand;
},
set: function(dHand) {
let theHand = dHand;
_dShowHand = theHand;
}
});
Object.defineProperty(this, 'dSumCards', {
get: function() {
return _dSumCards;
},
set: function(dSum) {
let theSum = dSum;
_dSumCards = theSum;
}
});
// Initialize the properties through the setters.
this.pShowHand = pShowHand;
this.pSumCards = pSumCards;
this.dShowHand = dShowHand;
this.dSumCards = dSumCards;
}
/**
* Clones new instance object and sets new parameters.
*
* @returns {Object} - Copy.
*/
CardTable.prototype.clone = function(p1, p2, p3, p4) {
let copy = Object.create(CardTable.prototype);
this.pShowHand = p1;
this.pSumCards = p2;
this.dShowHand = p3;
this.dSumCards = p4;
return copy;
};
/**
* Returns string representing result of game.
*
* @returns <String>
*/
CardTable.prototype.printResult = function() {
let str = '';
str += 'Player:' + this.pShowHand + ' (' + this.pSumCards + ')';
if (this.pSumCards > 21) {
str += ' BUSTED!\n';
str += 'Dealer: -\n';
str += 'Dealer wins!';
} else if (this.pSumCards === 21 || this.pSumCards < 21 && this.pShowHand.length === 15) {
str += '\nDealer: -\n';
str += 'Player wins!';
} else if (this.dSumCards > 21) {
str += '\nDealer:' + this.dShowHand + ' (' + this.dSumCards + ')';
str += ' BUSTED!\n';
str += 'Player wins!';
} else if (this.dSumCards === 21 || this.dSumCards === this.pSumCards || this.dSumCards > this.pSumCards) {
str += '\nDealer:' + this.dShowHand + ' (' + this.dSumCards + ')\n';
str += 'Dealer wins!';
}
return str;
};
/**
* Exports.
*/
module.exports = CardTable;
|
Python | UTF-8 | 2,195 | 2.6875 | 3 | [] | no_license | import pygame,sys,random
from pygame.locals import *
pygame.init()
fen=pygame.display.set_mode((181,179))
etat_initial=[[3,2,7],[8,6,9],[1,5,4]]
def position_case_vide (tableau):
for i in range(3):
for j in range(3):
if tableau[i][j] ==9:
return [i,j]
def initImages():#Chargement images
images=[]
for i in range(9):
images.append(pygame.image.load("t"+str(i)+".png"))
return images
def estEtatFinal(t, etat_final):
return etat_final == t
def numero(t, x, y):
return t[x][y]
from copy import deepcopy
def permuter(t, c1, c2):
tperm = deepcopy(t)
a = tperm[c1[0]][c1[1]]
tperm[c1[0]][c1[1]] = tperm[c2[0]][c2[1]]
tperm[c2[0]][c2[1]] = a
return tperm
def valid(x, y):
return x > -1 and x < 3 and y > -1 and y < 3
def transitions(t):
pos = position_case_vide(t)
tab = []
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
for i in range(4):
if (valid(pos[0] + dx[i], pos[1] + dy[i])):
tab.append([pos[0] + dx[i], pos[1] + dy[i]])
nvmatrice = []
for i in tab:
nvmatrice.append(permuter(t, pos, i))
return nvmatrice
etat_final=[[3,2,7],[8,6,4],[1,9,5]]
images=initImages()
#affichage du tableau
def affiche(tableau,images):
for i in range(3):
for j in range(3):
numeroCase=tableau[i][j]
case=images[numeroCase-1]
fen.blit(case,(i*60,j*60))
def afficher_taquin (t):
for row in t:
print('+++++++++++++')
print('|',row[0],'|',row[1],'|',row[2],'|')
print('+++++++++++++')
nb=0
trace= []
visited= []
success= False
def dfs(node, etat):
global success
if (success==False and node not in visited):
if estEtatFinal(node,etat):
trace.append(node)
success=True
trace.append(node)
visited.append(node)
tab=transitions(node)
for w in tab:
if w not in visited and success==False:
dfs(w,etat)
dfs(etat_initial,etat_final)
tableau = etat_initial = [[3, 2, 7], [8, 6, 9], [1, 5, 4]]
for k in trace:
nb=nb+1
affiche(k,images)
afficher_taquin(tableau)
#for evenement in pygame.event.get():
# affiche(tableau, images)
# if evenement.type == QUIT:
# pygame.quit()
#sys.exit()
pygame.display.update()
pygame.time.wait(2000)
if(nb==len(trace)):
pygame.time.wait(20000) |
PHP | UTF-8 | 621 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @copyright Copyright (c) 2016 by 1-more-thing (http://1-more-thing.com) All rights reserved.
* @license BSD
*/
namespace airmoi\FileMaker\Command;
use airmoi\FileMaker\Object\Result;
/**
* Command class that finds one random record.
* Create this command with {@link FileMaker::newFindAnyCommand()}.
*
* @package FileMaker
*/
class FindAny extends Find
{
/**
*
* @return Result
*/
public function execute()
{
$params = $this->getCommandParams();
$params['-findany'] = true;
return $this->getResult($this->fm->execute($params));
}
}
|
Python | UTF-8 | 7,049 | 3.015625 | 3 | [
"BSD-3-Clause"
] | permissive | """
Four sets of routing tables are produced for the same network:
* With keys assigned using a Hilbert Curve (this will tend to ensure that
similar keys originated in physical proximal chips)
* With keys assigned using the (x, y, p) of each core - a common SpiNNaker
approach
* With keys assigned using the (x, y, z, p) of each core
* With 12-bit keys randomly assigned to each core
Routing is performed by the NER algorithm, as implemented in Rig.
"""
from collections import OrderedDict
import random
from rig.bitfield import BitField
from rig.netlist import Net
from rig.geometry import to_xyz, minimise_xyz, shortest_torus_path_length
from rig.place_and_route import Cores, Machine
from rig.place_and_route.place.hilbert import hilbert_chip_order
from rig.place_and_route.route.ner import route
from rig.routing_table import routing_tree_to_tables
from six import iteritems, itervalues
from common import dump_routing_tables
def make_routing_tables():
# Create a perfect SpiNNaker machine to build against
machine = Machine(12, 12)
# Assign a vertex to each of the 17 application cores on each chip
vertices = OrderedDict(
((x, y, p), object()) for x, y in machine for p in range(1, 18)
)
# Generate the vertex resources, placements and allocations (required for
# routing)
vertices_resources = OrderedDict(
(vertex, {Cores: 1}) for vertex in itervalues(vertices)
)
placements = OrderedDict(
(vertex, (x, y)) for (x, y, p), vertex in iteritems(vertices)
)
allocations = OrderedDict(
(vertex, {Cores: slice(p, p+1)}) for (x, y, p), vertex in
iteritems(vertices)
)
# Compute the distance dependent probabilities - this is a geometric
# distribution such that each core has a 50% chance of being connected to
# each core on the same chip, 25% on chips one hop away, 12.5% on chips two
# hops away, etc.
p = 0.5
probs = {d: p*(1 - p)**d for d in
range(max(machine.width, machine.height))}
p = 0.3
dprobs = {d: p*(1 - p)**d for d in
range(max(machine.width, machine.height))}
# Compute offsets to get to centroids
vector_centroids = list()
for d in (5, 6, 7):
for i in range(d + 1):
for j in range(d + 1 - i):
vector_centroids.append((i, j, d - i - j))
# Make the nets, each vertex is connected with distance dependent
# probability to other vertices.
random.seed(123)
nets = OrderedDict()
for source_coord, source in iteritems(vertices):
# Convert source_coord to xyz form
source_coord_xyz = minimise_xyz(to_xyz(source_coord[:-1]))
# Add a number of centroids
x, y, z = source_coord_xyz
possible_centroids = [minimise_xyz((x + i, y + j, z + k)) for
i, j, k in vector_centroids]
n_centroids = random.choice(17*(0, ) + (1, 1) + (2, ))
centroids = random.sample(possible_centroids, n_centroids)
# Construct the sinks list
sinks = list()
for sink_coord, sink in iteritems(vertices):
# Convert sink_coord to xyz form
sink_coord = minimise_xyz(to_xyz(sink_coord[:-1]))
# Get the path length to the original source
dist = shortest_torus_path_length(source_coord_xyz, sink_coord,
machine.width, machine.height)
if random.random() < probs[dist]:
sinks.append(sink)
continue
# See if the sink is connected to the centre of any of the
# centroids.
for coord in centroids:
dist = shortest_torus_path_length(
coord, sink_coord, machine.width, machine.height
)
if random.random() < dprobs[dist]:
sinks.append(sink)
break
# Add the net
nets[source_coord] = Net(source, sinks)
rig_nets = list(itervalues(nets)) # Just the nets
# Determine how many bits to use in the keys
xyp_fields = BitField(32)
xyp_fields.add_field("x", length=8, start_at=24)
xyp_fields.add_field("y", length=8, start_at=16)
xyp_fields.add_field("p", length=5, start_at=11)
xyzp_fields = BitField(32)
xyzp_fields.add_field("x", length=8, start_at=24)
xyzp_fields.add_field("y", length=8, start_at=16)
xyzp_fields.add_field("z", length=8, start_at=8)
xyzp_fields.add_field("p", length=5, start_at=3)
hilbert_fields = BitField(32)
hilbert_fields.add_field("index", length=16, start_at=16)
hilbert_fields.add_field("p", length=5, start_at=11)
random.seed(321)
rnd_fields = BitField(32)
rnd_fields.add_field("rnd", length=12, start_at=20)
rnd_seen = set()
# Generate the routing keys
net_keys_xyp = OrderedDict()
net_keys_xyzp = OrderedDict()
net_keys_hilbert = OrderedDict()
net_keys_rnd = OrderedDict()
for i, (x, y) in enumerate(chip for chip in hilbert_chip_order(machine) if
chip in machine):
# Add the key for each net from each processor
for p in range(1, 18):
# Get the net
net = nets[(x, y, p)]
# Construct the xyp key/mask
net_keys_xyp[net] = xyp_fields(x=x, y=y, p=p)
# Construct the xyzp mask
x_, y_, z_ = minimise_xyz(to_xyz((x, y)))
net_keys_xyzp[net] = xyzp_fields(x=x_, y=y_, z=abs(z_), p=p)
# Construct the Hilbert key/mask
net_keys_hilbert[net] = hilbert_fields(index=i, p=p)
# Construct the random 12 bit value field
val = None
while val is None or val in rnd_seen:
val = random.getrandbits(12)
rnd_seen.add(val)
net_keys_rnd[net] = rnd_fields(rnd=val)
# Route the network and then generate the routing tables
constraints = list()
print("Routing...")
routing_tree = route(vertices_resources, rig_nets, machine, constraints,
placements, allocations)
# Write the routing tables to file
for fields, desc in ((net_keys_xyp, "xyp"),
(net_keys_xyzp, "xyzp"),
(net_keys_hilbert, "hilbert"),
(net_keys_rnd, "rnd")):
print("Getting keys and masks...")
keys = OrderedDict(
(net, (bf.get_value(), bf.get_mask())) for net, bf in
iteritems(fields)
)
print("Constructing routing tables for {}...".format(desc))
tables = routing_tree_to_tables(routing_tree, keys)
print([len(x) for x in itervalues(tables)])
print("Writing to file...")
fn = "uncompressed/centroid_{}_{}_{}.bin".format(
machine.width, machine.height, desc)
with open(fn, "wb+") as f:
dump_routing_tables(f, tables)
if __name__ == "__main__":
make_routing_tables()
|
Java | UTF-8 | 2,378 | 3.96875 | 4 | [] | no_license | package com.chandu.recursion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Print inorder traversal of tree using recursion
* Try the same without using recursion
*/
public class InorderTreeTraversal {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter data to root node , if nothing is present enter -1 ");
int input = Integer.parseInt(br.readLine());
if(input == -1){
System.exit(1);
}
TreeNode rootNode = createNode(input);
constructTree(rootNode);
inorderTraversal(rootNode);
}
private static void inorderTraversal(TreeNode rootNode) {
if (rootNode != null) {
inorderTraversal(rootNode.left);
System.out.println(rootNode.data);
inorderTraversal(rootNode.right);
}
}
public static void constructTree(TreeNode rootNode) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.println("Enter data to Tree node , if nothing is present enter -1 ");
int input = Integer.parseInt(br.readLine());
if (input == -1) break;
TreeNode currentNode = createNode(input);
createBst(rootNode, currentNode);
}
}
private static void createBst(TreeNode rootNode, TreeNode currentNode) {
TreeNode prev = null;
while(rootNode != null) {
prev = rootNode;
if (rootNode.data > currentNode.data) {
rootNode = rootNode.left;
} else {
rootNode = rootNode.right;
}
}
if (prev != null && prev.data > currentNode.data) {
prev.left = currentNode;
} else if (prev != null) {
prev.right = currentNode;
}
}
public static TreeNode createNode(int data) {
return new TreeNode(data,null,null);
}
}
class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
TreeNode() {}
public TreeNode(int data, TreeNode left, TreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
}
|
TypeScript | UTF-8 | 844 | 2.921875 | 3 | [] | no_license | import { ActionType } from './type'
import { Tool, pencil, eraser } from 'models/tool'
export const toolsReducer = (
tools: Tool[] = [pencil, eraser],
action: ActionType
): Tool[] => {
switch(action.type) {
case 'SELECT_TOOL':
console.log('select tool', action.tool)
return tools.map(t =>
Object.assign(
Object.create(t),
{ selected: t.title === action.tool.title }
)
)
case 'SET_WIDTH':
return tools.map(t =>
t.selected ?
Object.assign(
Object.create(t),
{ lineWidth: action.width }
) : t
)
case 'SET_COLOR':
return tools.map(t =>
t.selected ?
Object.assign(
Object.create(t),
{ color: action.color }
) : t
)
default: return tools
}
}
|
C# | UTF-8 | 6,464 | 2.5625 | 3 | [] | no_license | extern alias CZ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinstatApi.ViewModel;
namespace DesktopFinstatApiTester.ViewModel
{
public class Limit : ViewModel, IModelViewModel<FinstatApi.ViewModel.Limit>, IModelViewModel<CZ::FinstatApi.ViewModel.Limit>
{
public const string CurrentProperty = "Current";
public const string MaxProperty = "Max";
public const string LimitObjectProperty = "LimitObject";
public Limit()
{
PropertyChanged += Limit_PropertyChanged;
}
private long _current;
public long Current
{
get { return _current; }
set
{
if (_current != value)
{
_current = value;
RaisePropertyChanged(CurrentProperty);
}
}
}
private long _max;
public long Max
{
get { return _max; }
set
{
if (_max != value)
{
_max = value;
RaisePropertyChanged(MaxProperty);
}
}
}
private void Limit_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (new[] { CurrentProperty, MaxProperty }.Contains(e.PropertyName))
{
this.RaisePropertyChanged(LimitObjectProperty);
}
}
public void FromModel(FinstatApi.ViewModel.Limit model)
{
if (model != null)
{
Current = model.Current;
Max = model.Max;
}
}
public FinstatApi.ViewModel.Limit ToModel(FinstatApi.ViewModel.Limit model)
{
if (model == null)
{
model = new FinstatApi.ViewModel.Limit();
}
model.Current = Current;
model.Max = Max;
return model;
}
public void FromModel(CZ::FinstatApi.ViewModel.Limit model)
{
if (model != null)
{
Current = model.Current;
Max = model.Max;
}
}
public CZ::FinstatApi.ViewModel.Limit ToModel(CZ::FinstatApi.ViewModel.Limit model)
{
if(model == null)
{
model = new CZ::FinstatApi.ViewModel.Limit();
}
model.Current = Current;
model.Max = Max;
return model;
}
}
public class Limits : ViewModel, IModelViewModel<FinstatApi.ViewModel.Limits>, IModelViewModel<CZ::FinstatApi.ViewModel.Limits>
{
public const string DailyProperty = "Daily";
public const string MonthlyProperty = "Monthly";
public const string LimitsObjectProperty = "LimitsObject";
public Limits()
{
PropertyChanged += Limits_PropertyChanged;
Daily = new Limit();
Monthly = new Limit();
}
private Limit _daily;
public Limit Daily
{
get { return _daily; }
set
{
if (_daily != value)
{
if(_daily != null)
{
_daily.PropertyChanged -= _daily_PropertyChanged;
}
_daily = value;
if (_daily != null)
{
_daily.PropertyChanged += _daily_PropertyChanged;
}
}
}
}
private Limit _monthly;
public Limit Monthly
{
get { return _monthly; }
set
{
if (_monthly != value)
{
if (_monthly != null)
{
_monthly.PropertyChanged -= _monthly_PropertyChanged;
}
_monthly = value;
if (_monthly != null)
{
_monthly.PropertyChanged += _monthly_PropertyChanged;
}
}
}
}
private void _monthly_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == Limit.LimitObjectProperty)
{
RaisePropertyChanged(MonthlyProperty);
}
}
private void _daily_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == Limit.LimitObjectProperty)
{
RaisePropertyChanged(DailyProperty);
}
}
private void Limits_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (new[] { DailyProperty, MonthlyProperty }.Contains(e.PropertyName))
{
this.RaisePropertyChanged(LimitsObjectProperty);
}
}
public void FromModel(FinstatApi.ViewModel.Limits model)
{
if (model != null)
{
Daily.FromModel(model?.Daily);
Monthly.FromModel(model.Monthly);
}
}
public FinstatApi.ViewModel.Limits ToModel(FinstatApi.ViewModel.Limits model)
{
if (model == null)
{
model = new FinstatApi.ViewModel.Limits();
}
model.Daily = Daily.ToModel(new FinstatApi.ViewModel.Limit());
model.Monthly = Monthly.ToModel(new FinstatApi.ViewModel.Limit());
return model;
}
public void FromModel(CZ::FinstatApi.ViewModel.Limits model)
{
if(model != null)
{
Daily.FromModel(model?.Daily);
Monthly.FromModel(model.Monthly);
}
}
public CZ::FinstatApi.ViewModel.Limits ToModel(CZ::FinstatApi.ViewModel.Limits model)
{
if (model == null)
{
model = new CZ::FinstatApi.ViewModel.Limits();
}
model.Daily = Daily.ToModel(new CZ::FinstatApi.ViewModel.Limit());
model.Monthly = Monthly.ToModel(new CZ::FinstatApi.ViewModel.Limit());
return model;
}
}
}
|
Java | UTF-8 | 5,974 | 1.789063 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2013, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.salesforce.phoenix.pig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import com.salesforce.phoenix.jdbc.PhoenixConnection;
import com.salesforce.phoenix.util.ColumnInfo;
import com.salesforce.phoenix.util.QueryUtil;
/**
* A container for configuration to be used with {@link PhoenixHBaseStorage}
*
* @author pkommireddi
*
*/
public class PhoenixPigConfiguration {
private static final Log LOG = LogFactory.getLog(PhoenixPigConfiguration.class);
/**
* Speculative execution of Map tasks
*/
public static final String MAP_SPECULATIVE_EXEC = "mapred.map.tasks.speculative.execution";
/**
* Speculative execution of Reduce tasks
*/
public static final String REDUCE_SPECULATIVE_EXEC = "mapred.reduce.tasks.speculative.execution";
public static final String SERVER_NAME = "phoenix.hbase.server.name";
public static final String TABLE_NAME = "phoenix.hbase.table.name";
public static final String UPSERT_STATEMENT = "phoenix.upsert.stmt";
public static final String UPSERT_BATCH_SIZE = "phoenix.upsert.batch.size";
public static final long DEFAULT_UPSERT_BATCH_SIZE = 1000;
private final Configuration conf;
private Connection conn;
private List<ColumnInfo> columnMetadataList;
public PhoenixPigConfiguration(Configuration conf) {
this.conf = conf;
}
public void configure(String server, String tableName, long batchSize) {
conf.set(SERVER_NAME, server);
conf.set(TABLE_NAME, tableName);
conf.setLong(UPSERT_BATCH_SIZE, batchSize);
conf.setBoolean(MAP_SPECULATIVE_EXEC, false);
conf.setBoolean(REDUCE_SPECULATIVE_EXEC, false);
}
/**
* Creates a {@link Connection} with autoCommit set to false.
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
Properties props = new Properties();
conn = DriverManager.getConnection(QueryUtil.getUrl(this.conf.get(SERVER_NAME)), props).unwrap(PhoenixConnection.class);
conn.setAutoCommit(false);
setup(conn);
return conn;
}
/**
* This method creates the Upsert statement and the Column Metadata
* for the Pig query using {@link PhoenixHBaseStorage}. It also
* determines the batch size based on user provided options.
*
* @param conn
* @throws SQLException
*/
public void setup(Connection conn) throws SQLException {
// Reset batch size
long batchSize = getBatchSize() <= 0 ? ((PhoenixConnection) conn).getMutateBatchSize() : getBatchSize();
conf.setLong(UPSERT_BATCH_SIZE, batchSize);
if (columnMetadataList == null) {
columnMetadataList = new ArrayList<ColumnInfo>();
String[] tableMetadata = getTableMetadata(getTableName());
ResultSet rs = conn.getMetaData().getColumns(null, tableMetadata[0], tableMetadata[1], null);
while (rs.next()) {
columnMetadataList.add(new ColumnInfo(rs.getString(QueryUtil.COLUMN_NAME_POSITION), rs.getInt(QueryUtil.DATA_TYPE_POSITION)));
}
}
// Generating UPSERT statement without column name information.
String upsertStmt = QueryUtil.constructUpsertStatement(null, getTableName(), columnMetadataList.size());
LOG.info("Phoenix Upsert Statement: " + upsertStmt);
conf.set(UPSERT_STATEMENT, upsertStmt);
}
public String getUpsertStatement() {
return conf.get(UPSERT_STATEMENT);
}
public long getBatchSize() {
return conf.getLong(UPSERT_BATCH_SIZE, DEFAULT_UPSERT_BATCH_SIZE);
}
public String getServer() {
return conf.get(SERVER_NAME);
}
public List<ColumnInfo> getColumnMetadataList() {
return columnMetadataList;
}
public String getTableName() {
return conf.get(TABLE_NAME);
}
private String[] getTableMetadata(String table) {
String[] schemaAndTable = table.split("\\.");
assert schemaAndTable.length >= 1;
if (schemaAndTable.length == 1) {
return new String[] { "", schemaAndTable[0] };
}
return new String[] { schemaAndTable[0], schemaAndTable[1] };
}
public Configuration getConfiguration() {
return this.conf;
}
}
|
C | UTF-8 | 5,472 | 3.015625 | 3 | [] | no_license | /**
* @file list.c
*
* @date 2009-05-22
* @author Jean-Lou Dupont
*/
#include "cjld.h"
#include "macros.h"
cjld_list *cjld_list_create(int id, void (*cleaner)(void *el, int id)) {
cjld_list *tmp=NULL;
tmp = (cjld_list *) malloc( sizeof(cjld_list) );
if (NULL==tmp)
return NULL;
tmp->count = 0;
tmp->id = id;
tmp->cleaner = cleaner;
tmp->head = NULL;
tmp->tail = NULL;
return tmp;
}//
int cjld_list_getid(cjld_list *list) {
TESTPTR(cjld_list_get_id, list);
return list->id;
}//
int cjld_list_count(cjld_list *list) {
TESTPTR(cjld_list_get_id, list);
return list->count;
}//
void __cjld_cleaner_free(void *el, int id) {
if (NULL==el) {
DEBUG_LOG(LOG_ERR, "cjld_cleaner_free: NULL pointer" );
return;
}
free(el);
}//
int cjld_list_destroy(cjld_list *list) {
TESTPTR(cjld_list_destroy, list);
void (*cleaner)(void *, int);
cleaner = list->cleaner;
if (NULL==cleaner)
cleaner = &__cjld_cleaner_free;
cjld_list_visit( list, cleaner );
free(list);
}//
int cjld_list_append( cjld_list *dest, void *el, int id ) {
TESTPTR(cjld_list_append, dest);
int code = 1; //optimistic
cjld_snode *new_node;
new_node = (cjld_snode *) malloc(sizeof(cjld_snode));
if (NULL!=new_node) {
// new node...
new_node->el = el;
new_node->next = NULL;
// there is a tail... put at the end
if (NULL!=dest->tail)
(dest->tail)->next=new_node;
// point tail to the new element
dest->tail = new_node;
// adjust head
if (NULL==dest->head)
dest->head=new_node;
dest->count++;
} else {
code = 0;
}
return code;
}//
cjld_list *cjld_list_extend( cjld_list *dest, cjld_list *src ) {
//nothing to add
if (NULL==src) {
return dest;
}
//nothing to add to
if (NULL==dest) {
return src;
}
//first, link the lists
(dest->tail)->next = src->head;
//adjust tail of extended list
dest->tail = src->tail;
//adjust size
dest->count += src->count;
//free the list container... not the elements
free(src);
return dest;
}//
void *cjld_list_remove(cjld_list *list, int id) {
TESTPTR(cjld_list_remove, list);
void *element=NULL;
cjld_snode *current_node=list->head,
*previous_node=NULL,
*removed_node=NULL;
while(NULL!=current_node) {
if (id == current_node->id) {
removed_node = current_node;
break;
}
previous_node = current_node;
current_node = current_node->next;
};
//case 1: only one element and it is the one to remove => adjust both head & tail
//case 2: one element to remove from a plurality of elements
// a) element at the tail => use previous element to adjust tail
// b) element at the head
// c) element in between head & tail
if (NULL==removed_node) {
return NULL;
}
//case 1
if ( (list->tail==removed_node) && (list->head==removed_node) ) {
list->head = NULL;
list->tail = NULL;
list->count = 0;
element = removed_node->el;
free(removed_node);
return element;
}
//case 2a
if (list->tail == removed_node) {
previous_node->next = NULL;
list->tail = previous_node;
list->count--;
element = removed_node->el;
free(removed_node);
return element;
}
//case 2b
if (list->head == removed_node) {
list->head = (list->head)->next;
list->count--;
element = removed_node->el;
free(removed_node);
return element;
}
//case 2c
// must join the two list segments
previous_node->next = removed_node->next;
list->count--;
element = removed_node->el;
free(removed_node);
return element;
}//
/**
* Pointers 'list' and 'el' should already have been validated
*/
void __cjld_list_destroy_element(cjld_list *list, void *el, int id) {
void (*cleaner)(void *el, int id);
cleaner = list->cleaner;
if (NULL==cleaner) {
free(el);
}
*cleaner(el, id);
}//
int cjld_list_remove_destroy(cjld_list *list, int id) {
void *removed_element;
removed_element = cjld_list_remove( list, id );
//not found =>error
if (NULL==removed_element) {
return 0;
}
__cjld_list_destroy_element( list, removed_element, id );
return 1;
}//
void *cjld_list_pop(cjld_list *list) {
TESTPTRV(cjld_list_pop, list);
void *element=NULL;
cjld_snode *node=NULL,
*next=NULL;
next = list->head->next;
node = list->head;
list->head = next;
el=node->el;
free(node);
return element;
}//
/**
* Case 1: HEAD insertion
* Case 2: TAIL insertion
* Case 3: In between
*/
int cjld_list_insert(cjld_list *list, void *el, int id, int pos) {
TESTPTR(cjld_list_insert, list);
TESTINDEX(cjld_list_insert, pos);
TESTINDEXU(cjld_list_insert, pos, list->count );
int i=0;
cjld_snode *current = NULL,
*previous = NULL,
*node = NULL;
//create node
node = (cjld_snode *) malloc( sizeof(cjld_snode *) );
node->el = el;
node->id = id;
//case 1
if (0==pos) {
node->next = list->head;
list->head = node;
list->count++;
return 1;
}
//case 2 & 3: need to walk the list
// as it is single-linked
// NOTE: tail pointer never needs to be updated
current = list->head;
previous = NULL;
//walk till pos
while( i != pos ) {
previous=current;
current=current->next;
i++;
}//while
//insert in-between
previous->next = node;
node->next = current;
return 1;
}//
/**
*
* s[i:j]
* s[
*
* Case 1: empty list
* Case 2: one element
* Case 3:
*
*/
int *cjld_list_slice(cjld_list *list, int start, int stop) {
TESTPTR(cjld_list_insert, list);
TESTINDEX(cjld_list_insert, start);
TESTINDEX(cjld_list_insert, stop);
}//
|
C++ | UTF-8 | 852 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<math.h>
#include<unordered_map>
#include<unordered_set>
#include<algorithm>
#include<set>
using namespace std;
int ha[256];
int fibo[11] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
bool isF(string &s, int i, int j)
{
memset(ha, 0, sizeof(ha));
for(int k = i; k <= j; k++)
ha[s[k]]++ ;
int count = 0;
for(int k = 0; k < 256; k++)
if(ha[k] != 0)
count++;
for(int i = 0; i < 11; i++)
if(count == fibo[i])
return true;
return false;
}
int main()
{
string s;
cin>>s;
set<string> ans;
for(int i = 0; i < s.length(); i++)
for(int j = i; j < s.length(); j++)
if(isF(s, i, j))
ans.insert(s.substr(i, j - i + 1));
for(set<string>::iterator it = ans.begin(); it != ans.end(); it++)
cout<<*it<<"\n";
return 0;
} |
C++ | UTF-8 | 1,696 | 3.109375 | 3 | [] | no_license | /*************************************************************************
> File Name: 071_SimplifyPath.cpp
> Author: Sheng Qin
> Mail: sheng.qin@yale.edu
> Created Time: Tue Sep 6 16:50:26 2016
************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
string simplifyPath(string path) {
string now;
vector<string> wholePath;
int current = 0;
wholePath.push_back("/");
while(path.length() != 0){
path = path.substr(1);
int next = path.find('/');
if(next != -1){
now = path.substr(0, next);
path = path.substr(next);
} else {
now = path;
path = "";
}
if(now == ".")
continue;
else if(now == "..")
if(current == 0)
continue;
else
current--;
else if(now == "")
continue;
else{
current++;
if(current == wholePath.size())
wholePath.push_back('/' + now);
else
wholePath[current] = '/' + now;
}
}
string result;
for(int i = 1; i <= current; i++)
result = result + wholePath[i];
if(current == 0)
return "/";
else
return result;
}
};
int main() {
Solution newSolution;
cout << newSolution.simplifyPath("/home/a/b/../..////") << endl;
return 0;
}
|
C# | UTF-8 | 3,061 | 2.625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace GamesManager
{
public partial class FormLeagues : Form
{
public FormLeagues()
{
InitializeComponent();
}
private void Leagues_Load(object sender, EventArgs e)
{
this.UpdateCBLeague();
}
private void cbLeaguesList_SelectedIndexChanged(object sender, EventArgs e)
{
DataLayer.CbItem curItem=(DataLayer.CbItem)cbLeague.SelectedItem;
if (curItem == null)
return;
txtGuid.Text = curItem.ID.ToString();
DataLayer.League league = new DataLayer.League(curItem.ID, curItem.Name);
league.GetFromDB();
txtPictureUrl.Text = league.PictureUrl;
}
private void cbLeague_DropDown(object sender, EventArgs e)
{
this.UpdateCBLeague();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnRemoveLeague_Click(object sender, EventArgs e)
{
DataLayer.CbItem curItem = (DataLayer.CbItem)cbLeague.SelectedItem;
if (curItem == null)
return;
DataLayer.League league = new DataLayer.League(curItem.ID, curItem.Name);
MessageBox.Show(league.RemoveFromDB().ToString()+" row was removed", "Leagues removing");
this.ClearForm();
}
private void UpdateCBLeague()
{
cbLeague.Items.Clear();
DataLayer.Leagues leagues = new DataLayer.Leagues();
foreach (DataLayer.CbItem league in leagues)
{
cbLeague.Items.Add(league);
}
}
private void ClearForm()
{
txtGuid.Clear();
cbLeague.Text = "";
cbLeague.SelectedItem = null;
cbLeague.SelectedIndex = -1;
txtPictureUrl.Clear();
}
private void btnUpdateLeague_Click(object sender, EventArgs e)
{
if (txtGuid.Text == "" || cbLeague.Text=="" )
return;
DataLayer.League league = new DataLayer.League(Guid.Parse(txtGuid.Text), cbLeague.Text, txtPictureUrl.Text);
MessageBox.Show(league.UpdateInDB().ToString() + " row was updated", "Leagues updating");
}
private void btnAddLeague_Click(object sender, EventArgs e)
{
if (cbLeague.Text == "")
return;
Guid guid = Guid.NewGuid();
DataLayer.League league = new DataLayer.League(guid, cbLeague.Text, txtPictureUrl.Text);
MessageBox.Show(league.AddToDB().ToString() + " row was added", "Leagues adding");
this.ClearForm();
}
}
}
|
Java | UTF-8 | 2,378 | 2.265625 | 2 | [] | no_license | package com.strr.mall.generator.dao.impl;
import com.strr.mall.common.Constant;
import com.strr.mall.generator.dao.TableInfoDao;
import com.strr.mall.generator.entity.TableInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class TableInfoDaoImpl implements TableInfoDao {
@Autowired
private JdbcTemplate jdbcTemplate;
private RowMapper<TableInfo> tableInfoRowMapper = (rs, rowNum) -> {
TableInfo tableInfo = new TableInfo();
tableInfo.setTableSchema(rs.getString("TABLE_SCHEMA"));
tableInfo.setTableName(rs.getString("TABLE_NAME"));
tableInfo.setTableType(rs.getString("TABLE_TYPE"));
tableInfo.setEngine(rs.getString("ENGINE"));
tableInfo.setVersion(rs.getString("VERSION"));
tableInfo.setTableRows(rs.getInt("TABLE_ROWS"));
tableInfo.setCreateTime(rs.getTime("CREATE_TIME"));
tableInfo.setUpdateTime(rs.getTime("UPDATE_TIME"));
return tableInfo;
};
@Override
public List<TableInfo> getTableInfoList() {
String sql = "select TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, ENGINE, VERSION, TABLE_ROWS, CREATE_TIME, UPDATE_TIME " +
"from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = ?";
return jdbcTemplate.query(sql, new Object[] {Constant.TABLE_SCHEMA}, tableInfoRowMapper);
}
@Override
public Map<String, Object> getTableInfoPage(Integer page, Integer size) {
Map<String, Object> map = new HashMap<>();
String countSql = "select count(1) from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = ?";
Integer total = jdbcTemplate.queryForObject(countSql, new Object[] {Constant.TABLE_SCHEMA}, Integer.class);
String querySql = "select TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, ENGINE, VERSION, TABLE_ROWS, CREATE_TIME, UPDATE_TIME " +
"from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = ? limit ?, ?";
List<TableInfo> content = jdbcTemplate.query(querySql, new Object[] {Constant.TABLE_SCHEMA, page, size}, tableInfoRowMapper);
map.put("total", total);
map.put("content", content);
return map;
}
}
|
Shell | UTF-8 | 529 | 3.34375 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env bash
# Configure /etc/haas.cfg
if [ "$DB" == sqlite ]; then
mkdir /sqlite
DATABASE_URI="sqlite:////sqlite/haas.db"
elif [ "$DB" == postgresql ]; then
:
fi
sed -e "
s|%DATABASE_URI%|$DATABASE_URI|g;
" -i /etc/haas.cfg
cd /etc && haas-admin db create
if [ "$DB" == sqlite ]; then
# Since haas-admin db create will be run from the root user
# www-data will not have access to the sqlite file.
chown -R www-data:www-data /sqlite
fi
# Run apache in the foreground
apachectl -DFOREGROUND |
PHP | UTF-8 | 1,182 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
class IncidentType extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'incident_types';
protected $primaryKey = 'incident_type_id';
public $timestamps = false;
public static $medical = array(1, 2, 3, 4, 5);
public static $mvd = array(8, 9, 10);
public static $release_and_spill = array(6);
public static function rename($from, $to) {
$a = self::where('type_name', '=', $from)->first();
if ($a) {
$a->type_name = $to;
$a->save();
}
}
public static function add($typeName) {
$c = new self();
$c->type_name = $typeName;
$c->save();
}
public static function remove($typeName) {
self::where('type_name', '=', $typeName)->first()->delete();
}
public function isMedical(){
return in_array($this->incident_type_id, self::$medical);
}
public function isMVD(){
return in_array($this->incident_type_id, self::$mvd);
}
public function isReleaseAndSpill(){
return in_array($this->incident_type_id, self::$release_and_spill);
}
}
|
Ruby | UTF-8 | 4,883 | 2.546875 | 3 | [] | no_license | #!/usr/bin/ruby
#-------------------------------------------------------------------------------
# To do:
# * prettyify fstab, align columns, etc.
#-------------------------------------------------------------------------------
def usage
puts <<End
Options:
--no-color -- disable color
End
exit 1
end
#-------------------------------------------------------------------------------
require 'rubygems'
require 'facets'
require 'colored'
require 'pathname'
require 'facets/blank'
require 'facets/symbol/to_proc'
require 'quality_extensions/string/with_knowledge_of_color'
#-------------------------------------------------------------------------------
# duplication with files_of_hanoi
columns = [:uuid, :device_path, :mount_path, :file_system_type, :mount_options, :dump, :pass, :vol_id]
Disk = Struct.new(*columns)
class FstabParser
def initialize(fstab_path)
@fstab_path = fstab_path
end
def start
File.open(@fstab_path, 'r') do |file|
i = 0
device_path_for_line = []
file.map do |line|
if line =~ %r<^# (/dev/\S+)>
device_path_for_line[i+1] = $1
end
# An actual fstab line
if match = line.match(%r<^(/dev/\S+|UUID=\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+$>)
#puts '-----------------------------------------'
# Get the fstab data for this disk
d = Disk.new
device_path_or_uuid, d.mount_path, d.file_system_type, d.mount_options, d.dump, d.pass = match.captures
if device_path_or_uuid =~ /UUID=(\S+)/
d.uuid = $1
#puts d.uuid
d.device_path = device_path_for_line[i]
elsif device_path_or_uuid =~ %r<^(/dev/\S+)>
d.uuid = nil
d.device_path = $1
#puts d.device_path
else
raise "Expected device_path_or_uuid"
end
end
i += 1
d
end.compact
end
end
def each_entry!
# (with comments above entry)
# TODO: replace entry with new formatted entry?
yield entry
end
end
DeviceInfo = Struct.new(:model, :firmware_revision, :serial_num)
class VolIdParser
class NotFoundError < StandardError; end
def initialize(output)
@output = output
end
def start
@output.each do |line|
# ID_FS_UUID=008E-54E2
if match = line.match(%r{^ID_FS_UUID=(.+)$})
return $1
end
end
raise NotFoundError, "Couldn't find ID_FS_UUID line. Output=#{@output}"
end
end
#---------------------------------------------------------------------------------------------------
require 'getoptlong'
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--device', '-d', GetoptLong::NO_ARGUMENT ],
[ '--no-color', '--nc', GetoptLong::NO_ARGUMENT ]
)
opts.each do | opt, arg |
case opt
when '--device', '-d'
@show_device_info = true
when '--help', '-h'
usage
when '--no-color', '-nc'
class String
def colorize(string, options = {})
string
end
end
end
end
#---------------------------------------------------------------------------------------------------
#lines = `mount`.lines
#mounts = lines.inject([]) do |mounts, line|
# #/dev/sda1 on /media/500B1 type fuseblk (rw,nosuid,nodev,allow_other,default_permissions,blksize=4096)
# #/dev/sda2 on /media/500B2 type ext3
# if line.chomp =~ /(\S+) on (\S+) type (.*)$/
#
# name = $1
# mount_point = $2
# type = $3
# @longest_name = [name.length, @longest_name.to_i].max
#
# branches << Mount.new(name, mount_point, type)
# branches
# else
# puts "Line in unexpected format: #{line}"
# end
#end
disks = FstabParser.new('/etc/fstab').start
# Get the *actual* vol_id
disks.each do |disk|
next unless disk.device_path =~ %r(^/dev/hd|^/dev/sd)
begin
vol_id = VolIdParser.new(`sudo vol_id #{disk.device_path}`).start
rescue VolIdParser::NotFoundError
puts "While trying to get vol_id for #{disk.device_path}: #{$!.inspect}".red
end
disk.vol_id = vol_id
puts "vol_id '#{vol_id}' doesn't match UUID from fstab for mount #{disk}. Do you need to update the comment?".red if disk.uuid != vol_id
puts "vol_id '#{vol_id}' matches UUID from fstab for mount #{disk.device_path} / #{disk.mount_path}".green if disk.uuid == vol_id
end
#widths = columns.inject({}) do |hash, column|
# hash[column] = disks.map(&column).map(&:to_s).map(&:length).max
# hash
#end
class Disk
def to_pretty_fstab_entry(widths = Hash.new(0))
device_path. ljust(widths[:device_path]).cyan + ' ' +
mount_path. ljust(widths[:mount_path]).green + ' ' +
file_system_type. ljust(widths[:file_system_type]).magenta + ' ' +
"(#{mount_options})".ljust(widths[:mount_options]+2).magenta + ' ' +
''
end
end
|
Java | UTF-8 | 1,008 | 2.125 | 2 | [
"MIT"
] | permissive | package com.ixnah.mc.protocol.mixin.client.multiplayer;
import com.ixnah.mc.protocol.UriServerAddress;
import net.minecraft.client.multiplayer.ServerAddress;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.net.URI;
import static com.ixnah.mc.protocol.CustomProtocol.URI_REGEX;
/**
* @author 寒兮
* @version 1.0
* @date 2021/7/12 10:53
*/
@Mixin(ServerAddress.class)
public class ServerAddressMixin {
@Inject(method = "fromString", cancellable = true, at = @At("HEAD"))
private static void parseCustomProtocol(String addrString, CallbackInfoReturnable<ServerAddress> cir) {
try {
if (addrString.matches(URI_REGEX))
cir.setReturnValue(new UriServerAddress(new URI(addrString.trim())));
} catch (Throwable e) {
e.printStackTrace();
}
}
}
|
PHP | UTF-8 | 1,236 | 3.046875 | 3 | [] | no_license | <?php
/**
* Convert Markdown text to HTML
*
* Right now, this is simply a bridge to cqMarkdown class static functions.
* I have some interesting ideas for the future.
*
* @param string $text
* @return string
* @see cqMarkdown::doConvert()
*/
function convert_markdown_text($text)
{
return cqMarkdown::doConvert($text);
}
/**
* Convert Markdown file content to HTML
*
* Right now, this is simply a bridge to cqMarkdown class static functions.
* I have some interesting ideas for the future.
*
* @param string $file
* @return string
* @see cqMarkdown::doConvertFile()
*/
function convert_markdown_file($file)
{
return cqMarkdown::doConvertFile($file);
}
/**
* Converts Markdown text to HTML and prints returned data
*
* @param string $text
* @return void
* @see convert_markdown_text()
* @see cqMarkdown::doConvert()
*/
function include_markdown_text($text)
{
echo convert_markdown_text($text);
}
/**
* Converts Markdown file content to HTML and prints returned data
*
* @param string $file
* @return string
* @see convert_markdown_file()
* @see cqMarkdown::doConvertFile()
*/
function include_markdown_file($file)
{
echo convert_markdown_file($file);
}
|
JavaScript | UTF-8 | 841 | 3.09375 | 3 | [] | no_license | let input = document.getElementById ('myinput')
let addBtn = document.querySelector('.addBtn')
let list=document.querySelector('#myUl')
function addToDo(){
let text=document.createTextNode(input.value);
addToDo()
let li=document.createElement('li');
li.appendChild(text);
if (input.value){
list.appendChild(li);
} else{alert('Please enter an input')}
input.value='';
let removeBtn = document.createElement('button')
let=document.createElement('button')
li.appendChild(removeBtn);
removeBtn.innerText='x';
removeBtn.addEventListener('click','function'){
removeBtn.parentElement.remove();
}
removeBtn.setAttribute('class','removeBtn');
removeBtn.classList.toggle('removeBtn');
li.addEventListener('mouseover','function()'){
li.style.backgroundColor='rgb(173,173,173)';
}}
li.addEventListener('mouseout') |
Java | UTF-8 | 4,661 | 2.015625 | 2 | [
"LicenseRef-scancode-public-domain"
] | permissive | package se.datahamstern.external.osm;
import com.sleepycat.persist.EntityCursor;
import org.apache.commons.io.IOUtils;
import org.apache.xerces.parsers.DOMParser;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.w3c.dom.*;
import se.datahamstern.Datahamstern;
import se.datahamstern.Nop;
import se.datahamstern.domain.DomainStore;
import se.datahamstern.domain.Gata;
import se.datahamstern.domain.Koordinat;
import se.datahamstern.domain.Postort;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* @author kalle
* @since 2012-05-24 12:15
*/
public class GatupolygontagResolver {
public static void main(String[] args) throws Exception {
Datahamstern.getInstance().open();
GatupolygontagResolver resolver = new GatupolygontagResolver();
try {
EntityCursor<Gata> gator = DomainStore.getInstance().getGator().entities();
try {
Gata gata;
while ((gata = gator.next()) != null) {
resolver.resolve(gata);
}
} finally {
gator.close();
}
} finally {
Datahamstern.getInstance().close();
}
}
public GatupolygontagResolver() throws Exception {
}
private DOMParser p = new DOMParser();
private XPath xpath = XPathFactory.newInstance().newXPath();
private XPathExpression wayNodesExpression = xpath.compile("//nd/@ref");
private XPathExpression nodeLatitudeExpression = xpath.compile("//node/@lat");
private XPathExpression nodeLongitudeExpression = xpath.compile("//node/@lon");
public List<Koordinat> resolve(Gata gata) throws Exception {
Postort postort = DomainStore.getInstance().getPostorter().get(gata.getPostortIdentity().get());
StringBuilder addressQueryFactory = new StringBuilder();
addressQueryFactory.append(gata.getNamn().get());
addressQueryFactory.append(", ");
addressQueryFactory.append(postort.getNamn().get());
addressQueryFactory.append(", Sweden");
String addressQuery = URLEncoder.encode(addressQueryFactory.toString(), "UTF8");
StringBuilder urlFactory = new StringBuilder(512);
urlFactory.append("http://nominatim.openstreetmap.org/search?format=json&addressdetails=1&polygon=1");
urlFactory.append("&q=").append(addressQuery);
URLConnection connection = new URL(urlFactory.toString()).openConnection();
Reader reader = new InputStreamReader(connection.getInputStream(), "UTF8");
StringWriter jsonFactory = new StringWriter(49152);
IOUtils.copy(reader, jsonFactory);
reader.close();
String json = jsonFactory.toString();
reader = new StringReader(json);
JSONParser parser = new JSONParser();
JSONArray results = (JSONArray) parser.parse(reader);
reader.close();
if (results.size() == 0) {
return null;
} else {
List<Way> ways = new ArrayList<Way>();
for (int wayIndex = 0; wayIndex < results.size(); wayIndex++) {
JSONObject result = (JSONObject) results.get(wayIndex);
if ("way".equals(result.get("osm_type"))) {
Way way = new Way();
way.setId(Integer.valueOf((String) result.get("osm_id")));
// load way
way.setNodes(new ArrayList<Node>());
p.parse("http://www.openstreetmap.org/api/0.6/way/" + way.getId());
NodeList wayNodes = (NodeList) wayNodesExpression.evaluate(p.getDocument(), XPathConstants.NODESET);
if (wayNodes.getLength() == 0) {
throw new RuntimeException("Way nodes expected!");
}
for (int wayNodeIndex = 0; wayNodeIndex < wayNodes.getLength(); wayNodeIndex++) {
Node node = new Node();
node.setId(Integer.valueOf(wayNodes.item(wayNodeIndex).getTextContent()));
// load node
p.parse("http://www.openstreetmap.org/api/0.6/node/" + node.getId());
Document nodeDocument = p.getDocument();
node.setLatitude(Double.valueOf(nodeLatitudeExpression.evaluate(nodeDocument)));
node.setLongitude(Double.valueOf(nodeLongitudeExpression.evaluate(nodeDocument)));
way.getNodes().add(node);
}
ways.add(way);
}
}
Nop.breakpoint();
// todo make sure all results share at least one node id
}
return null;
}
}
|
SQL | UTF-8 | 6,716 | 3.390625 | 3 | [] | no_license | CREATE OR REPLACE PACKAGE BODY EcDp_Well_Shipper IS
/****************************************************************
** Package : EcDp_Well_Shipper, body part
**
** $Revision: 1.6 $
**
** Purpose : Finds well shipper properties.
**
** Documentation : www.energy-components.com
**
** Created : 10.05.2000 Carl-Fredrik Sørensen
**
** Modification history:
**
** Date Whom Change description:
** ------ ----- --------------------------------------
** 11.08.2004 mazrina removed sysnam and update as necessary
** 15.11.2005 DN TI2742: Changed cursor in function getShipperPhaseFraction according to new table structure.
** 08.11.2006 zakiiari TI4512: Updated getShipperPhaseFraction
*****************************************************************/
------------------------------------------------------------------
-- Function: getShipperPhaseFraction
-- Description: Returns the shipper fraction of a well stream phase
------------------------------------------------------------------
FUNCTION getShipperPhaseFraction(
p_object_id well.object_id%TYPE,
p_shipper VARCHAR2,
p_daytime DATE,
p_phase VARCHAR2)
RETURN NUMBER IS
CURSOR well_bores IS
SELECT object_id
FROM webo_bore
WHERE well_id = p_object_id
AND p_daytime BETWEEN Nvl(start_date,p_daytime-1) AND Nvl(end_date,p_daytime+1);
CURSOR shipper_fraction(cp_object_id VARCHAR2, cp_wellbore VARCHAR2, cp_shipper VARCHAR2, cp_daytime DATE) IS
SELECT Sum(Nvl(w.COND_PCT, 0) / 100) CON_FRACTION,
Sum(Nvl(w.GAS_PCT, 0) / 100) GAS_FRACTION,
Sum(Nvl(w.OIL_PCT, 0) / 100) OIL_FRACTION,
Sum(Nvl(w.WATER_PCT, 0) / 100) WAT_FRACTION,
Sum(Nvl(pis.COND_PCT, 0) / 100) P_CON_FRACTION,
Sum(Nvl(pis.GAS_PCT, 0) / 100) P_GAS_FRACTION,
Sum(Nvl(pis.OIL_PCT, 0) / 100) P_OIL_FRACTION,
Sum(Nvl(pis.WATER_PCT, 0) / 100) P_WAT_FRACTION
FROM webo_interval_gor w, webo_interval i, resv_block_formation r, rbf_version rbfv, webo_bore wb, perf_interval pi, perf_interval_gor pis
--WHERE i.resv_block_formation_id = r.object_id
WHERE pi.resv_block_formation_id = r.object_id
AND pi.webo_interval_id = i.object_id
AND i.well_bore_id = wb.object_id
AND wb.well_id = cp_object_id
AND wb.object_id = cp_wellbore
AND rbfv.object_id = r.object_id
AND cp_daytime >= rbfv.daytime
AND cp_daytime < nvl(rbfv.end_date, cp_daytime+1)
AND rbfv.commercial_entity_id = cp_shipper
AND w.daytime =
(SELECT Max(pis2.daytime)
FROM perf_interval_gor pis2, perf_interval pi2
WHERE pi2.object_id = pi.object_id
AND pi2.webo_interval_id = pi.webo_interval_id
AND pis2.daytime <= cp_daytime);
/*
(SELECT Max(w2.daytime)
FROM webo_interval_gor w2, webo_interval i2
WHERE i2.object_id = i.object_id
AND i2.well_bore_id = i.well_bore_id
AND w2.daytime <= cp_daytime);
*/
ln_webo_contr NUMBER;
ln_ship_contr NUMBER := 0; -- assume no contribution
ln_ship_webo_contr NUMBER;
BEGIN
FOR WellBoreCur IN well_bores LOOP
-- determine total contribution of this well bore flow...
ln_webo_contr := 1; -- TODO: should call function that traverses the webo tree
FOR ShipperFracCur IN shipper_fraction (p_object_id, WellBoreCur.object_id, p_shipper, p_daytime) LOOP
-- determine shipper share of well bore flow
IF (p_phase = EcDp_Phase.OIL) THEN
ln_ship_webo_contr := ShipperFracCur.OIL_FRACTION * ShipperFracCur.P_OIL_FRACTION;
ELSIF (p_phase = EcDp_Phase.GAS) THEN
ln_ship_webo_contr := ShipperFracCur.GAS_FRACTION * ShipperFracCur.P_GAS_FRACTION;
ELSIF (p_phase = EcDp_Phase.CONDENSATE) THEN
ln_ship_webo_contr := ShipperFracCur.CON_FRACTION * ShipperFracCur.P_CON_FRACTION;
ELSIF (p_phase = EcDp_Phase.WATER) THEN
ln_ship_webo_contr := ShipperFracCur.WAT_FRACTION * ShipperFracCur.P_WAT_FRACTION;
END IF;
IF ln_ship_webo_contr IS NULL THEN -- no contribution found for this shipper
ln_ship_webo_contr := 0;
END IF;
-- add up
ln_ship_contr := ln_ship_contr + (ln_ship_webo_contr * ln_webo_contr);
END LOOP;
END LOOP;
RETURN ln_ship_contr;
END getShipperPhaseFraction;
------------------------------------------------------------------
-- Function: getShipperConFraction
-- Description: Returns the shipper fraction of the well stream condensate phase
------------------------------------------------------------------
FUNCTION getShipperConFraction(
p_object_id well.object_id%TYPE,
p_shipper VARCHAR2,
p_daytime DATE)
RETURN NUMBER IS
ln_ship_contr NUMBER := 0; -- assume no contribution
BEGIN
ln_ship_contr := getShipperPhaseFraction(
p_object_id,
p_shipper,
p_daytime,
EcDp_Phase.CONDENSATE);
RETURN ln_ship_contr;
END getShipperConFraction;
------------------------------------------------------------------
-- Function: getShipperGasFraction
-- Description: Returns the shipper fraction of the well stream gas phase
------------------------------------------------------------------
FUNCTION getShipperGasFraction(
p_object_id well.object_id%TYPE,
p_shipper VARCHAR2,
p_daytime DATE)
RETURN NUMBER IS
ln_ship_contr NUMBER := 0; -- assume no contribution
BEGIN
ln_ship_contr := getShipperPhaseFraction(
p_object_id,
p_shipper,
p_daytime,
EcDp_Phase.GAS);
RETURN ln_ship_contr;
END getShipperGasFraction;
------------------------------------------------------------------
-- Function: getShipperOilFraction
-- Description: Returns the shipper fraction of the well stream oil phase
------------------------------------------------------------------
FUNCTION getShipperOilFraction(
p_object_id well.object_id%TYPE,
p_shipper VARCHAR2,
p_daytime DATE)
RETURN NUMBER IS
ln_ship_contr NUMBER := 0; -- assume no contribution
BEGIN
ln_ship_contr := getShipperPhaseFraction(
p_object_id,
p_shipper,
p_daytime,
EcDp_Phase.OIL);
RETURN ln_ship_contr;
END getShipperOilFraction;
------------------------------------------------------------------
-- Function: getShipperWatFraction
-- Description: Returns the shipper fraction of the well stream water phase
------------------------------------------------------------------
FUNCTION getShipperWatFraction(
p_object_id well.object_id%TYPE,
p_shipper VARCHAR2,
p_daytime DATE)
RETURN NUMBER IS
ln_ship_contr NUMBER := 0; -- assume no contribution
BEGIN
ln_ship_contr := getShipperPhaseFraction(
p_object_id,
p_shipper,
p_daytime,
EcDp_Phase.WATER);
RETURN ln_ship_contr;
END getShipperWatFraction;
END EcDp_Well_Shipper; |
PHP | UTF-8 | 4,927 | 3.296875 | 3 | [
"MIT"
] | permissive | <?php
namespace umbalaconmeogia\phputil\calculation;
/**
* Convert between number systems.
*/
class NumberSystem
{
const DIGIT_BINARY = '01';
const DIGIT_OCTAL = '01234567';
const DIGIT_DECIMAL = '0123456789';
const DIGIT_HEXADECIMAL = '0123456789ABCDEF';
const DITGIT_LOWER_CASE = '0123456789abcdefghijklmnopqrstuvwxyz';
const DITGIT_UPPER_CASE = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const BASE_2 = 'BASE_2';
const BASE_8 = 'BASE_8';
const BASE_10 = 'BASE_10';
const BASE_16 = 'BASE_16';
const BASE_DIGIT_MAPPING = [
self::BASE_2 => self::DIGIT_BINARY,
self::BASE_8 => self::DIGIT_OCTAL,
self::BASE_10 => self::DIGIT_DECIMAL,
self::BASE_16 => self::DIGIT_HEXADECIMAL,
];
/**
* Convert between number systems.
*
* Example usage
* ```php
* // Convert a decimal number to digit-and-lower-case number system.
* $digitAndLowerCaseDigits = NumberSystem::convert(NumberSystem::DITGIT_LOWER_CASE, 1234567890, NumberSystem::DIGIT_DECIMAL);
* // $digitAndLowerCaseDigits = kf12oi
*
* // Convert a decimal number to hexadecimal number.
* $hexadecimalValue = NumberSystem::convert(NumberSystem::DIGIT_HEXADECIMAL, 1234567890, NumberSystem::DIGIT_DECIMAL);
* // $hexadecimalValue = 499602D2
* ```
*
* @param string $toDigits
* @param string $fromValue
* @param string $fromDigits
*/
public static function convert($toDigits, $fromValue, $fromDigits = self::DIGIT_DECIMAL)
{
$decValue = self::convertToDecimal($fromValue, $fromDigits);
return self::convertFromDecimal($toDigits, $decValue);
}
/**
* Convert from value expressed by set of digits to decimal.
*
* Example usage
* ```php
* // Convert from hexadecimal to decimal.
* $fromHex = NumberSystem::convertToDecimal('FF0', NumberSystem::DIGIT_HEXADECIMAL);
* // $fromHex = 4080
*
* // Convert from binary to decimal.
* $fromBinary = NumberSystem::convertToDecimal('100110', NumberSystem::DIGIT_BINARY);
* // $fromBinary = 38
* ```
*
* @param string $fromValue
* @param string $fromDigits
* @return int
*/
public static function convertToDecimal($fromValue, $fromDigits)
{
$result = NULL;
$fromDigits = self::BASE_DIGIT_MAPPING[$fromDigits] ?? $fromDigits;
if ($fromDigits == self::DIGIT_DECIMAL) {
$result = $fromValue;
} else {
$mapDigitValue = self::mapDigitValue($fromDigits);
$numberOfDigit = count($mapDigitValue);
$fromArray = str_split(strrev($fromValue));
$result = 0;
$unit = 1;
foreach ($fromArray as $index => $digit) {
if ($index > 0) {
$unit *= $numberOfDigit;
}
$result += $mapDigitValue[$digit] * $unit;
}
}
if (!$result) {
$result = '0';
}
return $result;
}
/**
* Convert from decimal to value expressed by set of digits.
*
* Example usage
* ```php
* // Convert from decimal to hexadecimal.
* $hexValue = NumberSystem::convertFromDecimal(NumberSystem::DIGIT_HEXADECIMAL, 1234567890);
* // $hexValue = 499602D2
*
* // Convert from binary to decimal.
* $binaryValue = NumberSystem::convertFromDecimal(NumberSystem::DIGIT_BINARY, 1234567890);
* // $binaryValue = 1001001100101100000001011010010
* ```
*
* @param string $toDigits
* @param string $fromValue
* @return int
*/
public static function convertFromDecimal($toDigits, $fromValue)
{
$result = NULL;
$toDigits = self::BASE_DIGIT_MAPPING[$toDigits] ?? $toDigits;
if ($toDigits == self::DIGIT_DECIMAL) {
$result = $fromValue;
} else {
// echo "FROM* $fromValue\n";
$mapValueDigit = str_split($toDigits);
$numberOfDigit = count($mapValueDigit);
$result = '';
while ($fromValue > 0) {
$digit = $mapValueDigit[$fromValue % $numberOfDigit];
// echo "DIGIT $digit\n";
$result = "{$digit}{$result}";
$fromValue = intdiv($fromValue, $numberOfDigit);
// echo "FROM $fromValue\n";
}
}
if (!$result) {
$result = 0;
}
return $result;
}
/**
* Get value corresponding to each digit in digit string.
* @return array Mapping between each digit and its value.
*/
public static function mapDigitValue($digitString)
{
$result = [];
$digitArray = str_split($digitString);
foreach ($digitArray as $index => $letter) {
$result[$letter] = $index;
}
return $result;
}
} |
Java | UTF-8 | 615 | 3.15625 | 3 | [] | no_license | package model.entity;
import utilityclasses.Pair;
/**
* interface for every entity in the game.
*/
public interface Entity {
/**
* Method to get the position of the entity.
* @return a Pair that describes the position of the entity
*/
Pair<Integer, Integer> getLocation();
/**
*
* Each entity has its own way to "update" itself,
* and this method describes its behaviour.
*/
void update();
/**
* Asks the entity if it should be removed.
* @return true if the entity should be removed, false otherwise
*/
boolean shouldBeRemoved();
}
|
Ruby | UTF-8 | 320 | 3.546875 | 4 | [] | no_license | class Klasa
def metoda_pierwsza
zmienna1 = 1
end
end
module Modul
def funkcja_1
@funkcja_1 ||= Klasa.new #works only if variable is named like a function
end
end
include Modul
funkcja_1
[1,1,1,1].each do |amount|
puts funkcja_1.metoda_pierwsza #so You don't have to put "@" before variable
end |
Java | UTF-8 | 146 | 1.859375 | 2 | [] | no_license | package com.epam.javaIntro.service;
public interface UserService {
boolean logination(String login, String password) throws ServiceException;
}
|
Markdown | UTF-8 | 7,866 | 2.546875 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: Livox Mid-40 LiDAR review
description: "Recently I've been testing the performance of Livox Mid-40 LiDAR. This blog post contains my thoughts on using this sensor, it's performance and available ROS node."
modified: 2019-02-15
comments: true
tags: [ROS, Robotics, Sensors]
image:
feature: livox/livox_mid40.jpg
---
Continuing on my excursion in LiDAR testing I gave a Livox Mid-40 a spin. This post sums up my experience working with it for couple of days.
<!-- more -->
## Hardware specification
|Parameter | Value |
|:---------|:---------|
|Field of View | 38.4° (circular) |
|Maximum range | 230m |
|Range precision | 2 cm |
|Angular accuracy | < 0.1° |
|Point rate | 100,000 points/s|
|Laser wavelength | 905nm |
|Power | ~10W |
|Power supply | 10-16V DC|
|Weight | ~710g|
|Price | 599 USD |
The hardware specification above has been taken from the Livox user manuals available on [Livox website](https://www.livoxtech.com/mid-40-and-mid-100/downloads)
## First impressions
The first thing I liked about Mid-40 was the nicely machined aluminum body. The main body of the sensor comes with an attached cooling fan. The data cable is attached to the bottom of the sensor, hence it comes with an aluminum offset that allows mounting the sensor to flat surfaces. It also has a 1/4"-20 screw thread hole that makes it ideally fit most tripods.
<figure class="center">
<img src="{{site.url}}/images/livox/livox_mid40-1.jpg" alt="Sideview of Livox">
<figcaption>Side view of Livox together with Livox Converter</figcaption>
</figure>
To connect Mid-40 to your setup you will be working with Ethernet. To make sure you can access the LiDAR you will need to have a DNS server that will assign the address to LiDAR (either statically or dynamically). You will find more information about it on page 13 of [user manual](https://www.livoxtech.com/3296f540ecf5458a8829e01cf429798e/downloads/20190129/Livox%20Mid%20Series%20User%20Manual%20EN%2020190129%20v1.0.pdf)(checked with manual V1.0).
What is special about Mid-40 compared to the LiDARs you are used to is the scan pattern.
<figure class="center">
<img src="{{site.url}}/images/livox/scan_pattern.png" alt="Livox scan pattern">
<figcaption>Livox scan patterns</figcaption>
</figure>
From a short research it looks to me that the scanner might be using rotational Risley Prisms. If you would like to learn more about them then [this paper](https://acad.ro/sectii2002/proceedings/doc2018-1/08.pdf) might be a good start.
## Testing with ROS
After installing SDK I run a number of test using the [Livox-SDK-ROS package](Livox-SDK-ROS)(commit 59f904a47). Below are some visualizations that I captured with the LiDAR being stationary and looking at a fixed scene. To show the scanning pattern i varied the decay time (controls how long received point clouds are preserved) in RVIZ visualizations.
Checking publishing rate with rostopic hz command we learn that the new scans are delivered at 20 Hz.
### Static test in a room
<figure class="center">
<img src="/images/livox/room_scene.jpg" alt="Environment used for scan capture">
<figcaption>Scene used for performing an indoor tests</figcaption>
</figure>
In the first test I had the LiDAR looking at the scene shown above. Below you can see the captured point clouds.
<figure class="half">
<img src="/images/livox/livox_0_decay.gif">
<img src="/images/livox/livox_0_3_decay.gif">
<figcaption>Room capture - 0s vs 0.3s decay</figcaption>
</figure>
<figure class="half">
<img src="/images/livox/livox_0_6_decay.gif">
<img src="/images/livox/livox_1_decay.gif">
<figcaption>Room capture - 0.6s vs 1s decay</figcaption>
</figure>
The bandwidth consumed by the scans in this scene is 1.60 Mb/s.
Looking on the scene from the side the point cloud looks as follows:
<figure class="center">
<img src="/images/livox/livox_room.png" alt="Orthogonal projection of the scan data">
<figcaption>Top view showing captured point cloud</figcaption>
</figure>
### Outside test
In this test I used the sensor in the outside environment. It shows how impressive is the range and the amount of detail you can get with high enough exposure time. You can open the images in a new tab to see the at higher resolution.
<figure class="half">
<img src="/images/livox/livox_outside_0_decay.gif">
<img src="/images/livox/livox_outside_0_5_decay.gif">
<figcaption>Outside capture - 0s vs 0.5s decay</figcaption>
</figure>
<figure class="half">
<img src="/images/livox/livox_outside_2_decay.gif">
<img src="/images/livox/outside_test_2.png">
<figcaption>Outside capture 2s decay with different point size at two separate captures</figcaption>
</figure>
## Thoughts on ROS package
Working with the ROS package was a matter of downloading it, changing a broadcast code in the source file and compiling it. For a company that is just entering the market I would say that the ROS packages are in acceptable state however I would still love to see some improvements in the future:
* Change the repository directory structure. With the current structure the built code will be on the repository level, meaning after each build the repo will be in a dirty state
* Expose frame_name as a parameter so that it can be changed at launch time
* Similarly expose the broadcast_codes as parameters so that the code doesn't have to be recompiled if switching sensors
* Rename node names to include the company/product name
* Use PointCloud2 instead of PointCloud
* Use ROS logging constructs instead of printfs
## Final thoughts
I quite enjoyed working with the Mid-40. I especially liked how easy was the setup (provided you have 10-16V power supply and a router it's basically Plug&Play). What I missed from the documentation and I think is the minimum range that seems to be around 1m. Apart from that I was thoroughly impressed with the maximum range of the LiDAR and how clean the obtained data was. The ROS package is OK for something that has been developed for a month and I'm sure it will be improved over time.
What I think will be the biggest challenge that Livox will face is the technology adoption. I tried to test it with [HDL Graph Slam](https://github.com/koide3/hdl_graph_slam), however with default parameters I couldn't get a reliable SLAM output. I think the main issue might be what I would call "time to point revisit" (a time between two consecutive measurements of the same point). Given that in most of the traditional LiDARs the same points are revisited at every scan Livox might need to open a new era of SLAM tools that will support a new scan patterns.
## Update (10th of October 2019)
I think it's high time to update this post with some of the developments that had happend since I've tested the LiDAR.
### Loam Livox
[Loam Livox](https://github.com/hku-mars/loam_livox) is an odometry and mapping package created by Jiarong Lin. The demonstrators look quite promising and as soon as I have some spare time on my hand I'll run an extensive test of it and post some bag files for you.
### Special firmware
Livox had published a [repository with special firmware](https://github.com/Livox-SDK/Special-Firmwares-for-Livox-LiDARs). Among them we will find firmware that enables:
* [Mulit-return support](https://github.com/Livox-SDK/Special-Firmwares-for-Livox-LiDARs/blob/master/Multi-return_Firmware_For_Livox_MID/README.md) - this is the one I'm most excited about as it allows using the LiDAR in forestry applications
* [Threadlike-Noise Filtering](https://github.com/Livox-SDK/Special-Firmwares-for-Livox-LiDARs/blob/master/Threadlike-Noise_Filtering_Firmware_For_Livox_MID/README.md)
* [Short blind zone](https://github.com/Livox-SDK/Special-Firmwares-for-Livox-LiDARs/blob/master/Short-blind-zone_Firmware_For_Livox_MID/README.md) - decreasing the minimum range from 1m to 0.3m |
C++ | UTF-8 | 12,806 | 2.640625 | 3 | [] | no_license | #include "MeltingPotOnline.hxx"
#include "authorException.hxx"
#include "fileException.hxx"
#include "topicException.hxx"
#include "clientException.hxx"
#include "channelException.hxx"
//This function is the constructor of the class
MeltingPotOnline::MeltingPotOnline(){
_catalogue = "";
_topicDescription = "";
converter.add( "html" );
converter.add( "pdf_print" );
converter.add( "pdf_mark" );
associatedTopic = false;
//clientPreferSms = false;
//clientPreferWhatsapp = false;
}
//This function is the destructor of the class
MeltingPotOnline::~MeltingPotOnline(){
unsigned int i;
for(i = 0; i < listOfAuthors.size(); i++){
if(listOfAuthors[i]){
delete listOfAuthors[i];
}
}
for(i = 0; i < Topics.size(); i++){
if(Topics[i]){
delete Topics[i];
}
}
for(i = 0; i < listOfClients.size(); i++){
if(listOfClients[i]){
delete listOfClients[i];
}
}
for(i = 0; i < Channels.size(); i++){
if(Channels[i]){
delete Channels[i];
}
}
}
//This function returns a string that contains the information of all the authors and works
string MeltingPotOnline::catalogue(){ //Added on the first functional test
unsigned int i;
for(i = 0; i < listOfAuthors.size(); i++){
_catalogue = _catalogue.append(listOfAuthors[i]->description());
}
if (associatedTopic == true) _catalogue = _catalogue.append(_topicDescription);
return _catalogue;
}
//This function is used to add a new author to the system
void MeltingPotOnline::addAuthor(const string authorName, bool isContracted){ //Added on the second functional test
Author *newAuthor = new Author();
newAuthor->name(authorName);
if(isContracted){
newAuthor->contract();
}
listOfAuthors.push_back( newAuthor );
}
//This function is used to add a new work to a specific author.
void MeltingPotOnline::addWork(const string authorName, const string title, int worknum, string file){ //Added on the fifth functional test
unsigned int i;
string converterfile;
Author* authorSelected;
string fullname( "originals/" ); // The file is on this folder
fullname += file;
ifstream fichero( fullname.c_str() ); //We usea ifstream to check if the file exists
i = findAuthor(authorName);
listOfAuthors[i]->addWork(title, worknum, file);
if(fichero == 0){ //If the file does not exist (fichero is 0) we throw the file exception.
throw fileException();
}
converterfile = "generated/" + authorName + " - " + title;
converter.convert(fullname, converterfile);
for(i = 0; i < listOfAuthors.size(); i++){
if(listOfAuthors[i]->getName() == authorName){
authorSelected= listOfAuthors[i];
//autorencontrado = true;
}
}
authorSelected->notify(title, authorName);
}
int MeltingPotOnline::findAuthor(string authorName){
int posicio;
unsigned int i;
bool found = false; //Added to check if function has to generate an exception
for(i = 0; i < listOfAuthors.size(); i++){
if(listOfAuthors[i]->getName() == authorName){
posicio = i;
found = true;
}
}
if(found == false){ //Exception generated because we haven't found any author
throw authorException();
}
return posicio;
}
void MeltingPotOnline::addTopic(string name){
string topicName;
topicName = name + "\n";
Topic *newTopic = new Topic();
newTopic->setName(topicName);
Topics.push_back(newTopic);
}
string MeltingPotOnline::listTopics(){
string returnString;
for(unsigned int i = 0; i < Topics.size(); i++){
returnString = returnString + Topics[i]->getName();
}
return returnString;
}
void MeltingPotOnline::associateTopicWithWork(string topic, string author, string work){
if(Topics.size() < 1){
throw topicException();
}
else{
string topicName;
string authorName;
int i = findAuthor(author);
authorName = listOfAuthors[i]->getName();
Work linkedWork = listOfAuthors[i]->findWork(work);
linkedWork.associateTopic(topic);
_topicDescription = _topicDescription + linkedWork.topics(); //ESTO SERA EL REFACTOR
associatedTopic = true;
for(unsigned int i = 0; i < Topics.size(); i++){
topicName = Topics[i]->getName();
topicName.erase (topicName.length() - 1,2);
if(topicName == topic){
Topics[i]->notify(work, author);
}
}
}
}
void MeltingPotOnline::addClient(string name, string email){ //Creamos un nuevo cliente y lo añadimos a la lista
Client *newClient = new Client();
newClient->setName(name);
newClient->setEmail(email);
listOfClients.push_back(newClient);
}
string MeltingPotOnline::listClients(){ // Devuelve la información de todos los clientes de la lista
string description;
for(unsigned int i = 0; i < listOfClients.size(); i++){
description = description + listOfClients[i]->description();
}
return description;
}
void MeltingPotOnline::subscribeClientToTopic(string clientName, string topicName){
bool encontrado = false;
bool encontrado2 = false;
string nomDelTopic = topicName + "\n";
Topic* topicSelected;
Client* clientSelected;
unsigned int i = 0;
//Els busquem en el nostre MeltingPotOnline
for(i = 0; i < Topics.size(); i++){
if(Topics[i]->getName() == nomDelTopic){
topicSelected = Topics[i];
encontrado = true;
}
}
for(i = 0; i < listOfClients.size(); i++){
if(listOfClients[i]->getName() == clientName){
clientSelected = listOfClients[i];
encontrado2 = true;
}
}
//Excepcions per si no existeixen //Ja disenyat en refactors anteriors als tests sense client/topic, per aixo aquests donen green.
if (encontrado == false){
throw topicException();
}
if (encontrado2 == false){
throw clientException();
}
//Enllacem client al topic
topicSelected->subscribeClient(clientSelected);
delete topicSelected;
delete clientSelected;
}
string MeltingPotOnline::listSubscribedToTopic(string topicName){
string nomDelTopic = topicName + "\n";
bool encontrado = false;
Topic* topicSelected;
string textARetornar = "";
unsigned int i = 0;
//El busquem en el nostre MeltingPotOnline
if(Topics.size() > 0){
for(i = 0; i < Topics.size(); i++){
if(Topics[i]->getName() == nomDelTopic){
topicSelected = Topics[i];
encontrado = true;
}
}
}
//Excepcion per si no existeix topic
if (encontrado == false){
throw topicException();
}
//Extreiem nom del client lligat al topic seleccionat
textARetornar = textARetornar + topicSelected->getClient(); //el metode ja retorna la llista de clients del topic
return textARetornar;
}
void MeltingPotOnline::subscribeClientToAuthor(string clientName, string authorName){
Author* authorSelected;
Client* clientSelected;
bool autorencontrado = false;
bool clientencontrado = false;
unsigned int i = 0;
//Buscamos el autor seleccionado entre la lista de autores
for(i = 0; i < listOfAuthors.size(); i++){
if(listOfAuthors[i]->getName() == authorName){
authorSelected= listOfAuthors[i];
autorencontrado = true;
}
}
//Buscamos el cliente seleccionado entre la lista de clientes
for(i = 0; i < listOfClients.size(); i++){
if(listOfClients[i]->getName() == clientName){
clientSelected = listOfClients[i];
clientencontrado = true;
}
}
//Si no encontramos cliente o autor lanzamos exception
if (autorencontrado == false){
throw authorException();
}
if (clientencontrado == false){
throw clientException();
}
//Suscribimos el cliente al autor
authorSelected->subscribeClient(clientSelected);
}
void MeltingPotOnline::addChannel(const string name, const string description){
//Creamos un nuevo channel y lo ponemos a la lista de channels
Channel *newChannel = new Channel();
newChannel->addChannel(name, description);
Channels.push_back(newChannel);
}
string MeltingPotOnline::listThematicChannels(){
//Retornamos una string con toda la información de todos los channels creados
string textARetornar = "";
unsigned int i = 0;
//Exception por si no existe ningun channel
if(Channels.size() < 1){
throw channelException();
}
//El busquem en el nostre MeltingPotOnline
else{
for(i = 0; i < Channels.size(); i++){
string channelText = "";
channelText = Channels[i]->getName() + "\n" + "\t" + Channels[i]->getDescription() + "\n";
textARetornar = textARetornar + channelText;
}
}
return textARetornar;
}
string MeltingPotOnline::rssByChannel(const string title){
//Code for the refactor
Channel* channelSelected;
bool encontrado = false;
//Buscamos el channel seleccionado entre la lista de autores
for(unsigned int i = 0; i < Channels.size(); i++){
if(Channels[i]->getName() == title){
channelSelected = Channels[i];
encontrado = true;
}
}
//Si no se ha encontrado el canal -> exception
if(encontrado == false){
throw channelException();
}
string returnString;
returnString = "<?xml version='1.0' encoding='UTF-8' ?>\n<rss version='2.0'>\n<channel>\n<title>MeltingPotOnline: ";
returnString = returnString + channelSelected->getName() + "</title>\n";
returnString = returnString + "<link>" + channelSelected->getLink() + "</link>\n";
returnString = returnString + "<description>" + channelSelected->getDescription() + "</description>\n";
printf("FORA\n");
if(channelSelected->itemsBool()){
printf("DINS\n DINS\n");
for(int i = 0; i < channelSelected->getArraySizeOfChannelArrays(); i++){
returnString = returnString + "<item>\n";
returnString = returnString + "<title>Novelty: " + channelSelected->getItemName(i) + " by " + channelSelected->getItemAuthor(i) + "</title>\n";
returnString = returnString + "<link>" + channelSelected->getItemLink(i) + "</link>\n";
returnString = returnString + "</item>\n";
}
}
returnString = returnString + "</channel>\n" + "</rss>\n";
return returnString;
}
void MeltingPotOnline::subscribeChannelToAuthor(const string channelName, const string authorName){
Author* authorSelected;
Channel* channelSelected;
bool autorencontrado = false;
bool canalencontrado = false;
unsigned int i = 0;
//Buscamos el autor seleccionado entre la lista de autores
for(i = 0; i < listOfAuthors.size(); i++){
if(listOfAuthors[i]->getName() == authorName){
authorSelected= listOfAuthors[i];
autorencontrado = true;
}
}
//Buscamos el cliente seleccionado entre la lista de clientes
for(i = 0; i < Channels.size(); i++){
if(Channels[i]->getName() == channelName){
channelSelected = Channels[i];
canalencontrado = true;
}
}
//Si no encontramos canal o autor lanzamos exception
if (autorencontrado == false){
throw authorException();
}
if (canalencontrado == false){
throw channelException();
}
//Suscribimos el channel al autor
authorSelected->subscribeChannel(channelSelected);
}
void MeltingPotOnline::subscribeChannelToTopic(const string channelName, const string topicName){
Topic* topicSelected;
Channel* channelSelected;
bool topicencontrado = false;
bool canalencontrado = false;
unsigned int i = 0;
//Buscamos el autor seleccionado entre la lista de autores
for(i = 0; i < Topics.size(); i++){
/*RECORDAR QUE ELS NOMS DE TOPICS ES GUARDEN AMB UN \n AL FINAL (mirar metode addTopic de MeltingPotOnline.cxx)*/
if(Topics[i]->getName() == (topicName + "\n")){
topicSelected = Topics[i];
topicencontrado = true;
}
}
//Buscamos el cliente seleccionado entre la lista de clientes
for(i = 0; i < Channels.size(); i++){
if(Channels[i]->getName() == channelName){
channelSelected = Channels[i];
canalencontrado = true;
}
}
//Si no encontramos canal o autor lanzamos exception
if (topicencontrado == false){
throw topicException();
}
if (canalencontrado == false){
throw channelException();
}
//Suscribimos el channel al autor
topicSelected->subscribeChannel(channelSelected);
}
void MeltingPotOnline::clientPrefersSms(const string nombreCliente, const string numeroDeCliente){
unsigned int i;
bool clientencontrado = false;
for(i = 0; i < listOfClients.size(); i++){
if(listOfClients[i]->getName() == nombreCliente){
listOfClients[i]->setSmsnum(numeroDeCliente);
clientencontrado = true;
}
}
if (clientencontrado == false){
throw clientException();
}
}
void MeltingPotOnline::clientPrefersWhatsapp(const string nombreCliente, const string numeroDeCliente){
unsigned int i;
bool clientencontrado = false;
for(i = 0; i < listOfClients.size(); i++){
if(listOfClients[i]->getName() == nombreCliente){
listOfClients[i]->setWhatsappnum(numeroDeCliente);
clientencontrado = true;
}
}
if (clientencontrado == false){
throw clientException();
}
}
|
JavaScript | UTF-8 | 952 | 4.25 | 4 | [] | no_license | 'use strict';
// 0.
let a = true;
let b = false;
// 1.
console.log(a && b); // a is true but b is false so the expected result is false
console.log(a || b); // a is true so the expected result is true
console.log(!(a && b)); // the result of (a && b) is false so the opposite would be true
// 2.
let x = 112;
let y = 34.3;
let z = 1;
// 3.
console.log(x > z && x > y); // x is bigger than y AND z so the expected result is true
console.log(!(x === y)); // (x===y) is false so the opposite would be true
console.log(z < y || z > x); // z is lower than y, the expected result is true
console.log(x === z || x !== y); // x is not equal to z but x is unequal to y so the expected result is true
console.log(x >= 10 && y <= 10); // x is bigger than 10 but y is not less or equal to 10 the expected result is false
console.log(x * z <= 100 || x * y > 100); // x * z is not bigger or equal to 100 but x*y is bigger than 100, expected result is true
|
Java | UTF-8 | 13,340 | 2.421875 | 2 | [] | no_license | package interfaz;
import dominio.Adoptante;
import dominio.Mascota;
import dominio.Sistema;
import javax.swing.DefaultComboBoxModel;
import logicanegocio.LogicaMascota;
class PanelAdopcion extends javax.swing.JPanel {
public PanelAdopcion() {
initComponents();
this.modeloComboMascotasParaAdoptar = new DefaultComboBoxModel<>();
this.comboMascotasParaAdoptar.setModel(modeloComboMascotasParaAdoptar);
}
PanelAdopcion(Sistema sistema, int width, int height) {
this();
this.logicaMascota = new LogicaMascota(sistema);
this.setSize(width, height-100);
this.setListaMascotas();
this.errorTxt.setVisible(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
comboMascotasParaAdoptar = new javax.swing.JComboBox<>();
jLabel1 = new javax.swing.JLabel();
lbNombre = new javax.swing.JLabel();
lbApellido = new javax.swing.JLabel();
lbTenefono = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txNombre = new javax.swing.JTextField();
txApellido = new javax.swing.JTextField();
txTelefono = new javax.swing.JTextField();
btCancelar = new javax.swing.JButton();
btAdoptar = new javax.swing.JButton();
mascotaFoto = new javax.swing.JLabel();
errorTxt = new javax.swing.JLabel();
comboMascotasParaAdoptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboMascotasParaAdoptarActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel1.setText("Mascotas disponibles para adopción:");
lbNombre.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
lbNombre.setText("Nombre:");
lbApellido.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
lbApellido.setText("Apellido:");
lbTenefono.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
lbTenefono.setText("Telefono:");
jLabel2.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jLabel2.setText("Adopotante");
btCancelar.setText("Cancelar");
btCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btCancelarActionPerformed(evt);
}
});
btAdoptar.setText("Adoptar");
btAdoptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btAdoptarActionPerformed(evt);
}
});
errorTxt.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
errorTxt.setText("Error");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(comboMascotasParaAdoptar, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(mascotaFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(140, 140, 140))
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbNombre)
.addComponent(lbApellido)
.addComponent(lbTenefono))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
.addComponent(txApellido)
.addComponent(txTelefono))
.addGap(40, 40, 40))
.addGroup(layout.createSequentialGroup()
.addComponent(errorTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
.addGroup(layout.createSequentialGroup()
.addGap(292, 292, 292)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btAdoptar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(mascotaFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txNombre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbNombre, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(comboMascotasParaAdoptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txApellido, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbApellido, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txTelefono, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbTenefono, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addComponent(errorTxt)
.addGap(0, 25, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btAdoptar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btCancelar)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btCancelarActionPerformed
private void btAdoptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAdoptarActionPerformed
if(this.txNombre.getText().equals("")){
this.errorTxt.setText("El nombre del adoptante no puede estar vacío");
this.errorTxt.setVisible(true);
}
else if(this.txApellido.getText().equals("")){
this.errorTxt.setText("El apellido del adoptante no puede estar vacío");
this.errorTxt.setVisible(true);
}
else if(this.txTelefono.getText().equals("")){
this.errorTxt.setText("El telefono del adoptante no puede estar vacío");
this.errorTxt.setVisible(true);
}
else if(this.comboMascotasParaAdoptar.getItemCount() == 0){
this.errorTxt.setText("No hay mascotas para adoptar, ingrese una");
this.errorTxt.setVisible(true);
}
else {
Mascota mascota = this.logicaMascota.getMascotaPorNombre(this.comboMascotasParaAdoptar.getSelectedItem().toString());
this.adoptante = new Adoptante(this.txNombre.toString(), this.txApellido.toString(), this.txTelefono.toString(), mascota);
mascota.setEstado("adoptado");
limpiarFormulario();
}
}//GEN-LAST:event_btAdoptarActionPerformed
private void limpiarFormulario(){
this.txNombre.setText("");
this.txApellido.setText("");
this.txTelefono.setText("");
this.errorTxt.setText("");
actualizarListaMascotas();
}
private void comboMascotasParaAdoptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboMascotasParaAdoptarActionPerformed
if(modeloComboMascotasParaAdoptar.getSize() >0){
Mascota mascotaSeleccionada = logicaMascota.getMascotaPorNombre(comboMascotasParaAdoptar.getSelectedItem().toString());
mascotaFoto.setIcon(mascotaSeleccionada.getFoto());
}
}//GEN-LAST:event_comboMascotasParaAdoptarActionPerformed
private void setListaMascotas() {
this.modeloComboMascotasParaAdoptar.removeAllElements();
this.logicaMascota.getMascotasParaAdoptar()
.forEach(mascota -> {
this.modeloComboMascotasParaAdoptar.addElement(mascota.getNombre());
});
}
public void actualizarListaMascotas(){
setListaMascotas();
}
private LogicaMascota logicaMascota;
private DefaultComboBoxModel<String> modeloComboMascotasParaAdoptar;
private Adoptante adoptante;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btAdoptar;
private javax.swing.JButton btCancelar;
private javax.swing.JComboBox<String> comboMascotasParaAdoptar;
private javax.swing.JLabel errorTxt;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lbApellido;
private javax.swing.JLabel lbNombre;
private javax.swing.JLabel lbTenefono;
private javax.swing.JLabel mascotaFoto;
private javax.swing.JTextField txApellido;
private javax.swing.JTextField txNombre;
private javax.swing.JTextField txTelefono;
// End of variables declaration//GEN-END:variables
}
|
C# | UTF-8 | 6,382 | 2.6875 | 3 | [] | no_license | using Unity.Collections;
using Unity.Mathematics;
public static class KdTreeUtility
{
public const int MAX_LEAF_SIZE = 5;
public struct TreeNode
{
public int begin;
public int end;
public int left;
public int right;
public float maxX;
public float maxY;
public float minX;
public float minY;
}
static public void BuildTree(NativeArray<TreeNode> tree, NativeArray<float2> agents, NativeArray<int> agentIndices)
{
BuildTree(tree, agents, agentIndices, 0, agents.Length, 0);
}
static void BuildTree(NativeArray<TreeNode> tree, NativeArray<float2> agents, NativeArray<int> agentIndices, int begin, int end, int index)
{
var node = tree[index];
node.begin = begin;
node.end = end;
node.minX = node.maxX = agents[begin].x;
node.minY = node.maxY = agents[begin].y;
for(var i = begin+1;i<end;++i)
{
node.maxX = math.max(node.maxX, agents[i].x);
node.minX = math.min(node.minX, agents[i].x);
node.maxY = math.max(node.maxY, agents[i].y);
node.minY = math.min(node.minY, agents[i].y);
}
tree[index] = node;
if (end - begin > MAX_LEAF_SIZE)
{
/* No leaf node. */
bool isVertical = (node.maxX - node.minX > node.maxY - node.minY);
float splitValue = (isVertical ? 0.5f * (node.maxX + node.minX) : 0.5f * (node.maxY + node.minY));
int left = begin;
int right = end;
while (left < right)
{
while (left < right && (isVertical ? agents[left].x : agents[left].y) < splitValue)
{
++left;
}
while (right > left && (isVertical ? agents[right - 1].x : agents[right - 1].y) >= splitValue)
{
--right;
}
if (left < right)
{
Swap(agents, left, right - 1);
Swap(agentIndices, left, right - 1);
++left;
--right;
}
}
if (left == begin)
{
++left;
++right;
}
node.left = index + 1;
node.right = index + 2 * (left - begin);
tree[index] = node;
BuildTree(tree, agents, agentIndices, begin, left, node.left);
BuildTree(tree, agents, agentIndices, left, end, node.right);
}
}
static void Swap<T>(NativeArray<T> array, int l, int r)
where T: struct
{
T t = array[l];
array[l] = array[r];
array[r] = t;
}
static public void QueryNeighbors(NativeArray<TreeNode> tree, NativeArray<float2> agents, int agentID, float rangeSq, NativeLocalArray<int> neighbors, NativeLocalArray<float> distance, ref int neighborSize)
{
QueryNeighbors(tree, agents, agentID, ref rangeSq, 0, neighbors, distance, ref neighborSize);
}
static void QueryNeighbors(NativeArray<TreeNode> tree, NativeArray<float2> agents, int agentID, ref float rangeSq, int index, NativeLocalArray<int> neighbors, NativeLocalArray<float> distances, ref int neighborSize)
{
var agent = agents[agentID];
if (tree[index].end - tree[index].begin <= MAX_LEAF_SIZE)
{
for (int i = tree[index].begin; i < tree[index].end; ++i)
{
if (i != agentID)
{
float distSq = math.lengthSquared(agent - agents[i]);
if (distSq < rangeSq)
{
if (neighborSize < neighbors.Length)
{
neighbors[neighborSize] = i;
distances[neighborSize++] = distSq;
}
int k = neighborSize - 1;
while (k != 0 && distSq < distances[k - 1])
{
neighbors[k] = neighbors[k - 1];
distances[k] = distances[k - 1];
--k;
}
neighbors[k] = i;
distances[k] = distSq;
if (neighborSize == neighbors.Length)
{
rangeSq = distances[neighborSize - 1];
}
}
}
}
}
else
{
float distSqLeft =
sqr(math.max(0.0f, tree[tree[index].left].minX - agent.x)) +
sqr(math.max(0.0f, agent.x - tree[tree[index].left].maxX)) +
sqr(math.max(0.0f, tree[tree[index].left].minY - agent.y)) +
sqr(math.max(0.0f, agent.y - tree[tree[index].left].maxY));
float distSqRight =
sqr(math.max(0.0f, tree[tree[index].right].minX - agent.x)) +
sqr(math.max(0.0f, agent.x - tree[tree[index].right].maxX)) +
sqr(math.max(0.0f, tree[tree[index].right].minY - agent.y)) +
sqr(math.max(0.0f, agent.y - tree[tree[index].right].maxY));
if (distSqLeft < distSqRight)
{
if (distSqLeft < rangeSq)
{
QueryNeighbors(tree, agents, agentID, ref rangeSq, tree[index].left, neighbors, distances, ref neighborSize);
if (distSqRight < rangeSq)
{
QueryNeighbors(tree, agents, agentID, ref rangeSq, tree[index].right, neighbors, distances, ref neighborSize);
}
}
}
else
{
if (distSqRight < rangeSq)
{
QueryNeighbors(tree, agents, agentID, ref rangeSq, tree[index].right, neighbors, distances, ref neighborSize);
if (distSqLeft < rangeSq)
{
QueryNeighbors(tree, agents, agentID, ref rangeSq, tree[index].left, neighbors, distances, ref neighborSize);
}
}
}
}
}
static float sqr(float f) { return f * f; }
} |
JavaScript | UTF-8 | 11,138 | 2.75 | 3 | [] | no_license | function InputBox (input, textBox, onSubmit, initialText = "") {
this.input = input;
this.charBuffer = initialText;
this.onSubmit = onSubmit;
this.textBox = textBox;
this.required = true;
this.cursorBlinkState = true;
this.cursorIndex = 0;
this.selectionIndex = null;
}
InputBox.prototype = {
_updateShownText: function() {
let showText = this.masked ? this.maskBuffer() : this.charBuffer;
this.textBox.clear();
let textTiles;
if (showText.length) {
textTiles = this.textBox.addText(showText);
if (this.selectionIndex !== null) {
const fromIndex = Math.min(this.selectionIndex, this.cursorIndex);
const toIndex = Math.max(this.selectionIndex, this.cursorIndex);
for (var i = fromIndex; i < toIndex; i++) {
const tile = textTiles[i];
let // Swap foreground and background to indicate selected text
tmp = tile.r; tile.r = tile.br; tile.br = tmp;
tmp = tile.g; tile.g = tile.bg; tile.bg = tmp;
tmp = tile.b; tile.b = tile.bb; tile.bb = tmp;
}
}
} else {
textTiles = [];
}
// Always add a reserved space at the end for the cursor, which ensures
// getRemainingSpace is accurate for e.g. pasting. Also, with the way
// the textbox handles wrapping, it's better to add this here separately.
textTiles.push(this.textBox.addText(' ')[0]);
if (this.cursorBlinkState) {
const tile = textTiles[this.cursorIndex];
tile.r = tile.g = tile.b = 0;
tile.br = tile.bg = tile.bb = 255;
}
this.textBox.draw();
this.textBox.term.render();
},
setText: function (text) {
this.charBuffer = text;
let showText = this.masked ? this.maskBuffer() : this.charBuffer;
this.textBox.setText(showText + (this.active ? "_" : ""));
this.textBox.draw();
},
submit: function (){
if (this.required && this.charBuffer.trim() == "") {
return;
}
this.onSubmit(this.charBuffer);
if (this.clearOnSent) {
this.charBuffer = "";
this.cursorIndex = 0;
this.selectionIndex = null;
}
this._updateShownText();
},
cancelMessage: function (){
this.charBuffer = "";
this.cursorIndex = 0;
this.selectionIndex = null;
this._updateShownText();
},
draw: function () {
this.textBox.draw();
},
setActive: function (state) {
if (state) {
if (this.input.activeInputBox && this.input.activeInputBox.active) {
this.input.activeInputBox.setActive(false);
}
this.input.activeInputBox = this;
}
this.active = state;
this.setCursorIndex(this.charBuffer.length);
this.setCursorBlinkState(state);
},
maskBuffer: function () {
let ret = "";
for (let i = 0; i < this.charBuffer.length; i++) {
ret += "*";
}
return ret;
},
// Returns true if the caller should consume the key-press event
applyKey: function (key, metaDown, ctrlDown, altDown, shiftDown){
this.setCursorBlinkState(true); // Reset the cursor blink
if (key === 'Enter') {
this.submit();
return true;
}
if (key === 'Backspace') {
if (this.selectionIndex === null && this.cursorIndex > 0){
this.setSelection(this.cursorIndex - 1, this.cursorIndex);
}
this.deleteSelection();
return true;
}
if (key === 'Delete') {
if (this.selectionIndex === null && this.cursorIndex < this.charBuffer.length){
this.setSelection(this.cursorIndex, this.cursorIndex + 1);
}
this.deleteSelection();
return true;
}
// Note copy, paste etc needs to be handled by document events for
// security reasons (can't have unfettered access to the clipboard).
if ((metaDown || ctrlDown) && !altDown && !shiftDown && key === 'a'){
this.selectAll();
return true;
}
// Determine the x,y position of the cursor inside the text box for
// some relative movements like arrow up/down.
let cursorx = 0;
let cursory = 0;
for (; cursory < this.textBox.lines.length; cursory++){
const lineCharCount = this.textBox.lines[cursory].length;
if (cursorx + lineCharCount > this.cursorIndex){
cursorx = this.cursorIndex - cursorx;
break;
}
cursorx += lineCharCount;
}
const oldCursorIndex = this.cursorIndex;
const oldselectionIndex = this.selectionIndex;
let isCursorMoveKey = true;
if (key == 'Home') this.setCursorIndex(this.cursorIndex - cursorx);
else if (key == 'End') this.setCursorIndex(this.cursorIndex - cursorx + this.textBox.lines[cursory].length + (cursory == this.textBox.lines.length - 1 ? 0 : -1));
else if (key == 'PageUp') this.setCursorIndex(0);
else if (key == 'PageDown') this.setCursorIndex(this.charBuffer.length);
else if (key == 'ArrowLeft') this.setCursorIndex(Math.max(0, this.cursorIndex - 1));
else if (key == 'ArrowRight') this.setCursorIndex(Math.min(this.charBuffer.length, this.cursorIndex + 1));
else if (key == 'ArrowUp'){
if (cursory > 0) {
const prevLineLength = this.textBox.lines[cursory - 1].length;
this.setCursorIndex(this.cursorIndex - cursorx - prevLineLength + Math.min(cursorx, prevLineLength - 1));
}
} else if (key == 'ArrowDown'){
if (cursory < this.textBox.lines.length - 1) {
const cursorLineLength = this.textBox.lines[cursory].length;
const nextLineLength = this.textBox.lines[cursory + 1].length + (cursory + 1 == this.textBox.lines.length - 1 ? 0 : -1);
this.setCursorIndex(this.cursorIndex - cursorx + cursorLineLength + Math.min(cursorx, nextLineLength));
}
} else {
isCursorMoveKey = false;
}
if (isCursorMoveKey) {
if (!shiftDown || this.selectionIndex === this.cursorIndex) this.clearSelection();
else if (oldselectionIndex === null) this.setSelectionIndex(oldCursorIndex);
return true;
}
// If any of the modifier keys are down (except for shift), then
// assume the user is trying to doing some action, not typing.
if (!this.textBox.isFull() && key.length === 1 && !metaDown && !ctrlDown && !altDown) {
this.addText(key);
return true;
}
return false;
},
setCursorIndex: function(cursorIndex){
cursorIndex = Math.max(0, Math.min(cursorIndex, this.charBuffer.length));
this.cursorIndex = cursorIndex;
// Note, clearSelection calls _updateShownText
if (this.selectionIndex === cursorIndex) this.clearSelection();
else this._updateShownText();
},
setCursorBlinkState: function(state) {
this.cursorBlinkState = state;
if (this.cursorBlinkTimeout) {
clearTimeout(this.cursorBlinkTimeout);
}
if (this.active) {
this.cursorBlinkTimeout = setTimeout(() => this.setCursorBlinkState(!state), 600);
}
this._updateShownText();
},
setSelection: function(startIndex, endIndex) {
startIndex = Math.max(0, Math.min(this.charBuffer.length, startIndex));
endIndex = Math.max(0, Math.min(this.charBuffer.length, endIndex));
if (endIndex === startIndex) {
this.clearSelection();
return;
}
if (endIndex < startIndex) {
const temp = endIndex;
endIndex = startIndex;
startIndex = temp;
}
this.setCursorIndex(endIndex);
this.setSelectionIndex(startIndex);
},
setSelectionIndex: function(selectionIndex) {
if (!Number.isInteger(selectionIndex)) {
selectionIndex = null;
} else {
selectionIndex = Math.max(0, Math.min(this.charBuffer.length, selectionIndex));
if (selectionIndex === this.cursorIndex){
// There are no characters between the selIdx and curIdx if they're equal,
// so unset the selection.
selectionIndex = null;
}
}
this.selectionIndex = selectionIndex;
this._updateShownText();
},
addText: function(text) {
this.deleteSelection();
if (this.textBox.isFull()) return;
// Clean text of non printable and non ascii characters, i.e outside range
// space(32) to tilde(126)
text.replace(/[^ -~]/g, '');
// TODO this is still a bit wonky, because an unknown portion of remaining
// space may be used for graceful wrapping of the text. May have to just
// blindly add it in, then pare it back if it's overgrown.
if (text.length > this.textBox.getRemainingSpace()) {
text = text.substr(0, this.textBox.getRemainingSpace());
}
if (text.length === 0) return;
const oldText = this.charBuffer;
const left = this.cursorIndex > 0 ? oldText.substring(0, this.cursorIndex) : "";
const right = this.cursorIndex < oldText.length ? oldText.substring(this.cursorIndex, oldText.length) : "";
const newText = left + text + right;
if (newText === oldText) return;
this.clearSelection();
this.charBuffer = newText;
this.setCursorIndex(this.cursorIndex + text.length);
},
deleteSelection: function() {
if (this.selectionIndex === null) return undefined;
const from = Math.min(this.cursorIndex, this.selectionIndex);
const to = Math.max(this.cursorIndex, this.selectionIndex);
const oldSelection = this.clearSelection();
const oldText = this.charBuffer;
let newText = from === 0 ? '' : oldText.substring(0, from);
if (to < oldText.length) {
newText += oldText.substring(to, oldText.length);
}
this.clearSelection();
this.charBuffer = newText;
this.setCursorIndex(from);
return oldSelection;
},
selectAll: function() {
this.setSelection(0, this.charBuffer.length);
},
clearSelection: function() {
const oldSelection = this.getSelection();
this.setSelectionIndex(null);
return oldSelection;
},
getSelection: function() {
if (this.selectionIndex === null) return undefined;
const fromIndex = Math.min(this.selectionIndex, this.cursorIndex);
const toIndex = Math.max(this.selectionIndex, this.cursorIndex);
return this.charBuffer.substring(fromIndex, toIndex);
}
}
module.exports = InputBox; |
PHP | UTF-8 | 2,594 | 2.671875 | 3 | [] | no_license | <?php
class Page {
static function header($title) { ?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<?php }
static function footer() { ?>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</body>
</html>
<?php }
static function printMenu($menu) {
echo '<H3>Pizzas</H3>';
echo '<TABLE CLASS="table-striped">';
echo '<THEAD><TR><TH>Pizza Type</TH>
<TH>Item</TH>
<TH>Description</TH></TR></THEAD>';
foreach ($menu->pizzas as $key => $pizzaType) {
foreach ($pizzaType as $pizza) {
echo "<TR><TD>".$pizza->type."</TD>
<TD>".$pizza->item."</TD>
<TD>".$pizza->description."</TD></TR>";
}
}
echo "</TABLE>";
echo '<H3>Drinks</H3>';
echo '<TABLE CLASS="table-striped">';
echo '<THEAD><TR><TH>Drink Type</TH>
<TH>Item</TH>
<TH>Description</TH></TR></THEAD>';
foreach ($menu->drinks as $key => $drinkType) {
foreach ($drinkType as $drink) {
echo "<TR><TD>".$drink->type."</TD>
<TD>".$drink->item."</TD>
<TD>".$drink->description."</TD>
</TR>";
}
}
echo "</TABLE>";
}
static function notify($messages) {
echo '<DIV>';
foreach ($messages as $message) {
echo '•'.$message.'';
}
echo '</DIV>';
}
}
?> |
Java | UTF-8 | 1,101 | 3.875 | 4 | [] | no_license | import java.util.concurrent.Callable;
public class MyCallable implements Callable {
private Integer messageCount;
private Integer sleepTime;
private Integer cycleCount;
public MyCallable(String name, Integer sleepTime, Integer cycleCount) {
this.sleepTime = sleepTime;
this.messageCount = 0;
this.cycleCount = cycleCount;
Thread.currentThread().setName(name);
}
@Override
public Integer call() {
try {
for (int i = 0; i < cycleCount; i++) {
System.out.println("Я поток " + Thread.currentThread().getName() + ". Всем привет!");
messageCount++;
Thread.sleep(sleepTime);
}
} catch (InterruptedException err) {
System.out.println("Ошибка при попытке вызова метода sleep для потока " + Thread.currentThread().getName());
} finally {
System.out.printf("Поток %s завершен\n", Thread.currentThread().getName());
}
return messageCount;
}
}
|
C# | UTF-8 | 3,485 | 2.609375 | 3 | [] | no_license | using System.Threading.Tasks;
using UserRegistrationSystem.Core.Repositories;
using UserRegistrationSystem.Infrastructure.RelationalDatabase;
using UserRegistrationSystem.Infrastructure.Mapping.DBModelsMapping;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using UserRegistrationSystem.Core.Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace UserRegistrationSystem.Infrastructure.Repositories
{
public class UsersRepository : IUsersRepository
{
private readonly ApplicationDbContext _context;
private readonly UserManager<RelationalDatabase.DBEntities.User> _userManager;
public UsersRepository(ApplicationDbContext context, UserManager<RelationalDatabase.DBEntities.User> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task<User> AddUser(User user)
{
var dbUser = user.ToDbObject();
await _userManager.CreateAsync(dbUser, user.Password);
return dbUser.ToObject();
}
public async Task<IdentityResult> DeleteUser(RelationalDatabase.DBEntities.User user)
{
var result = await _userManager.DeleteAsync(user);
return result;
}
public async Task<User> UpdateUserAndAddress(User user)
{
var dbUser = await GetUserByUserName(user.UserName);
if (dbUser != null)
{
dbUser.IsMarried = user.IsMarried;
dbUser.IsEmployed = user.IsEmployed;
dbUser.Salary = user.Salary;
if (dbUser.Address != null)
{
dbUser.Address.Building = user.Address.Building;
dbUser.Address.Country = user.Address.Country;
dbUser.Address.City = user.Address.City;
dbUser.Address.Street = user.Address.Street;
dbUser.Address.Apartment = user.Address.Apartment;
}
await _userManager.UpdateAsync(dbUser);
}
return dbUser.ToObject();
}
public async Task<RelationalDatabase.DBEntities.User> GetUserByUserName(string userName)
{
var existedUser = await FindUserByUserName(userName);
if (existedUser != null)
{
existedUser.Address = await GetAddressByUserId(existedUser.Id);
}
return existedUser;
}
public async Task<bool> CheckUserPassword(LoginModel loginModel)
{
var user = await FindUserByUserName(loginModel.UserName);
return (user != null && await _userManager.CheckPasswordAsync(user, loginModel.Password));
}
public async Task<List<string>> GetUserRoles(string userName)
{
var user = await FindUserByUserName(userName);
return (await _userManager.GetRolesAsync(user)).ToList();
}
#region private methods
private async Task<RelationalDatabase.DBEntities.Address> GetAddressByUserId(Guid? userId)
{
return await _context.Addresses.FirstOrDefaultAsync(item => item.UserId == userId);
}
private async Task<RelationalDatabase.DBEntities.User> FindUserByUserName(string userName)
{
return await _userManager.FindByNameAsync(userName);
}
#endregion
}
} |
Shell | UTF-8 | 843 | 3.109375 | 3 | [] | no_license | #!/bin/bash
#Setup disk and copy and configure various parts of the Arch install.
pvcreate /dev/mapper/cryptlvm
vgcreate system /dev/mapper/cryptlvm
lvcreate -L 8G system -n swap
lvcreate -L 32G system -n root
lvcreate -l 100%FREE system -n home
mkfs.ext4 /dev/system/root
mkfs.ext4 /dev/system/home
mkfs.fat -F32 /dev/sda2
mkswap /dev/system/swap
mount /dev/system/root /mnt
mkdir /mnt/home
mount /dev/system/home /mnt/home
mkdir /mnt/efi
mount /dev/sda2 /mnt/efi
swapon /dev/system/swap
cp -ax / /mnt
cp -vaT /run/archiso/bootmnt/arch/boot/$(uname -m)/vmlinuz /mnt/boot/vmlinuz-linux
echo "This script will now go into a chroot, after having copied the install2.sh and other pertinent items to the chroot device."
cp install{2,4}.sh /mnt
cp locale.conf /mnt/etc/locale.conf
rm /mnt/etc/hosts
cp hosts /mnt/etc
arch-chroot /mnt /bin/bash
|
PHP | UTF-8 | 5,742 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Lib\ImageDownloader;
use Goutte\Client as GoutteClient;
use Ramsey\Uuid\Uuid;
use GuzzleHttp\Exception\RequestException;
use App\Stpack;
use App\Sticker;
use Exception;
use App\Lib\Telegram\Api;
use Config;
class Line
{
public function __construct(){}
/**
* downlolad sticker from line
* @param $id stpack id
* @return model App\Stpack | array
*/
public function download($id) {
$client = new GoutteClient();
try {
$crawler = $client->request('GET', 'https://store.line.me/stickershop/product/'.$id.'/ja');
} catch(RequestException $e) {
$response = $e->getResponse();
$status_code = $response->getStatusCode();
return [
'code' => $status_code,
'error' => $this->getStatusStr($status_code),
'error_description' => 'LINE server returned an ERROR',
];
}
$telegram_api = new Api(Config::get('telegram.authorization_token'));
// Goutte, 指定したセレクタが存在しないとエラーを吐く.
try {
$name = $crawler->filter('.mdCMN08Ttl')->text();
$short_name = 'l'.str_replace('-', '_', Uuid::uuid4()->toString()).'_by_'.$telegram_api->user->getUsername();
$original_url = 'https://store.line.me/stickershop/product/'.$id.'/ja';
$sticker_urls = $crawler->filter('.mdCMN09Image')->each(function ($node) {
return $this->getNodeBackgroundImage($node);
});
} catch(Exception $e) {
return [
'code' => 404,
'error' => $this->getStatusStr(404),
'error_description' => 'There are no stickers or download restricted',
];
}
$stickers = [];
$sticker_models = [];
foreach ($sticker_urls as $url) {
$formatted_url = explode(';', $url)[0];
$sticker_id = $this->getStickerIdFromUrl($formatted_url);
$sticker = [
'id' => $sticker_id,
'original_url' => $formatted_url,
];
$stickers[] = $sticker;
$sticker_models[] = new Sticker($sticker);
}
$stpack_data = [
'id' => $id,
'name' => $name,
'short_name' => $short_name,
'thumbnail_url' => $stickers[0]['original_url'],
'original_url' => $original_url,
'stickers' => $stickers,
];
$stpack = Stpack::create($stpack_data);
$stpack->stickers()->saveMany($sticker_models);
return $stpack;
}
/**
* Get sticker ID from its image's URL
* @param string $url Image URL for the sticker
* @return string $sticker_id ID for the sticker
*/
protected function getStickerIdFromUrl($url) {
preg_match('/sticker\/(.+?)\//', $url, $sticker_id);
return $sticker_id[1];
}
/**
* Get background-image from DOM node
* @param Crawler $node DOM node
* @return string $background_image Value of background-image
*/
protected function getNodeBackgroundImage($node) {
preg_match(
'/\s?background-image:\s?url\([\'\"]*(.+?)[\'\"]*\)/',
$node->attr('style'),
$matches
);
return $matches[1];
}
public function getStatusStr($code) {
switch ($code) {
case 100: $text = 'Continue'; break;
case 101: $text = 'Switching Protocols'; break;
case 200: $text = 'OK'; break;
case 201: $text = 'Created'; break;
case 202: $text = 'Accepted'; break;
case 203: $text = 'Non-Authoritative Information'; break;
case 204: $text = 'No Content'; break;
case 205: $text = 'Reset Content'; break;
case 206: $text = 'Partial Content'; break;
case 300: $text = 'Multiple Choices'; break;
case 301: $text = 'Moved Permanently'; break;
case 302: $text = 'Moved Temporarily'; break;
case 303: $text = 'See Other'; break;
case 304: $text = 'Not Modified'; break;
case 305: $text = 'Use Proxy'; break;
case 400: $text = 'Bad Request'; break;
case 401: $text = 'Unauthorized'; break;
case 402: $text = 'Payment Required'; break;
case 403: $text = 'Forbidden'; break;
case 404: $text = 'Not Found'; break;
case 405: $text = 'Method Not Allowed'; break;
case 406: $text = 'Not Acceptable'; break;
case 407: $text = 'Proxy Authentication Required'; break;
case 408: $text = 'Request Time-out'; break;
case 409: $text = 'Conflict'; break;
case 410: $text = 'Gone'; break;
case 411: $text = 'Length Required'; break;
case 412: $text = 'Precondition Failed'; break;
case 413: $text = 'Request Entity Too Large'; break;
case 414: $text = 'Request-URI Too Large'; break;
case 415: $text = 'Unsupported Media Type'; break;
case 500: $text = 'Internal Server Error'; break;
case 501: $text = 'Not Implemented'; break;
case 502: $text = 'Bad Gateway'; break;
case 503: $text = 'Service Unavailable'; break;
case 504: $text = 'Gateway Time-out'; break;
case 505: $text = 'HTTP Version not supported'; break;
default:
$text = 'unknown status code';
break;
}
return $text;
}
}
|
C# | UTF-8 | 1,727 | 3.09375 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace YiSha.Util
{
public class ReflectionHelper
{
private static ConcurrentDictionary<string, object> dictCache = new ConcurrentDictionary<string, object>();
#region 得到类里面的属性集合
/// <summary>
/// 得到类里面的属性集合
/// </summary>
/// <param name="type"></param>
/// <param name="columns"></param>
/// <returns></returns>
public static PropertyInfo[] GetProperties(Type type, string[] columns = null)
{
PropertyInfo[] properties = null;
if (dictCache.ContainsKey(type.FullName))
{
properties = dictCache[type.FullName] as PropertyInfo[];
}
else
{
properties = type.GetProperties();
dictCache.TryAdd(type.FullName, properties);
}
if (columns != null && columns.Length > 0)
{
// 按columns顺序返回属性
var columnPropertyList = new List<PropertyInfo>();
foreach (var column in columns)
{
var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();
if (columnProperty != null)
{
columnPropertyList.Add(columnProperty);
}
}
return columnPropertyList.ToArray();
}
else
{
return properties;
}
}
#endregion
}
}
|
Python | UTF-8 | 2,767 | 3.71875 | 4 | [] | no_license | import math
import function as function
class Main:
f = function.Function()
e = 0.001
def __init__(self, epsilon=0.001):
e = epsilon
def newtons_method(self, start_approximation, func):
while start_approximation > 0\
and ((self.f.function(0)) * (self.f.function(start_approximation)) >= 0):
start_approximation -= 0.005
n = 0
while abs(func.function(start_approximation)) > self.e:
n += 1
start_approximation -= (func.function(start_approximation)) / func.derivative(start_approximation)
return start_approximation, n
def fixed_point_iteration_method(self, start_approximation, func):
while start_approximation > 0\
and ((self.f.function(0)) * (self.f.function(start_approximation)) >= 0):
start_approximation -= 0.005
n = 0
while abs(func.function(start_approximation)) > self.e:
n += 1
start_approximation += func.function(start_approximation)
return start_approximation, n
def fixed_point_iteration_method_reverse(self, start_approximation, func):
while start_approximation > 0\
and ((self.f.function(0)) * (self.f.function(start_approximation)) >= 0):
start_approximation -= 0.005
n = 0
while abs(func.function(start_approximation)) > self.e:
n += 1
start_approximation -= func.function(start_approximation)
return start_approximation, n
def find_fwhm(self, method_left, method_right):
max_x, max_value = function.Function.get_max()
x_l, n_l = method_left(max_x - 0.4, self.f)
print(f"Left roote is {x_l}")
x_r, n_r = method_right(max_x + 0.2, self.f)
print(f"Right roote is {x_r}")
return x_r - x_l, n_l, n_r
def show_results(self):
print("Solving with Newton's method")
r_n, n_l_n, n_r_n = self.find_fwhm(self.newtons_method, self.newtons_method)
print("\nSolving with fixed-point iteration method")
r_fpi, n_l_fpi, n_r_fpi = self.find_fwhm(self.fixed_point_iteration_method_reverse, self.fixed_point_iteration_method)
print()
print(f"For the fixed-point iteration method results are:\nx_r - x_l = {r_fpi}")
print(f"Number of iterations for finding the left limit: {n_l_fpi}")
print(f"Number of iterations for finding the right limit: {n_r_fpi}\n")
print(f"For the Newton's method results are:\nx_r - x_l = {r_n}")
print(f"Number of iterations for finding the left limit: {n_l_n}")
print(f"Number of iterations for finding the right limit: {n_r_n}")
if __name__ == '__main__':
main = Main()
main.show_results()
|
PHP | UTF-8 | 3,711 | 2.8125 | 3 | [] | no_license | <?php
require_once dirname( __FILE__ ) . '/../lib/SmashingBase.php';
require_once 'PHPUnit/Framework/Constraint/IsInstanceOf.php';
require_once 'PHPUnit/Framework/Constraint/IsType.php';
/**
* These tests cover our SmashingBase class. There are quite a few mock
* objects involved here because the SmashingBase class is the seam between
* our plugin and WordPress. By using mock objects, we can isolate our
* plugin code from the rest of WordPress and just test the specific units
* we're concerned about.
*/
class SmashingBaseTest extends PHPUnit_Framework_TestCase
{
/**
* @var wpdb
*/
protected $wpdb;
/**
* We use our setUp() method in this case just to stash a reference to wpdb
* for use in the other test cases. PHPUnit will run this method before
* each of the test methods in this class so that we always start off with
* a clean slate.
*/
public function setUp()
{
global $wpdb;
$this->wpdb = $wpdb;
}
/**
* In this case we simulate our admin_init handler being called when no
* user is logged in. In that situation, we don't want to the log to be
* updated, so we use PHPUnit's mock object API to ensure that it isn't.
*
* To create a mock object, you just call getMock() inside your test case,
* supplying it with three arguments:
*
* <ol>
* <li>The class you want to create a mock for.</li>
* <li>An array of methods you'd like to mock.</li>
* <li>An array of parameters to supply to the object's constructor.</li>
* </ol>
*/
public function testLogIsNotUpdatedIfUserIsNotLoggedIn()
{
$log = $this->getMock(
'SmashingLog',
array( 'update' ),
array( $this->wpdb )
);
$base = $this->getMock(
'SmashingBase',
array( 'is_user_logged_in' ),
array( $log )
);
$log
->expects( $this->never() )
->method( 'update' );
$base
->expects( $this->once() )
->method( 'is_user_logged_in' )
->will( $this->returnValue( false ) );
$base->admin_init();
}
/**
* In this case, we want to make sure the log's update method is called if
* admin_init is run while a user is logged in. We don't want to actually
* run the log's true update method because we're testing SmashingBase here,
* not SmashingLog. For this test case, we just want to know that the logic
* in SmashingBase accurately passes responsibilty onto the log when it
* should.
*/
public function testLogIsUpdatedIfUserIsLoggedIn()
{
$log = $this->getMock(
'SmashingLog',
array( 'update' ),
array( $this->wpdb )
);
$base = $this->getMock(
'SmashingBase',
array( 'is_user_logged_in', 'get_current_user_id' ),
array( $log )
);
$log
->expects( $this->once() )
->method( 'update' );
$base
->expects( $this->once() )
->method( 'is_user_logged_in' )
->will( $this->returnValue( true ) );
$base
->expects( $this->once() )
->method( 'get_current_user_id' )
->will( $this->returnValue( 1 ) );
$base->admin_init();
}
/**
* In this case, we're testing to make sure our dashboard_setup handler
* correctly adds the dashboard widget. Because these WP functions won't
* exist in the test environment, we just test that the function is called
* using arguments of the correct/expected types.
*/
public function testDashboardSetupAddsWidget()
{
$base = $this->getMock(
'SmashingBase',
array( 'add_dashboard_widget' ),
array()
);
$base
->expects( $this->once() )
->method( 'add_dashboard_widget' )
->with(
new PHPUnit_Framework_Constraint_IsType( 'string' ),
new PHPUnit_Framework_Constraint_IsType( 'string' ),
new PHPUnit_Framework_Constraint_IsType( 'callable' )
);
$base->dashboard_setup();
}
}
|
Java | UTF-8 | 1,099 | 2.578125 | 3 | [] | no_license | package com.websystique.springmvc.dtos;
import com.websystique.springmvc.pojos.City;
public class CityDTO {
private int id;
private String city;
private String uuid;
private CountryDTO country;
private byte isDeleted;
public CityDTO() {
}
public CityDTO(String id) {
this.id = Integer.parseInt(id);
}
public CityDTO(City city) {
this.id = city.getId();
this.city = city.getCity();
this.uuid = city.getUuid();
// this.country = new CountryDTO(city.getCountry());
this.isDeleted = city.getIsDeleted();
}
public void setIsDeleted(byte isDeleted) {
this.isDeleted = isDeleted;
}
public byte getIsDeleted() {
return isDeleted;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public CountryDTO getCountry() {
return country;
}
public void setCountry(CountryDTO country) {
this.country = country;
}
}
|
Shell | UTF-8 | 1,381 | 2.671875 | 3 | [] | no_license | # The following lines were added by compinstall
zstyle ':completion:*' completer _complete _ignored
zstyle :compinstall filename '/home/antonioh/.zshrc'
autoload -Uz compinit
compinit
# End of lines added by compinstall
# Lines configured by zsh-newuser-install
HISTFILE=~/.histfile
HISTSIZE=1000
SAVEHIST=1000
unsetopt beep
bindkey -e
# End of lines configured by zsh-newuser-install
# For vkernel building scripts
export REPOSITORY=/build/home/antonioh/s/dragonfly
export VKDIR=/build/home/antonioh/vk
# From http://stackoverflow.com/questions/1128496/to-get-a-prompt-which-indicates-git-branch-in-zsh (Christopher)
setopt prompt_subst
autoload -Uz vcs_info
zstyle ':vcs_info:*' stagedstr 'M'
zstyle ':vcs_info:*' unstagedstr 'M'
zstyle ':vcs_info:*' check-for-changes true
zstyle ':vcs_info:*' actionformats '%F{5}[%F{2}%b%F{3}|%F{1}%a%F{5}]%f '
zstyle ':vcs_info:*' formats \
'%F{5}[%F{2}%b%F{5}] %F{2}%c%F{3}%u%f'
zstyle ':vcs_info:git*+set-message:*' hooks git-untracked
zstyle ':vcs_info:*' enable git
+vi-git-untracked() {
if [[ $(git rev-parse --is-inside-work-tree 2> /dev/null) == 'true' ]] && \
[[ $(git ls-files --no-empty-directory --other --directory --exclude-standard | sed q | wc -l | tr -d ' ') == 1 ]] ; then
hook_com[unstaged]+='%F{1}??%f'
fi
}
precmd () { vcs_info }
PROMPT='%F{5}[%F{2}%n%F{5}] %F{3}%3~ ${vcs_info_msg_0_} %f%# '
|
JavaScript | UTF-8 | 5,929 | 2.984375 | 3 | [] | no_license | var move_up = 0;
var move_down = 0;
var hit = new sound("hit.mp3");
var bgm = new sound('bgm_3.mp3');
var gameover = new sound("gameover.mp3");
var canvas = document.getElementById("game_area");
var pad1 = canvas.getContext("2d");
var pad2 = canvas.getContext("2d");
var object = canvas.getContext("2d");
var pongball = new Image();
pongball.src = "ball.png";
var time = new Date();
var start_time = time.getTime();
var paddle1 = {
x: 5,
y: 160,
width: 15,
height: 100,
score: 0,
color: 'yellow'
}
var paddle2 = {
x: 1280,
y: 160,
width: 15,
height: 100,
score: 0,
color: 'aqua'
}
var ball = {
x: 625,
y: 190,
width: 20,
height: 20,
speed: 5,
left: 1, //ball.left=1 shows ball should move leftwards
down: 1, //ball.down=1 shows ball should move downwards
move: 1, //ball.move=1 shows ball should move
}
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function() {
this.sound.play();
}
this.stop = function() {
this.sound.pause();
}
}
window.addEventListener("keydown", move, false);
pad1.fillStyle = paddle1.color;
pad1.fillRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
pad2.fillStyle = paddle2.color;
pad2.fillRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
function animate() {
if (ball.move == 1) {
reqAnimFrame = window.mozRequestAnimationFrame || //since different browsers have different names for this function
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
reqAnimFrame(animate);
draw();
}
}
function draw() {
pad1.clearRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
pad2.clearRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
object.clearRect(ball.x, ball.y, ball.width, ball.height);
var t = new Date();
if ((ball.x == (paddle1.x + 15)) && (((ball.y < (paddle1.y + 100)) && (ball.y > paddle1.y)) || (((ball.y + 20) < (paddle1.y + 100)) && ((ball.y + 20) > paddle1.y)))) {
ball.collide = 1;
ball.left = 0;
hit.play();
paddle1.score++;
paddle1.y = Math.floor(Math.random() * 300);
} else if ((ball.x == (paddle2.x - 15)) && (((ball.y < (paddle2.y + 100)) && (ball.y > paddle2.y)) || (((ball.y + 20) < (paddle2.y + 100)) && ((ball.y + 20) > paddle2.y)))) {
ball.collide = 1;
ball.left = 1;
hit.play();
paddle2.score++;
paddle2.y = Math.floor(Math.random() * 300);
}
if (move_up == 1) {
if (ball.left == 1) {
paddle1.y -= 50;
move_up = 0;
} else {
paddle2.y -= 50;
move_up = 0;
}
}
if (move_down == 1) {
if (ball.left == 1) {
paddle1.y += 50;
move_down = 0;
} else {
paddle2.y += 50;
move_down = 0;
}
}
if (ball.left == 1) {
ball.x -= ball.speed;
if (ball.down == 1) {
ball.y += ball.speed;
} else {
ball.y -= ball.speed;
}
} else {
ball.x += ball.speed;
if (ball.down == 1) {
ball.y += ball.speed;
} else {
ball.y -= ball.speed;
}
}
if (ball.y <= 0) {
ball.y += ball.speed;
ball.down = 1;
}
if (ball.y >= 380) {
ball.y -= ball.speed;
ball.down = 0;
}
pad1.fillStyle = paddle1.color;
pad1.fillRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
pad2.fillStyle = paddle2.color;
pad2.fillRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
object.drawImage(pongball, ball.x, ball.y, ball.width, ball.height);
document.getElementById("score").innerHTML = "SCORE = " + paddle1.score + " : " + paddle2.score;
if (ball.x <= 0) {
object.clearRect(ball.x, ball.y, ball.width, ball.height);
paddle2.score++;
document.getElementById("score").innerHTML = "SCORE = " + paddle1.score + " : " + paddle2.score;
bgm.stop();
gameover.play();
pad1.clearRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
pad2.clearRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
pad1.rect(0, 0, 1300, 400);
pad1.fillStyle = "#009900";
pad1.fill();
object.font = "50px 'Exo',sans-serif";
object.fillStyle = "white";
object.fillText("GAME OVER !!", 494, 150);
object.fillText("PLAYER-2 WINS !", 465, 220);
ball.move = 0;
}
if (ball.x >= 1280) {
object.clearRect(ball.x, ball.y, ball.width, ball.height);
paddle1.score++;
document.getElementById("score").innerHTML = "SCORE = " + paddle1.score + " : " + paddle2.score;
bgm.stop();
gameover.play();
pad1.clearRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
pad2.clearRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
pad1.rect(0, 0, 1300, 400);
pad1.fillStyle = "#009900";
pad1.fill();
object.font = "50px 'Exo',sans-serif";
object.fillStyle = "white";
object.fillText("GAME OVER !!", 494, 150);
object.fillText("PLAYER-1 WINS !", 465, 220);
ball.move = 0;
}
}
function start() {
bgm.play();
animate();
}
function move(e) {
if (e.keyCode == 38) {
move_up = 1;
}
if (e.keyCode == 40) {
move_down = 1;
}
}
function resume() {
ball.move = 1;
animate();
//start();
}
function pause() {
ball.move = 0;
bgm.stop();
} |
Java | UTF-8 | 9,303 | 2.859375 | 3 | [] | no_license | package org.kerw1n.javautil.file;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.kerw1n.javautil.format.ReflectionUtil;
import org.springframework.util.Assert;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
/**
* Excel 操作
*
* @author kerw1n
*/
public class ExcelUtil {
/**
* 单表最大写入行数,不包含标题行
*/
private static final int MAX_ROW = 65535;
/**
* 初始页码
*/
private static final int INIT_PAGE = 1;
/**
* 2003 版后缀名称
*/
private static final String SUFFIX_2003 = ".xls";
/**
* 2007 版后缀名称
*/
private static final String SUFFIX_2007 = ".xlsx";
/**
* 默认表名称
*/
private static final String DEFAULT_SHEET_NAME = "sheet";
private ExcelUtil() {
}
/**
* 读取 Excel 文件
* <p>
* 需含有标题行,返回 {@link List} 列表,{@link HashMap} 对应的键值分别为标题、值。
* 列表顺序与表格顺序相同;
*
* @param file Excel 文件
* @return {@code List<HashMap<String, Object>> }
* @throws Exception
*/
public static List<HashMap<String, String>> read(File file) throws IOException {
return read(new FileInputStream(file));
}
/**
* 读取Excel文件流
* <p>
* 需含有标题行,返回List列表,HashMap对应的键值分别为标题、值,列表顺序与表格顺序相同;
*
* @param inp 文件流
* @return {@code List<HashMap<String, Object>> }
* @throws Exception
*/
public static List<HashMap<String, String>> read(InputStream inp) throws IOException {
List<HashMap<String, String>> result = null;
try {
// 创建工作簿
Workbook workbook = createWorkbook(inp);
// 获取第一张表
Sheet sheet = workbook.getSheetAt(0);
// 标题行
Row headerRow = sheet.getRow(0);
int lastCellNum = headerRow.getLastCellNum();
if (lastCellNum == 0) {
return null;
}
String[] headerArray = new String[lastCellNum];
int j = 0;
while (j < lastCellNum) {
String cellTitle = getCell(headerRow, j);
if (StringUtils.isEmpty(cellTitle)) {
continue;
}
headerArray[j] = cellTitle;
j++;
}
int lastRowNum = sheet.getLastRowNum();
result = new ArrayList<>(lastRowNum);
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
HashMap<String, String> data = new HashMap<>(lastCellNum);
int k = 0;
while (k < lastCellNum) {
data.put(headerArray[k], getCell(row, k));
result.add(data);
k++;
}
}
} finally {
IoUtil.close(inp);
}
return result;
}
/**
* 写数据到 Excel,行数超过 {@link #MAX_ROW} 时分表
*
* @param sheetName 工作表名称
* @param data 数据源,考虑到应用场景,目前仅支持 {@link List}
* @param title 标题行<br>
* key:指定字段名称,与 JavaBean 中对应<br>
* value:显示的标题名称,为空则取字段名
* @param path 生成的文件路径
* @throws Exception
*/
public static <T> void write(String sheetName, final List<T> data, final Map<String, String> title, String path) throws IOException, ReflectiveOperationException {
Assert.isTrue((data != null && data.size() > 0), "Invalid data source.");
Assert.isTrue((title != null && title.size() > 0), "Invalid column.");
int total = data.size(), page = getPage(total);
Workbook workbook = null;
FileOutputStream os = null;
try {
workbook = createWorkbook(path);
for (int l = 0; l < page; l++) {
// 开始位置的下标、行号
int beginIndex = l * MAX_ROW, rowNum = 0;
// 创建表
Sheet sheet = workbook.createSheet(getSheetName(sheetName, (l + 1)));
// 创建标题行
Row titleRow = sheet.createRow(0);
for (int i = beginIndex; i < total; i++) {
if (rowNum == MAX_ROW) {
break;
}
T d = data.get(i);
if (d == null) {
continue;
}
Class<?> clazz = d.getClass();
Field[] fields = ReflectionUtil.getClassFields(clazz);
if (fields == null) {
continue;
}
int column = 0;
Row row = sheet.createRow(rowNum + 1);
for (Map.Entry<String, String> map : title.entrySet()) {
String key = map.getKey(), val = map.getValue();
// 写入标题
Cell titleCell = titleRow.createCell(column);
titleCell.setCellValue(null == val ? key : val);
if (StringUtils.isEmpty(key)) {
continue;
}
for (Field field : fields) {
String fieldName = field.getName();
if (fieldName.equalsIgnoreCase(key)) {
// 匹配字段赋值
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Object value = clazz.getMethod(getMethodName).invoke(d);
Cell cell = row.createCell(column);
cell.setCellValue(value.toString());
break;
}
}
column++;
}
rowNum++;
}
}
os = new FileOutputStream(path);
workbook.write(os);
os.flush();
} finally {
IoUtil.close(workbook, os);
}
}
/**
* 获取工作表名称
*
* @param name
* @param index
* @return 表名称
*/
private static String getSheetName(String name, int index) {
return StringUtils.isEmpty(name) ? DEFAULT_SHEET_NAME + index : name;
}
/**
* 获取页数
*
* @param total 总条数
* @return
*/
private static int getPage(int total) {
int page = INIT_PAGE;
if (total > MAX_ROW) {
page = total / MAX_ROW;
if (total % MAX_ROW != 0) {
page++;
}
}
return page;
}
/**
* 根据文件流创建工作簿对象
* 创建不同版本Excel 的工作簿.
*
* @param inp 文件流
* @return
* @throws IOException
*/
private static Workbook createWorkbook(InputStream inp) throws IOException {
if (!inp.markSupported()) {
inp = new PushbackInputStream(inp, 8);
}
if (POIFSFileSystem.hasPOIFSHeader(inp)) {
return new HSSFWorkbook(inp);
} else if (POIXMLDocument.hasOOXMLHeader(inp)) {
return new XSSFWorkbook(inp);
}
throw new IllegalArgumentException("不支持的excel版本.");
}
/**
* 根据文件名创建工作簿对象
*
* @param path
* @return
*/
private static Workbook createWorkbook(String path) {
if (StringUtils.isNotEmpty(path)) {
if (path.endsWith(SUFFIX_2003)) {
return new HSSFWorkbook();
} else if (path.endsWith(SUFFIX_2007)) {
return new XSSFWorkbook();
}
}
throw new IllegalArgumentException("不支持的excel版本.");
}
/**
* 获取指定单元格的值
* 均按照字符串处理,日期则格式化为{@link org.kerw1n.javautil.format.DateUtil.Format#FORMAT_03}
*
* @param row
* @param cellNum
* @return
*/
private static String getCell(Row row, int cellNum) {
Cell cell = row.getCell(cellNum);
if (cell == null) {
return null;
}
String value = "";
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)) {
Date d = cell.getDateCellValue();
value = org.kerw1n.javautil.format.DateUtil.formatDate(d, org.kerw1n.javautil.format.DateUtil.Format.FORMAT_03);
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
value = cell.getStringCellValue();
}
return value;
}
}
|
TypeScript | UTF-8 | 3,413 | 2.5625 | 3 | [
"MIT"
] | permissive | import { Request, Response } from 'express';
import { check } from 'express-validator';
import dbAppointments from '../db/appointments';
import dbPatient from '../db/patients';
import dbPsychologists from '../db/psychologists';
import asyncHelper from '../utils/async-helper';
import CustomError from '../utils/CustomError';
import dateUtils from '../utils/date';
import validation from '../utils/validation';
const createValidators = [
check('date')
.isISO8601()
.withMessage('Vous devez spécifier une date pour la séance.'),
check('patientId')
.isUUID()
.withMessage('Vous devez spécifier un patient pour la séance.'),
check('renewal')
.isBoolean()
.withMessage("Vous devez confirmer que c'est un renouvellement."),
];
const create = async (req: Request, res: Response): Promise<void> => {
// Todo : test case where patient id does not exist
validation.checkErrors(req);
const { patientId, renewal } = req.body;
const psyId = req.auth.psychologist;
const date = new Date(req.body.date);
const today = new Date();
const limitDate = new Date(today.setMonth(today.getMonth() + 4));
const patientExist = await dbPatient.getById(patientId, psyId);
if (!patientExist) {
console.warn(`Patient id ${patientId} does not exist for psy id : ${psyId}`);
throw new CustomError("Erreur. La séance n'est pas créée. Pourriez-vous réessayer ?");
}
const psy = await dbPsychologists.getById(psyId);
if (date < psy.createdAt) {
console.warn("It's impossible to declare an appointment before psychologist creation date");
throw new CustomError("La date de la séance ne peut pas être antérieure à l'inscription au dispositif", 400);
}
if (date > limitDate) {
console.warn('The difference between today and the declaration date is beyond 4 month');
throw new CustomError('La date de la séance doit être dans moins de 4 mois', 400);
}
if (renewal) {
await dbPatient.renew(patientId, psyId);
}
await dbAppointments.insert(date, patientId, psyId);
console.log(`Appointment created for patient id ${patientId} by psy id ${psyId}`);
res.json({ message: `La séance du ${dateUtils.formatFrenchDate(date)} a bien été créée.` });
};
const deleteValidators = [
check('appointmentId')
.isUUID()
.withMessage('Vous devez spécifier une séance à supprimer.'),
];
const deleteOne = async (req: Request, res: Response): Promise<void> => {
validation.checkErrors(req);
const { appointmentId } = req.params;
const psychologistId = req.auth.psychologist;
const deletedAppointment = await dbAppointments.delete(appointmentId, psychologistId);
if (deletedAppointment === 0) {
console.log(
`Appointment ${appointmentId} does not belong to psy id ${psychologistId}`,
);
throw new CustomError('Impossible de supprimer cette séance.', 404);
}
console.log(
`Appointment deleted ${appointmentId} by psy id ${psychologistId}`,
);
res.json({
message: 'La séance a bien été supprimée.',
});
};
const getAll = async (req: Request, res: Response): Promise<void> => {
const psychologistId = req.auth.psychologist;
const appointments = await dbAppointments.getAll(psychologistId);
res.json(appointments);
};
export default {
createValidators,
deleteValidators,
create: asyncHelper(create),
getAll: asyncHelper(getAll),
delete: asyncHelper(deleteOne),
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.