language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 323 | 2.53125 | 3 | [] | no_license | package br.com.tt.aula01;
public class Exercicio2 {
public static void main(String[]args) {
float nota1 = 9.8f;
float nota2 = 7.1f;
float nota3 = 5.3f;
float nota4 = 8.7f;
System.out.println("Soma="+((nota1+nota2+nota3+nota4)/4));
//Resposta = 7.72
}
}
|
Go | UTF-8 | 1,107 | 2.640625 | 3 | [
"MIT"
] | permissive | package helper
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"github.com/parnurzeal/gorequest"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
func DownloadHtml(url string, args ...interface{}) ([]byte, error) {
request := gorequest.New()
resp, _, _ := request.Get(url).
Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36").
End()
fmt.Println(resp.StatusCode)
if len(args) == 0 {
utf8Content := transform.NewReader(resp.Body, simplifiedchinese.GBK.NewDecoder())
return ioutil.ReadAll(utf8Content)
} else {
e := determineCharset(resp.Body)
utf8Content := transform.NewReader(resp.Body, e.NewDecoder())
return ioutil.ReadAll(utf8Content)
}
}
func determineCharset(i io.Reader) encoding.Encoding {
resp, err := bufio.NewReader(i).Peek(1024)
if err != nil {
return unicode.UTF8
}
e, _, _ := charset.DetermineEncoding(resp, "")
//fmt.Println(e)
return e
}
|
Java | UTF-8 | 203 | 2.84375 | 3 | [] | no_license | package nonfunctionalprogramming;
public class AppleHeavyWeightPredicate implements ApplePredicate{
@Override
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
}
|
Markdown | UTF-8 | 1,851 | 2.609375 | 3 | [] | no_license | ---
title: easyswoole Smtp Client
meta:
- name: description
content: Easyswoole provides a mail sending component. E-mail is a kind of communication mode that provides information exchange by electronic means. It is the most widely used service on the Internet. Email is essential to almost every web application, whether it's a newsletter or an order confirmation. This component uses the swoole cooperation client to realize the sending of e-mail。
- name: keywords
content: easyswoole Smtp Client|swoole smtp|swoole coroutine smtp
---
# Smtp
Easyswoole provides a mail sending component. E-mail is a kind of communication mode that provides information exchange by electronic means. It is the most widely used service on the Internet. Email is essential to almost every web application, whether it's a newsletter or an order confirmation. This component uses the swoole cooperation client to realize the sending of e-mail。
## Install
```php
composer require easyswoole/smtp
```
## Use
```php
use EasySwoole\Smtp\Mailer;
use EasySwoole\Smtp\MailerConfig;
use EasySwoole\Smtp\Message\Html;
use EasySwoole\Smtp\Message\Attach;
// Must use go function
go(function (){
$config = new MailerConfig();
$config->setServer('smtp.163.com');
$config->setSsl(false);
$config->setUsername('huizhang');
$config->setPassword('*******');
$config->setMailFrom('xx@163.com');
$config->setTimeout(10);// Set client connection timeout
$config->setMaxPackage(1024*1024*5);//Set the size of the package sent:5M
//Set text or html
$mimeBean = new Html();
$mimeBean->setSubject('Hello Word!');
$mimeBean->setBody('<h1>Hello Word</h1>');
//Add attachments
$mimeBean->addAttachment(Attach::create('./test.txt'));
$mailer = new Mailer($config);
$mailer->sendTo('xx@qq.com', $mimeBean);
});
```
|
Shell | UTF-8 | 3,502 | 3.3125 | 3 | [] | no_license | # This file processes the raw data in $PL_DATA and generates data files that
# we use to plot them in the imc13 paper. It lives in the pl-mapping git repo.
# The data files produced are then plotted using the gnuplot scripts in the
# paper repo.
# The files produced in the gen-data directory should be copied over to the
# paper repository.
# This script assumes that iffinder analysis has been run
export PL_DATA=/research/cogent_map/pl_archives
export IFFINDER=/research/cogent_map/iffinder-analysis
export PL_BIN=$HOME/work/projects/pl-mapping/analysis-scripts
mkdir gen-data
#File required by dns-results.gp
echo "Transposing summaries..."
./transpose-summaries.pl $PL_DATA > gen-data/summary-transpose.txt
#Files needed by iface_breakdown.gp
echo "Computing interfaces breakdown..."
$PL_BIN/generateInterfaceBreakdown.py $PL_DATA --allWeeks > gen-data/iface_breakdown.allweeks.dat
$PL_BIN/generateInterfaceBreakdown.py $PL_DATA --physical --allWeeks > gen-data/iface_breakdown.allweeks.physical.dat
$PL_BIN/generateInterfaceBreakdown.py $PL_DATA --virtual --allWeeks > gen-data/iface_breakdown.allweeks.virtual.dat
cat gen-data/iface_breakdown.allweeks.dat | ./fix_weeks_iface_breakdown.pl > gen-data/iface_breakdown.allweeks.fixed.dat
cat gen-data/iface_breakdown.allweeks.physical.dat | ./fix_weeks_iface_breakdown.pl > gen-data/iface_breakdown.allweeks.physical.fixed.dat
cat gen-data/iface_breakdown.allweeks.virtual.dat | ./fix_weeks_iface_breakdown.pl > gen-data/iface_breakdown.allweeks.virtual.fixed.dat
mv gen-data/iface_breakdown.allweeks.fixed.dat gen-data/iface_breakdown.allweeks.dat
mv gen-data/iface_breakdown.allweeks.physical.fixed.dat gen-data/iface_breakdown.allweeks.physical.dat
mv gen-data/iface_breakdown.allweeks.virtual.fixed.dat gen-data/iface_breakdown.allweeks.virtual.dat
#gnuplot iface_breakdown.gp
#Files needed by router_degrees.gp
echo "Gathering router degrees..."
$PL_BIN/generateRouterHistogram.py $IFFINDER $PL_DATA > gen-data/router_degrees.all.dat
$PL_BIN/generateRouterHistogram.py $IFFINDER $PL_DATA --physical > gen-data/router_degrees.physical.dat
$PL_BIN/generateRouterHistogram.py $IFFINDER $PL_DATA --virtual > gen-data/router_degrees.virtual.dat
echo "Cleaning up router degree data..."
#Remap weeks and remove weeks 9 and 10
cat gen-data/router_degrees.all.dat | ./fix_weeks_router_degrees.pl > gen-data/router_degrees.fixed.all.dat
cat gen-data/router_degrees.physical.dat | ./fix_weeks_router_degrees.pl > gen-data/router_degrees.fixed.physical.dat
cat gen-data/router_degrees.virtual.dat | ./fix_weeks_router_degrees.pl > gen-data/router_degrees.fixed.virtual.dat
#Compute the average degree for each week
cat gen-data/router_degrees.fixed.all.dat | perl compute_degree_averages.pl > gen-data/router_degrees.fixed.all.avg.dat
cat gen-data/router_degrees.fixed.physical.dat | perl compute_degree_averages.pl > gen-data/router_degrees.fixed.physical.avg.dat
cat gen-data/router_degrees.fixed.virtual.dat | perl compute_degree_averages.pl > gen-data/router_degrees.fixed.virtual.avg.dat
#Normalize the CDFs
./normalize.pl gen-data/router_degrees.fixed.all.dat
./normalize.pl gen-data/router_degrees.fixed.physical.dat
./normalize.pl gen-data/router_degrees.fixed.virtual.dat
#Getting number of routers per week
grep -n "Number of names found" $IFFINDER/*.stderr.txt | perl -ne 'chomp; ($w,$r) = $_ =~ /(\d+)\.stderr.*found:\s+(\d+)/; print "$w,$r\n"' | sort -n -k 1,1 > gen-data/number_of_routers_raw.csv
#gnuplot router_degrees.gp
|
Python | UTF-8 | 332 | 3.203125 | 3 | [] | no_license | from sys import stdin
def main():
str_rep = ["" for x in range(1002)]
str_rep[0] = "1"
fact = 1
for i in range (1, 1001):
fact *= i
str_rep[i] = str(fact)
for line in stdin:
q = int(line)
print("{0}!".format(q))
print(str_rep[q])
if __name__ == "__main__":
main()
|
Java | UTF-8 | 283 | 2.25 | 2 | [] | no_license | package MOS;
import Hardware.VirtualMachine;
/**
*
* @author ernestas
*/
public abstract class Service extends Process {
public Service(String name, ProcessState state) {
super(name, state);
}
public abstract void interrupt(Interrupt i);
}
|
C++ | UTF-8 | 5,782 | 2.734375 | 3 | [
"MIT"
] | permissive | /*************************************************************************
> File Name: Time_heap.h
> Author: Liu Shengxi
> Mail: 13689209566@163.com
> Created Time: 2019年01月22日 星期二 16时49分00秒
************************************************************************/
#include "MiniHeap.h"
#include <sys/timerfd.h>
#include <iostream>
#include <unistd.h>
#include <functional>
#include <assert.h>
#include <cstring>
namespace Tattoo
{
namespace detail
{
//创建 timerfd
int createTimerfd()
{
int timerfd = ::timerfd_create(CLOCK_MONOTONIC,
TFD_NONBLOCK | TFD_CLOEXEC);
if (timerfd < 0)
{
std::cout << "Failed in timerfd_create" << std::endl;
}
return timerfd;
}
/* 计算超时时间与当前时间的时间差,并将参数转换为 api 接受的类型 */
struct timespec howMuchTimeFromNow(Timestamp when)
{
/* 微秒数 = 超时时刻微秒数 - 当前时刻微秒数 */
int64_t microseconds = when.microSecondsSinceEpoch() - Timestamp::now().microSecondsSinceEpoch();
if (microseconds < 100)
{
microseconds = 100;
}
struct timespec ts; // 转换成 struct timespec 结构返回
// tv_sec 秒
// tv_nsec 纳秒
ts.tv_sec = static_cast<time_t>(
microseconds / Timestamp::kMicroSecondsPerSecond);
ts.tv_nsec = static_cast<long>(
(microseconds % Timestamp::kMicroSecondsPerSecond) * 1000);
return ts;
}
/* 读timerfd,避免定时器事件一直触发 */
void readTimerfd(int timerfd, Timestamp now)
{
uint64_t howmany;
ssize_t n = ::read(timerfd, &howmany, sizeof(howmany));
std::cout << "TimerQueue::handleRead() " << howmany << " at " << now.toString() << std::endl;
if (n != sizeof howmany)
{
std::cout << "TimerQueue::handleRead() reads " << n << " bytes instead of 8" << std::endl;
}
}
/* 重置 timerfd 的超时时间 */
void resetTimerfd(int timerfd, Timestamp expiration)
{
struct itimerspec newValue;
struct itimerspec oldValue;
bzero(&newValue, sizeof newValue);
bzero(&oldValue, sizeof oldValue);
newValue.it_value = howMuchTimeFromNow(expiration);
//到这个时间后,会产生一个定时事件
int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue);
if (ret)
{
std::cout << "timerfd_settime()" << std::endl;
}
}
} // namespace detail
} // namespace Tattoo
using namespace Tattoo;
using namespace Tattoo::detail;
Timer::Timer(Timestamp when)
: timer_rou_(get_curr_routine()), //一个定时器对应一个协程
expire_(when)
{
}
void Timer::run() const
{
cout << "由定时器唤醒对应协程" << endl;
timer_rou_->Resume();
}
TimeHeap::TimeHeap(EventLoop *loop)
: loop_(loop),
timerfd_(createTimerfd()),
timerfdChannel_(loop, timerfd_),
timers_()
{
// 设置自己独特的回调函数,并不是和普通的Channel 一样,直接唤醒了对应的协程
timerfdChannel_.setHandleCallback(
std::bind(&TimeHeap::handleRead, this));
timerfdChannel_.enableReading();
}
TimeHeap::~TimeHeap()
{
timerfdChannel_.disableAll();
::close(timerfd_);
for (auto it = timers_.begin();
it != timers_.end(); ++it)
{
delete it->second;
}
}
/* 添加一个定时器 ,返回定时器指针,会在 channel->addEpoll 函数中使用到,因为要删除对应的定时器*/
Timer *TimeHeap::addTimer(Timestamp when)
{
Timer *timer = new Timer(when);
////如果当前插入的定时器 比队列中的定时器都早 则返回真
bool earliestChanged = insert(timer);
//最早的超时时间改变了,就需要重置timerfd_的超时时间
if (earliestChanged)
{
//timerfd_ 重新设置超时时间,使得 timerfd 的定时事件始终是最小的
resetTimerfd(timerfd_, timer->expiration());
}
return timer;
}
/* 删除一个定时器 */
void TimeHeap::delTimer(Timer *timer)
{
auto it = timers_.find(timer->expire_);
if (it != timers_.end())
{
timers_.erase(it);
}
return;
}
//timerfd 可读 的回调
void TimeHeap::handleRead()
{
Timestamp now(Timestamp::now());
//先读取
readTimerfd(timerfd_, now);
std::vector<Entry> expired = getExpired(now);
for (std::vector<Entry>::iterator it = expired.begin();
it != expired.end(); ++it)
{
it->second->run(); //run->Resume()
}
reset(expired, now); //这里主要是改变 timerfd 的定时最小值
}
//获取所有超时的定时器
std::vector<TimeHeap::Entry> TimeHeap::getExpired(Timestamp now)
{
std::vector<Entry> expired;
auto it = timers_.lower_bound(now);
assert(it == timers_.end() || now < it->first);
std::copy(timers_.begin(), it, back_inserter(expired));
timers_.erase(timers_.begin(), it);
return expired;
}
void TimeHeap::reset(const std::vector<Entry> &expired, Timestamp now)
{
Timestamp nextExpire;
for (std::vector<Entry>::const_iterator it = expired.begin();
it != expired.end(); ++it)
{
delete it->second;
}
if (!timers_.empty()) //timers_ 不为空
{
/*获取当前定时器集合中的最早定时器的时间戳,作为下次超时时间*/
nextExpire = timers_.begin()->second->expiration();
}
//如果取得的时间 >0就改变 timerfd 的定时
if (nextExpire.valid())
{
resetTimerfd(timerfd_, nextExpire);
}
}
bool TimeHeap::insert(Timer *timer)
{
bool earliestChanged = false;
Timestamp when = timer->expiration();
auto it = timers_.begin();
if (it == timers_.end() || when < it->first)
{
earliestChanged = true;
}
timers_.insert(std::make_pair(when, timer));
return earliestChanged;
} |
Java | UTF-8 | 1,533 | 2.859375 | 3 | [] | no_license | package by.boika.electrical.model;
public class MediaCenter extends AbstractLocalAppliance {
private final String BEGIN_PLAY = "begin play";
private final String FINISH_PLAY = "finish play";
private final int FACTOR = 31;
private int maxVolume;
public MediaCenter() {
}
public int getMaxVolume() {
return maxVolume;
}
public AbstractElectricalAppliance setMaxVolume(int maxVolume) {
this.maxVolume = maxVolume;
return this;
}
@Override
public int hashCode() {
LOGGER.info("MC - " + getModel());
return FACTOR * getID() + getModel().hashCode() + maxVolume + getPower();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MediaCenter sample = (MediaCenter) obj;
if (getModel().equals(sample.getModel()))
return false;
if (getProducer().equals(sample.getProducer()))
return false;
if (getPower() != sample.getPower())
return false;
if (getVoltage() != sample.getVoltage())
return false;
return true;
}
@Override
public void switchOn() {
super.switchOn();
LOGGER.info(toString() + " " + BEGIN_PLAY);
}
@Override
public void switchOff() {
super.switchOff();
LOGGER.info(toString() + " " + FINISH_PLAY);
}
}
|
C++ | WINDOWS-1251 | 1,863 | 2.90625 | 3 | [
"MIT"
] | permissive | // Radiation Oncology Monte Carlo open source project
//
// Author: [2005-2017] Gennady Gorlachev (ggorlachev@roiss.ru)
//---------------------------------------------------------------------------
#pragma once
#include "mctransport.h"
// ,
//
class mcTransportCylinderStack : public mcTransport
{
public:
mcTransportCylinderStack();
mcTransportCylinderStack(const geomVector3D& orgn, const geomVector3D& z, const geomVector3D& x,
int nc, double dr, double ds, double h);
virtual ~mcTransportCylinderStack(void);
void setGeometry(int nc, double dr, double ds, double h);
int Nc() const { return nc_; }
double Dr() const { return dr_; }
double Ds() const { return ds_; }
double getHeight() const { return h_; }
void dump(ostream& os) const override;
void dumpVRML(ostream& os)const override;
protected:
double getDistanceInside(mcParticle& p) const override;
double getDistanceOutside(mcParticle& p) const override;
double getDNearInside(const geomVector3D& p) const override;
protected:
// ,
// .
//
int nc_;
//
double dr_;
//
// ds_ ;
// 2*ds_ ..
// dr_.
double ds_;
//
double h_;
};
|
Java | UTF-8 | 1,203 | 2.21875 | 2 | [] | no_license | package com.saurav.controller;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.saurav.dao.ModalDAO;
import com.saurav.modal.Modal;
@Controller
public class ControllerClass {
@Autowired
ModalDAO modalDAO;
@RequestMapping("/home")
public String ctrl(Model model) {
model.addAttribute("page", "home");
List<Modal> list = this.modalDAO.getAll();
model.addAttribute("empList", list);
return "home";
}
@RequestMapping("/add")
public String addList(Model model) {
Modal modal = new Modal();
model.addAttribute("page", "add");
model.addAttribute("modal", modal);
return "home";
}
@RequestMapping(value = "/saveForm", method = RequestMethod.POST)
public String saveForm(@ModelAttribute("modal") Modal modal, Model model) {
model.addAttribute("page", "home");
this.modalDAO.save(modal);
return "home";
}
}
|
SQL | UTF-8 | 887 | 3.578125 | 4 | [] | no_license | /*UPDATE admin SET comment=users.user_name+' - ' + users.phone
FROM users WHERE users.chat_id=admin.chat_id;*/
/*select *
from admin a
inner join users u
on a.chat_id = u.chat_id
where a.chat_id=u.chat_id;*/
/*
update admin
set a.comment = u.user_name + '- ' + u.phone
from admin a
inner join users u
on a.chat_id = u.chat_id
where a.chat_id = u.chat_id*/
/*SELECT
task.id AS id_task,
*
FROM task
INNER JOIN users ON task.tenant_id = users.chat_id
LEFT JOIN centres ON task.id_centres = centres.id
LEFT JOIN position ON task.id_position = position.id
LEFT JOIN status ON task.id_status = status.id
WHERE task.dataadd BETWEEN TO_TIMESTAMP('2018-03-06 00:0:00.000000000', 'YYYY-MM-DD HH24:MI:SS.FF') AND TO_TIMESTAMP(
'2018-04-08 00:0:00.000000000', 'YYYY-MM-DD HH24:MI:SS.FF') ORDER BY task.id*/
-- 2018-03-06 15:06:00.000000
-- 2018-04-08 15:06:00.000000 |
C | UTF-8 | 1,027 | 3.03125 | 3 | [] | no_license | /** @file usart1.h
@author Michael Hayes
@date 10 March 2005
@brief Routines for interfacing with the usart1 on an AT91 ARM
*/
#ifndef USART1_H
#define USART1_H
#include "config.h"
#define USART1_BAUD_DIVISOR(BAUD_RATE) ((F_CPU / 16) / (BAUD_RATE))
/* Return non-zero if there is a character ready to be read. */
bool
usart1_read_ready_p (void);
/* Read character from USART1. This blocks if nothing
is available to read. */
int
usart1_getc (void);
/* Return non-zero if a character can be written without blocking. */
bool
usart1_write_ready_p (void);
/* Return non-zero if transmitter finished. */
bool
usart1_write_finished_p (void);
/* Write character to USART1. This returns zero if
the character could not be written. */
int
usart1_putc (char ch);
/* Write string to USART1. */
int
usart1_puts (const char *str);
/* Initialise USART1 and set baud rate. */
int
usart1_init (uint16_t baud_divisor);
/* Shutdown USART1 in preparation for sleep. */
void
usart1_shutdown (void);
#endif
|
Java | UTF-8 | 202 | 1.929688 | 2 | [] | no_license | package fr.enssat.leave_manager.service.exception.not_found;
public class HRNotFoundException extends NotFoundException {
public HRNotFoundException(String msg) {
super("HR "+msg);
}
}
|
C++ | UTF-8 | 587 | 3.78125 | 4 | [] | no_license | /*
* initializer_lists.cpp
*
* Created on: 15 Mar 2021
* Author: Bowen Li
*/
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
class Test {
public:
Test(initializer_list<string> texts) {
for (auto value : texts) {
cout << value << endl;
}
}
void print(initializer_list<string> texts) {
for (auto value : texts) {
cout << value << endl;
}
}
};
int main() {
vector<int> numbers{1, 2, 3, 4, 5};
cout << numbers[2] << endl;
Test test{"apple", "orange", "banana"};
test.print({"one", "two", "three"});
return 0;
}
|
JavaScript | UTF-8 | 511 | 3.125 | 3 | [] | no_license | // var form = document.querySelector("form");
// var passwordCorrecto = ("gatitos123") ;
// form.onsubmit = function (evento) {
// evento.preventDefault();
// var password = document.getElementById("pass")
// if (password.value === passwordCorrecto) {
// } else {
// password.classList.add("error")
// }
// }
var checkboxes = document.getElementById("check");
var gato = checkboxes[0];
var perro = checkboxes[1];
console.log(gato.checked); //retorna true
|
JavaScript | UTF-8 | 3,463 | 2.78125 | 3 | [] | no_license | import './assets/toml.js'
export function read(text, position) {
const mappings = {
'_': '|',
'^': '|L10|R',
'$': '|M10|S',
'e': '|E6 ',
'B': '|B5 ',
'G': '|G5 ',
'D': '|D5 ',
'A': '|A4 ',
'E': '|E4 ',
'F': '|F5 ',
}
text = text.slice(0, position);
let note = parseInt(text.slice(-1), 36);
let string = getNote(mappings[text.split('|')[0]]);
return isNaN(note) ? null : note + string - 38;
}
export function getNote(string = '') {
var trimmed = string.trim();
var octave = Number(trimmed.slice(-1));
var note = trimmed.slice(1, -1);
console.log('getNote', {
string,
trimmed,
octave,
note,
})
return ([
'C', 'C#',
'D', 'D#',
'E',
'F', 'F#',
'G', 'G#',
'A', 'A#',
'B'
].indexOf(note) + 12 * octave);
}
export function getLine(value, { row }) {
console.log('getLine', { value, row })
return value.split('\n')[row]
}
export function getIndexes(value, position) {
console.log('getIndexes', { value, position })
// In case you are already at the end of the file
let line = getLine(value, position)
return line && line.split('|').map(s => s.length).join('|')
}
export function getPreviousSiblings(value, position, indexes = getIndexes(value, position)) {
let { row, column } = position;
row--;
return indexes === getIndexes(value, { row, column }) ? [...getPreviousSiblings(value, { row, column }, indexes), row] : []
}
export function getNextSiblings(value, position, indexes = getIndexes(value, position)) {
let { row, column } = position;
row++;
return indexes === getIndexes(value, { row, column }) ? [row, ...getPreviousSiblings(value, { row, column }, indexes)] : []
}
export function getFirstSibling(value, position, indexes = getIndexes(value, position)) {
let { row, column } = position;
return indexes === getIndexes(value, { row: row - 1, column }) ? getFirstSibling(value, { row: row - 1, column }, indexes) : row
}
export function getLastSibling(value, position, indexes = getIndexes(value, position)) {
let { row, column } = position;
console.log('getLastSibling', {
value, row, column, indexes
})
return indexes === getIndexes(value, { row: row + 1, column }) ? getLastSibling(value, { row: row + 1, column }, indexes) : row
}
export function getSiblings(value, position) {
return value
.split('\n')
.map((line, row) => row)
.slice(getFirstSibling(value, position), getLastSibling(value, position))
}
export function getPreviousRow(value, position) {
let { row, column } = position;
return value.split('\n')
.slice(row)
.map((line, row) => ({ line, row }))
.filter(({ line }) => line.match(/^(\|?[-\w]*)(\|[-\w]*\s{0,2})\s*#?/))[getSiblings(value, position).length].row
}
export function getNextRow(value, position) {
let { row, column } = position;
let regex = /^(\|?[-\w]*)(\|[-\w]*\s{0,2})\s*#?/;
console.log('getNextRow', { value, position })
return value.split('\n')
.slice(row)
.map((line, row) => ({ line, row }))
.filter(({ line }) => line.match(regex))[getSiblings(value, position).length].row + row + 1
}
export function getStartingRows(value) {
return [0, 1, 2, 3, 4, 5]
}
export const parse = toml.parse
export default {
parse,
getFirstSibling,
getIndexes,
getLastSibling,
getLine,
getNextRow,
getNextSiblings,
getNote,
getPreviousRow,
getPreviousSiblings,
getSiblings,
read
} |
Java | UTF-8 | 2,065 | 4.4375 | 4 | [
"MIT"
] | permissive | package com.tirthal.learning.concepts;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* Functions as First Class Citizen = The ability to store a function as a variable and pass that function as a parameter
*
* @author tirthalp
*
*/
public class FunctionAsFirstClassCitizensDemo {
public static void main(String[] args) {
// Example 1 - Assigning lambda expression as a function in a variable and calling directly from variable
BiFunction<String, String, String> concatFunction = (s1, s2) -> s1 + " " + s2;
System.out.println(concatFunction.apply("Hello", "World!"));
// Example 2 - Storing static method (which conforms method signature of BiFunction) in a variable and then invoking it
concatFunction = FunctionAsFirstClassCitizensDemo::concatStrings;
System.out.println(concatFunction.apply("Hello", "World!"));
// Example 3 - Storing instance method (which conforms method signature of BiFunction) in a variable and then invoking it
FunctionAsFirstClassCitizensDemo instance = new FunctionAsFirstClassCitizensDemo();
concatFunction = instance::concatStringsAnother;
System.out.println(concatFunction.apply("Hello", "World!"));
// Example 4 - Passing function as a parameter
// passing lambda directly
System.out.println(concatAndTransform("Hello", "World!", (s) -> s.toUpperCase()));
// passing from a variable
Function<String, String> transformToLower = (s) -> s.toLowerCase();
System.out.println(concatAndTransform("Hello", "World!", transformToLower));
}
// Static method
private static String concatStrings(String s1, String s2) {
return s1 + " " + s2;
}
// Instance method
String concatStringsAnother(String s1, String s2) {
return s1 + " " + s2;
}
// Method taking function as an input parameter
private static String concatAndTransform(String s1, String s2, Function<String, String> stringTransform) {
if(stringTransform != null) {
s1 = stringTransform.apply(s1);
s2 = stringTransform.apply(s2);
}
return s1 + " " + s2;
}
}
|
Python | UTF-8 | 5,046 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 10:56:10 2019
@author: yifan.gong
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.ticker as mtick
import matplotlib.dates as mdate
import datetime
#使用Df数据,计算净值PnL图数据
def Asset_to_list_Df(Df,asset = 100000000):
datelist = [key for key in Df.keys()]
Asset1 = [v['Asset']/asset for v in Df.values()]
return datelist,Asset1
#使用Df数据,计算收益率(加算)图数据
def Assetpct_to_list_Df(Df,asset = 100000000):
datelist = [key for key in Df.keys()]
temp1 = [v['Assetpct'] for v in Df.values()]
Assetpct1 = [1+sum(temp1[:i]) for i in range(len(temp1))]
return datelist,Assetpct1
def plot_Exceed_Df(Df,DfAll,title = 'fig'):
datelist,AssetpctAll = Assetpct_to_list_Df(DfAll)
fig1 = plt.figure(figsize = (16,9),dpi = 200)
ax1 = fig1.add_subplot(111)
Assetpct = []
Aex = []
Ex = []
for i in range(len(Df)):
Assetpct.append(0)
Aex.append(0)
Ex.append(0)
_,Assetpct[i] = Assetpct_to_list_Df(Df[i])
Aex[i] = [Assetpct[i][j]- AssetpctAll[j] for j in range(len(AssetpctAll))]
Ex[i] = ax1.plot(datelist[:],Aex[i][:],label = '第'+str(i+1)+'组')
ax1.legend(loc="best")
ax1.set_title(title,fontsize=16)
xt = np.arange(0,int(len(datelist)/10)*10,int(len(datelist)/100)*4)
xtick = [datelist[x] for x in xt]
ax1.set_xticks(xtick)
plt.xticks(rotation = 45)
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)
plt.legend(fontsize = 15)
return fig1
def plot_PnL_Df(Df,DfAll,title = 'fig'):
datelist,AssetAll = Asset_to_list_Df(DfAll)
fig1 = plt.figure(figsize = (16,9),dpi = 200)
ax1 = fig1.add_subplot(111)
Asset = []
Aex = []
Ex = []
for i in range(len(Df)):
Asset.append(0)
Aex.append(0)
Ex.append(0)
_,Asset[i] = Asset_to_list_Df(Df[i])
Aex[i] = [Asset[i][j] for j in range(len(AssetAll))]
Ex[i] = ax1.plot(datelist[:],Aex[i][:],label = '第'+str(i+1)+'组')
ax1.legend(loc="best")
ax1.set_title(title,fontsize=16)
xt = np.arange(0,int(len(datelist)/10)*10,int(len(datelist)/100)*4)
xtick = [datelist[x] for x in xt]
ax1.set_xticks(xtick)
plt.xticks(rotation = 45)
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)
plt.legend(fontsize = 15)
return fig1
#%%
#使用Nv数据,计算净值PnL图数据
def Asset_to_list_Nv(Nv,asset = 100000000):
datelist = [key for key in Nv.keys()]
Asset1 = [v/asset for v in Nv.values()]
return datelist,Asset1
#使用Nv数据,计算收益率(加算)图数据
def Assetpct_to_list_Nv(Nv,asset = 100000000):
datelist = [key for key in Nv.keys()]
values = list(Nv.values())
temp1 = [0]
for i in range(len(values)-1):
temp1.append(values[i+1]/values[i]-1)
Assetpct1 = [1+sum(temp1[:i]) for i in range(len(temp1))]
return datelist,Assetpct1
def plot_Exceed_Nv(Nv,NvAll,title = 'fig'):
datelist,AssetpctAll = Assetpct_to_list_Nv(NvAll)
fig1 = plt.figure(figsize = (16,9),dpi = 200)
ax1 = fig1.add_subplot(111)
Assetpct = []
Aex = []
Ex = []
for i in range(len(Nv)):
Assetpct.append(0)
Aex.append(0)
Ex.append(0)
_,Assetpct[i] = Assetpct_to_list_Nv(Nv[i])
Aex[i] = [Assetpct[i][j]- AssetpctAll[j] for j in range(len(AssetpctAll))]
Ex[i] = ax1.plot(datelist[:],Aex[i][:],label = '第'+str(i+1)+'组')
ax1.legend(loc="best")
ax1.set_title(title,fontsize=16)
xt = np.arange(0,int(len(datelist)/10)*10,int(len(datelist)/100)*4)
xtick = [datelist[x] for x in xt]
ax1.set_xticks(xtick)
plt.xticks(rotation = 45)
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)
plt.legend(fontsize = 15)
return fig1
def plot_PnL_Nv(Nv,NvAll,title = 'fig'):
datelist,AssetAll = Asset_to_list_Nv(NvAll)
fig1 = plt.figure(figsize = (16,9),dpi = 200)
ax1 = fig1.add_subplot(111)
Asset = []
Aex = []
Ex = []
for i in range(len(Nv)):
Asset.append(0)
Aex.append(0)
Ex.append(0)
_,Asset[i] = Asset_to_list_Nv(Nv[i])
Aex[i] = [Asset[i][j] for j in range(len(AssetAll))]
Ex[i] = ax1.plot(datelist[:],Aex[i][:],label = '第'+str(i+1)+'组')
ax1.legend(loc="best")
ax1.set_title(title,fontsize=16)
xt = np.arange(0,int(len(datelist)/10)*10,int(len(datelist)/100)*4)
xtick = [datelist[x] for x in xt]
ax1.set_xticks(xtick)
plt.xticks(rotation = 45)
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)
plt.legend(fontsize = 15)
return fig1
#%%
if __name__ == '__main__':
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
fig1 = plot_PnL_Df(Dfprofit,DfAll,title = '市值——PnL')
fig1.savefig('temp.png')
|
PHP | UTF-8 | 6,794 | 2.515625 | 3 | [] | no_license | <?php
namespace app\models\member;
use app\models\accounting\FeeCalendar;
use app\modules\admin\models\FeeType;
use Yii;
use yii\base\Model;
use yii\base\InvalidConfigException;
use app\components\utilities\OpDate;
use app\models\accounting\Assessment;
use app\models\accounting\BaseAllocation;
/**
* Model class for determining the financial status of a member
*
* Requires the injection of a Member
*/
class Standing extends Model
{
/**
* @var OpDate
*/
private $_today;
/**
* @var OpDate
*/
private $_currentMonthEnd;
/**
* @var Member
*/
public $member;
// Can inject for testing
public $lob_cd;
public $rate_class;
/**
* @var boolean When true, standing calculations will be based on APF only
*/
public $apf_only;
/**
* @throws InvalidConfigException
*/
public function init()
{
if(!(isset($this->member) && ($this->member instanceof Member)))
throw new InvalidConfigException('No member object injected');
$this->lob_cd = isset($this->member->currentStatus) ? $this->member->currentStatus->lob_cd : null;
$this->rate_class = isset($this->member->currentClass) ? $this->member->currentClass->rate_class : 'R';
}
/**
* Determines number of dues months owed by member. If paid thru is future, then returns zero.
*
* @return number
*/
public function getMonthsToCurrent()
{
$start_dt = clone $this->member->duesPaidThruDtObject;
$obligation_dt = $this->getDuesObligation();
return $this->calcMonths($start_dt, $obligation_dt);
}
/**
* Compute discounted months for granted in service card
*
* @return number
*/
public function getDiscountedMonths()
{
$months = 0;
$status = $this->member->inServicePeriod;
if (isset($status)) {
$start_dt = ($status->effective_dt > $this->member->dues_paid_thru_dt) ? $status->effective_dt : $this->member->dues_paid_thru_dt;
$start_dt_obj = (new OpDate)->setFromMySql($start_dt);
$end_dt_obj = ($status->end_dt === null) ? $this->getDuesObligation() : (new OpDate)->setFromMySql($status->end_dt);
$months = $this->calcMonths($start_dt_obj, $end_dt_obj);
}
return $months;
}
/**
* Returns owed dues period into a date range
*
* @return string
\ */
public function getBillingDescrip()
{
$obligation_dt = $this->getDuesObligation();
$cr = ' - ';
switch ($this->getMonthsToCurrent()) {
case 0:
$paid_thru_dt = $this->member->duesPaidThruDtObject;
$descrip = 'Paid thru ' . $paid_thru_dt->getMonthName(true) . ' ' . $paid_thru_dt->getYear();
$cr = ' + ';
break;
case 1:
$descrip = $obligation_dt->getMonthName(true);
break;
default:
$start_dt = clone $this->member->duesPaidThruDtObject;
$start_dt->modify('+1 month');
$descrip = $start_dt->getMonthName(true) . '-' . $obligation_dt->getMonthName(true) . ' (' . $this->getMonthsToCurrent() . ' months)';
}
if($this->member->overage > 0.00)
$descrip .= $cr . 'Credit ' . number_format($this->member->overage, 2);
if ($this->getOutStandingAssessment(FeeType::TYPE_INIT))
$descrip .= ' + Init Fee';
return $descrip;
}
/**
* Returns total outstanding dues owed. If paid thru is future, returns 0.00
*
* @return false|float|string|null
*/
public function getDuesBalance()
{
$obligation_dt = $this->getDuesObligation();
$adjusted_pt_dt = clone $this->member->duesPaidThruDtObject;
$adjusted_pt_dt->modify('+' . $this->getDiscountedMonths() . ' month');
return isset($this->lob_cd) && isset($this->rate_class) && ($obligation_dt > $this->member->duesPaidThruDtObject)
? FeeCalendar::getTrueDuesBalance($this->lob_cd, $this->rate_class, $adjusted_pt_dt->getMySqlDate(), null, $obligation_dt) : 0.00;
}
/**
* Returns the first matching Assessment of fee type that has a balance, null if none
*
* @param $fee_type
* @return Assessment|null
*/
public function getOutstandingAssessment($fee_type)
{
$assessments = Assessment::findAll(['member_id' => $this->member->member_id, 'fee_type' => $fee_type]);
foreach ($assessments as $assessment) {
if ($assessment->balance <> 0)
return $assessment;
}
return null;
}
public function getTotalAssessmentBalance()
{
$sql = "SELECT SUM(assessment_amt) FROM Assessments AS A WHERE member_id = :id";
$assessments = Assessment::findBySql($sql, ['id' => $this->member->member_id])->scalar();
$sql = <<<SQL
select COALESCE (SUM(allocation_amt), 0.00) AS alloc
from Allocations AS Al
join Assessments AS A ON A.id = Al.assessment_id
where member_id = :id;
SQL;
$allocs = BaseAllocation::findBySql($sql, ['id' => $this->member->member_id])->scalar();
return bcsub($assessments, $allocs, 2);
}
/**
* Today's date is current based on injected Member object
*
* @returns OpDate
*/
private function getToday()
{
if(!isset($this->_today)) {
$this->_today = $this->member->today;
}
return $this->_today;
}
/**
* Returns the last day of the current month
*
* @return OpDate
*/
private function getCurrentMonthEnd()
{
if(!isset($this->_currentMonthEnd)) {
$this->_currentMonthEnd = $this->getToday();
$this->_currentMonthEnd->setToMonthEnd();
}
return $this->_currentMonthEnd;
}
/**
* Returns the date dues must be paid thru to meet obligation.
*
* If member, is in application, this date is determined by adding the APF dues months to the current application
* date. Otherwise, the current month end is used.
*
* @return OpDate
* @see Member::getDuesStartDt
*/
private function getDuesObligation()
{
$monthend_dt = $this->getCurrentMonthEnd();
if ($this->member->isInApplication()) {
$apf = $this->member->currentApf;
if (isset($apf)) {
$obligation_dt = $this->member->getDuesStartDt();
$obligation_dt->modify('+' . $apf->months . ' month');
if (!($this->apf_only) && (OpDate::dateDiff($obligation_dt, $monthend_dt) > 0))
$obligation_dt = $monthend_dt;
} else {
Yii::warning("Member `{$this->member->member_id}` is in application but does not have a current APF Assessment.");
$obligation_dt = $monthend_dt;
}
} else {
$obligation_dt = $monthend_dt;
}
return $obligation_dt;
}
/**
* Difference in months between 2 date objects
*
* @param OpDate $start
* @param OpDate $end
* @return number
*/
private function calcMonths(OpDate $start, OpDate $end)
{
$i = 0;
while ($start->getYearMonth() < $end->getYearMonth()) {
$i++;
$start->modify('+1 month');
$start->setToMonthEnd();
}
return $i;
}
}
|
Java | UTF-8 | 6,919 | 2.1875 | 2 | [] | no_license | package com.towcent.base.common.model;
import java.util.List;
import java.util.Map;
/**
* 权限验证参数
*
*/
public class AuthorityParams {
/**
* 用户编号
*/
private String userId;
/**
* 是否验证
*/
private boolean verification;
/**
* 品牌编码
*/
private String brandNoVerify;
/**
* 系统编码
*/
private String systemNoVerify;
/**
* 区域系统编码
*/
private String areaSystemNoVerify;
/**
* 品牌编码参数列表
*/
private String[] brandNoList;
/**
* 用户拥有品牌列表
*/
private List<String> hasBrandNoList;
/**
* 地区
*/
private String areaVerify;
/**
* 地区列表
*/
private String[] areaList;
/**
* 用户拥有地区列表
*/
private List<String> hasAreaList;
/**
* 城市中心
*/
private String cityCenterVerify;
/**
* 城市中心列表
*/
private String[] cityCenterList;
/**
* 用户拥有的地区列表
*/
private List<String> hasCityCenterList;
/**
* 仓库
*/
private String storeVerify;
/**
* 仓库列表
*/
private String[] storeList;
/**
* 用户拥有的仓库列表
*/
private List<String> hasStoreList;
/**
* 门店
*/
private String shopVerify;
/**
* 门店列表
*/
private String[] shopList;
/**
* 用户拥有的门店列表
*/
private List<String> hasShopList;
/**
* 权限查询参数
*/
private Map<String,List<String>> queryParams;
/**
* {@linkplain #userId}
* @return
*/
public String getUserId() {
return userId;
}
/**
* {@linkplain #userId}
* @param userId
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* {@linkplain #brandNoVerify}
* @return
*/
public String getBrandNoVerify() {
return brandNoVerify;
}
/**
* {@linkplain #brandNoVerify}
* @param brandNoVerify
*/
public void setBrandNoVerify(String brandNoVerify) {
this.brandNoVerify = brandNoVerify;
}
/**
* {@linkplain #areaVerify}
* @return
*/
public String getAreaVerify() {
return areaVerify;
}
/**
* {@linkplain #areaVerify}
* @param areaVerify
*/
public void setAreaVerify(String areaVerify) {
this.areaVerify = areaVerify;
}
/**
* {@linkplain #cityCenterVerify}
* @return
*/
public String getCityCenterVerify() {
return cityCenterVerify;
}
/**
* {@linkplain #cityCenterVerify}
* @param cityCenterVerify
*/
public void setCityCenterVerify(String cityCenterVerify) {
this.cityCenterVerify = cityCenterVerify;
}
/**
* {@linkplain #storeVerify}
* @return
*/
public String getStoreVerify() {
return storeVerify;
}
/**
*
* @param storeVerify {@linkplain #storeVerify}
*/
public void setStoreVerify(String storeVerify) {
this.storeVerify = storeVerify;
}
/**
* {@linkplain #shopVerify}
* @return
*/
public String getShopVerify() {
return shopVerify;
}
/**
*
* @param shopVerify {@linkplain #shopVerify}
*/
public void setShopVerify(String shopVerify) {
this.shopVerify = shopVerify;
}
/**
* {@linkplain #brandNoList}
* @return
*/
public String[] getBrandNoList() {
return brandNoList;
}
/**
* {@linkplain #brandNoList}
* @param brandNoList
*/
public void setBrandNoList(String[] brandNoList) {
this.brandNoList = brandNoList;
}
/**
* {@linkplain #hasBrandNoList}
* @return
*/
public List<String> getHasBrandNoList() {
return hasBrandNoList;
}
/**
* {@linkplain #hasBrandNoList}
* @param hasBrandNoList
*/
public void setHasBrandNoList(List<String> hasBrandNoList) {
this.hasBrandNoList = hasBrandNoList;
}
/**
* {@linkplain #areaList}
* @return
*/
public String[] getAreaList() {
return areaList;
}
/**
* {@linkplain #areaList}
* @param areaList
*/
public void setAreaList(String[] areaList) {
this.areaList = areaList;
}
/**
* {@linkplain #shopList}
* @return
*/
public String[] getCityCenterList() {
return cityCenterList;
}
/**
* {@linkplain #shopList}
* @param cityCenterList
*/
public void setCityCenterList(String[] cityCenterList) {
this.cityCenterList = cityCenterList;
}
/**
* {@linkplain #hasAreaList}
* @return
*/
public List<String> getHasAreaList() {
return hasAreaList;
}
/**
* {@linkplain #hasAreaList}
* @param hasAreaList
*/
public void setHasAreaList(List<String> hasAreaList) {
this.hasAreaList = hasAreaList;
}
/**
* {@linkplain #hasCityCenterList}
* @return
*/
public List<String> getHasCityCenterList() {
return hasCityCenterList;
}
/**
* {@linkplain #hasCityCenterList}
* @param hasCityCenterList
*/
public void setHasCityCenterList(List<String> hasCityCenterList) {
this.hasCityCenterList = hasCityCenterList;
}
/**
* {@linkplain #shopList}
* @return
*/
public String[] getStoreList() {
return storeList;
}
/**
* {@linkplain #shopList}
* @param storeList
*/
public void setStoreList(String[] storeList) {
this.storeList = storeList;
}
/**
* {@linkplain #hasStoreList}
* @return
*/
public List<String> getHasStoreList() {
return hasStoreList;
}
/**
* {@linkplain #hasStoreList}
* @param hasStoreList
*/
public void setHasStoreList(List<String> hasStoreList) {
this.hasStoreList = hasStoreList;
}
/**
* {@linkplain #shopList}
* @return
*/
public String[] getShopList() {
return shopList;
}
/**
* {@linkplain #shopList}
* @param shop
*/
public void setShopList(String[] shopList) {
this.shopList = shopList;
}
/**
* {@linkplain #hasShopList}
* @return
*/
public List<String> getHasShopList() {
return hasShopList;
}
/**
* {@linkplain #hasShopList}
* @param hasShopList
*/
public void setHasShopList(List<String> hasShopList) {
this.hasShopList = hasShopList;
}
/**
* {@linkplain #verification}
* @return
*/
public boolean isVerification() {
return verification;
}
/**
* {@linkplain #verification}
* @param verification
*/
public void setVerification(boolean verification) {
this.verification = verification;
}
/**
* {@linkplain #queryParams}
* @return
*/
public Map<String, List<String>> getQueryParams() {
return queryParams;
}
/**
* {@linkplain #queryParams}
* @param queryParams
*/
public void setQueryParams(Map<String, List<String>> queryParams) {
this.queryParams = queryParams;
}
/**
* {@link #systemNoVerify}
* @return
*/
public String getSystemNoVerify() {
return systemNoVerify;
}
/**
* {@link #systemNoVerify}
* @param systemNoVerify
*/
public void setSystemNoVerify(String systemNoVerify) {
this.systemNoVerify = systemNoVerify;
}
/**
* {@link #areaSystemNoVerify}
* @return
*/
public String getAreaSystemNoVerify() {
return areaSystemNoVerify;
}
/**
* {@link #areaSystemNoVerify}
* @param areaSystemNoVerify
*/
public void setAreaSystemNoVerify(String areaSystemNoVerify) {
this.areaSystemNoVerify = areaSystemNoVerify;
}
}
|
JavaScript | UTF-8 | 1,113 | 3.125 | 3 | [] | no_license | import { createStore } from "../192.arrays";
describe("Arrays Test", () => {
test("Arrays Add Fruit", () => {
const store = createStore();
store.addFruit("Apple");
expect(store.getFruits()).toStrictEqual(["Apple"]);
});
test("Arrays Add 2 Fruit", () => {
const store = createStore();
store.addFruit("Apple");
store.addFruit("Mango");
expect(store.getFruits()).toStrictEqual(["Apple", "Mango"]);
});
test("Arrays Contains Expecific Fruit", () => {
const store = createStore();
store.addFruit("Orange");
store.addFruit("Pineapple");
expect(store.getFruits()).toContain("Pineapple");
expect(store.getFruits()).not.toContain("Apple");
});
test("Arrays length Fruit", () => {
const store = createStore();
store.addFruit("Orange");
store.addFruit("Pineapple");
expect(store.getFruits()).toHaveLength(2);
});
test("Arrays Adding Fruit object", () => {
const store = createStore();
store.addFruit({ name: "Orange", price: 10 });
expect(store.getFruits()).toContainEqual({ name: "Orange", price: 10 });
});
});
|
Python | UTF-8 | 1,044 | 2.984375 | 3 | [] | no_license | INF=float("inf")
#入力
n=5
d=[[INF for _ in range(n)] for _ in range(n)]
n=5
d=[[INF,3,INF,4,INF],[INF,INF,5,INF,INF],[4,INF,INF,5,INF],[INF,INF,INF,INF,3],[7,6,INF,INF,INF]]
#DP
dp=[[-1 for _ in range(n)] for _ in range(2**n)]
#経路
route="0"
def rec(S,v,r):
if(dp[S][v] >= 0):
return dp[S][v],r
if(S == 2**n - 1 and v == 0):
#全ての頂点を訪れて戻ってきた
dp[S][v] = 0
return dp[S][v],r
res = INF
ans_route=r
for u in range(n):
#uがまだ訪れてない? -> Sの2^u桁目が0
if d[v][u] != INF and (not (S >> u & 1)):
#次にuに移動する
res_u,res_route=rec(S | 1 << u , u , r+" -> "+str(u))
#uに移動した結果の重みが小さいならばその結果を保存する
if(res>res_u + d[v][u]):
res=res_u + d[v][u]
ans_route=res_route
dp[S][v] = res
return dp[S][v],ans_route
ans,route=rec(0,0,route)
print("答:{0},経路:{1}".format(ans,route)) |
Python | UTF-8 | 1,079 | 3.46875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
def hasNoX_2(s):
if type(s)!=str:
return False
for c in s:
if c!='x' or c!='X':
return True
return False
def hasNoX_3(s):
if type(s)!=str:
return False
for c in s:
if c=='x' or c=='X':
return False
return True
def hasNoX_4(s):
if type(s)!=str:
return False
for c in s:
if c!='x' and c!='X':
return True
else:
return False
def hasNoX_5(s):
if s!=str:
return False
for c in s:
if c=='x' or c=='X':
return False
return True
def hasNoX_6(s):
if type(s)!=str:
return False
for c in s:
if c=='x' or c=='X':
return True
return False
if __name__=="__main__":
values = ["Fox","Xie","Axe","Pat",12345]
functions = [
hasNoX_2,
hasNoX_3,
hasNoX_4,
hasNoX_5,
hasNoX_6]
for f in functions:
print("")
for v in values:
print("{}({})={}".format(f.__name__,repr(v),repr(f(v))))
|
Java | UTF-8 | 6,007 | 2.171875 | 2 | [] | no_license | package controllers;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import models.activity.Activity;
import models.charity.Wel;
import models.index.Index;
import models.index.SolrContent;
import models.index.IndexStore;
import models.qa.Paging;
import models.qa.Ques;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
public class IndexController extends Application {
/**
* 重构索引
*/
public static void updateReconstructorIndex() {
try {
SolrContent.getInstance().getServer().deleteByQuery("*:*");
List<Activity> activity = Activity.findAll();// 活动
List<Ques> ques = Ques.findAll();// 问答
List<Wel> wel = Wel.findAll();// 公益
// 判断活动是否过期先获取系统当前时间
String startDate = new SimpleDateFormat("yyyy-MM-dd")
.format(Calendar.getInstance().getTime());
List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
for (Activity a : activity) {
if (a.time.get(0).date.compareTo(startDate) == 1) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "1" + a.id);
doc.addField("msg_id", a.id);
doc.addField(
"msg_name",
a.publisherSU == null ? (a.publisherCSSA.school.name + " CSSA")
: a.publisherSU.name);
doc.addField("msg_title", a.name);
doc.addField("msg_content", a.intro);
doc.addField("msg_date", a.postAt);
doc.addField("msg_join", a.joiner.size());
doc.addField("msg_attention", a.liker.size());
doc.addField("msg_type", "1");
docs.add(doc);
}
}
for (Ques q : ques) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "2" + q.id);
doc.addField("msg_id", q.id);
doc.addField("msg_name", q.username);
doc.addField("msg_title", q.title);
doc.addField("msg_content", q.content);
doc.addField("msg_date", q.date);
doc.addField("msg_join", q.answerNum);
doc.addField("msg_attention", q.focusNum);
doc.addField("msg_type", "2");
docs.add(doc);
}
for (Wel w : wel) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "3" + w.id);
doc.addField("msg_id", w.id);
doc.addField("msg_name", w.fromUser);
doc.addField("msg_title", w.title);
doc.addField("msg_content", w.content);
doc.addField("msg_date", w.time);
doc.addField("msg_join", w.likerCount);
doc.addField("msg_attention", w.views);
doc.addField("msg_type", "3");
docs.add(doc);
}
SolrContent.getInstance().getServer().add(docs);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查询
* @param condition 需要查询的内容
* @param model 要搜索的域
* @param currentPage 显示的页
*/
public static void findByModel(String condition, int model, int currentPage) {
boolean contentIsEmpty = false;
String sign = null;
long pageCount = 0;
if (model == 0) {
sign = "all";
} else if (model == 1) {// "1" 代表活动
sign = "Activity";
} else if (model == 2) {// "2" 代表问答
sign = "QA";
} else if (model == 3) {// "3" 代表公益
sign = "Wel";
}
List<Index> datas = new ArrayList<Index>();
try {
if(condition.equals("")||currentPage<=0){
contentIsEmpty=true;
}else{
// 定义分页,每次显示十条数据
int pageSize = 10;
// 通过currPage和pageSize计算出开始,在solr里面不需要加1
int start = (currentPage - 1) * pageSize;
//把condition按照空格进行拆分
String [] string = condition.split(" ");
String conString = "";
for (int i = 0; i < string.length; i++) {
conString += string[i];
}
SolrQuery query = new SolrQuery();
if (model == 0) {
query.set("q", "msg_all:" + conString);
} else {
query.set("q", "msg_type:" + model + " AND msg_all:"
+ conString);
}
query.setHighlight(true)
.setHighlightSimplePre("<span style='color:red'>")
.setHighlightSimplePost("</span>").setStart(start)
.setRows(pageSize);
query.setParam("hl.fl", "msg_title,msg_content");
QueryResponse resp = SolrContent.getInstance().getServer()
.query(query);
SolrDocumentList sdl = resp.getResults();
if (sdl.getNumFound()>0) {
for (SolrDocument sd : sdl) {
String id = (String) sd.getFieldValue("id");
Index index = new Index();
index.setId(id);
index.setTitle(sd.getFieldValue("msg_title").toString());
index.setSummary(sd.getFieldValue("msg_content")
.toString());
index.setFrom(sd.getFieldValue("msg_name").toString());
index.setCreateDate(sd.getFieldValue("msg_date")
.toString());
index.setAttention((int) sd
.getFieldValue("msg_attention"));
index.setJoin((int) sd.getFieldValue("msg_join"));
index.setType((String) sd.getFieldValue("msg_type"));
if (resp.getHighlighting().get(id) != null) {
List<String> htitle = resp.getHighlighting()
.get(id).get("msg_title");
if (htitle != null)
index.setTitle(htitle.get(0));
List<String> hcontent = resp.getHighlighting()
.get(id).get("msg_content");
if (hcontent != null)
index.setSummary(hcontent.get(0));
}
datas.add(index);
contentIsEmpty = false;
pageCount = sdl.getNumFound() % pageSize == 0 ? sdl
.getNumFound() / pageSize : (sdl.getNumFound()
/ pageSize + 1);
}
}else{
contentIsEmpty=true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
int[] inter = Paging.getRount(8, (int) pageCount, currentPage);
renderTemplate("Index/indexSearch.html", sign, datas, condition, inter,model,
currentPage, pageCount, contentIsEmpty);
}
}
|
Shell | UTF-8 | 998 | 3.59375 | 4 | [] | no_license | #!/bin/bash
usage() {
echo "This won't clean anything, it will use whatever is in the cmdstan submodule even if it's dirty."
echo "Pass the arguments to runPerformanceTests.py in quotes as the first argument."
echo "Pass the alternative compiler binary path as the second argument."
}
if [ -z "$1" ] || [ -z "$2" ] ; then
usage
exit
fi
set -e -x
# run develop version of cmdstan with the nightly stanc3 binary
cd cmdstan; make clean-all; make -j4 build; make -j4 examples/bernoulli/bernoulli; ./bin/stanc --version; cd ..
./runPerformanceTests.py --overwrite-golds $1
for i in performance.*; do
mv $i "reference_${i}"
done
# run develop version of cmdstan with the stanc3 binary at the provided path
cd cmdstan; make clean-all; make -j4 build; cd ..
rm cmdstan/bin/stanc
cp "$2" cmdstan/bin/stanc
cmdstan/bin/stanc --version
./runPerformanceTests.py --check-golds-exact 1e-8 $1 --scorch-earth && ./comparePerformance.py "reference_performance.csv" performance.csv csv
|
TypeScript | UTF-8 | 439 | 2.953125 | 3 | [
"MIT"
] | permissive | interface UploadedFile {
path: string;
}
type onProgress = (percent: number) => void;
interface RenderProps {
path: string
uploading: boolean
progress: number
}
export interface UploaderProps {
id: string
children: (props: RenderProps) => React.ReactNode
uploadFile: (file: File, onProgress?: onProgress) => Promise<UploadedFile>
onError: (err: Error) => void
initialPath?: string
onUploaded?: (url: string) => void
}
|
Swift | UTF-8 | 2,571 | 2.953125 | 3 | [] | no_license | //
// PersonalScheduleService.swift
// ulink
//
// Created by 양시연 on 2020/07/16.
// Copyright © 2020 송지훈. All rights reserved.
//
import Alamofire
import Foundation
import SwiftyJSON
struct PersonalScheduleService {
private init() { }
static let shared = PersonalScheduleService()
private func makeParameter(_ list : [PersonalScheduleModel]) -> Parameters {
// struct를 json으로 바꾼다
var resultList = [String]()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
var parameter: String = ""
for(index, value) in list.enumerated(){
let key = "schedule[\(index)]"
var dicdic = value
let jsonData = try? encoder.encode(dicdic)
if let jsonString = String(data: jsonData!, encoding: .utf8) {
parameter = String(jsonString.filter { !" \n\t\r".contains($0) })
}
resultList.append(parameter)
}
// var json: JSON = JSON([“schedule” : parameter])
return ["scheduleList" : resultList]
}
let header: HTTPHeaders = [
"Content-Type" : "application/json",
"token" : UserDefaults.standard.object(forKey: "token") as! String
]
func postPersonalScheudule(personalScheudleList: [PersonalScheduleModel], completion: @escaping (NetworkResult<Any>) -> Void) {
print("hello1")
Alamofire.request(APIConstants.personalSchedule, method : .post, parameters: makeParameter(personalScheudleList), encoding: JSONEncoding.default, headers: header).responseJSON {
response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else { return }
guard let value = response.result.value else { return }
let json = JSON(value)
let networkResult = self.judge(by: statusCode, json)
completion(networkResult)
case .failure:
print("hello3")
completion(.networkFail)
}
}
}
private func judge(by statusCode: Int, _ json: JSON) -> NetworkResult<Any> {
print("status", statusCode)
switch statusCode {
case 200: return .success(0, 0)
case 201: return .success(0, 0)
case 400: return .pathErr
case 500: return .serverErr
default: return .networkFail
}
}
}
|
Java | UTF-8 | 1,471 | 2.3125 | 2 | [] | no_license | package com.ds.po;
public class AGPullRecordPO {
private Long id;
private String agPath;
private String datePath;
private String filename;
private long lastUpdateTime;
private String fileSize;
public AGPullRecordPO() {
super();
}
/**
*
* @param agPath
* @param datePath
* @param filename
* @param lastUpdateTime
* @param fileSize
*/
public AGPullRecordPO(String agPath, String datePath, String filename, long lastUpdateTime, String fileSize) {
super();
this.agPath = agPath;
this.datePath = datePath;
this.filename = filename;
this.lastUpdateTime = lastUpdateTime;
this.fileSize = fileSize;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAgPath() {
return agPath;
}
public void setAgPath(String agPath) {
this.agPath = agPath;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getDatePath() {
return datePath;
}
public void setDatePath(String datePath) {
this.datePath = datePath;
}
public long getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(long lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public String getUniqueKey() {
return agPath + datePath + filename;
}
}
|
Java | UTF-8 | 3,617 | 2.3125 | 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 Controllers;
import Models.Clubes;
import diastrabalhofinal.InteracaoBD;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* @author André Marques
*/
public class ConsultarClubesController implements Initializable {
TableView<Clubes> TabelaClubes;
@FXML
private AnchorPane PainelClubes;
@FXML
private TextField txtCodClube;
@FXML
private TextField txtNomeClube;
private InteracaoBD conexao = new InteracaoBD();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
TabelaClubes = listarClubesTabela(conexao.getClubes(20));
} catch (SQLException ex) {
Logger.getLogger(ConsultarJogoController.class.getName()).log(Level.SEVERE, null, ex);
}
PainelClubes.getChildren().add(TabelaClubes);
}
public void abrirJanela(String caminho, ActionEvent event1) throws IOException {
FXMLLoader fxml = new FXMLLoader(getClass().getResource(caminho));
Parent root = (Parent) fxml.load();
Stage stage = new Stage();
stage.setTitle("Rato-Esquilo - Gestor da Superliga");
stage.setScene(new Scene(root, 1200, 800));
stage.setResizable(false);
stage.show();
}
private int codigoClube;
private String nome;
private String pais;
public TableView listarClubesTabela(ArrayList<Clubes> listaClubes) throws SQLException {
TableView tableView = new TableView();
tableView.setMaxWidth(1125);
tableView.setMinWidth(1125);
tableView.setMaxHeight(321);
TableColumn<Integer, Clubes> column2 = new TableColumn<>("Nome Clube");
column2.setCellValueFactory(new PropertyValueFactory<>("nome"));
column2.setMinWidth(150);
column2.setMaxWidth(150);
TableColumn<Integer, Clubes> column3 = new TableColumn<>("País Clube");
column3.setCellValueFactory(new PropertyValueFactory<>("pais"));
column3.setMinWidth(150);
column3.setMaxWidth(150);
tableView.getColumns().add(column2);
tableView.getColumns().add(column3);
for (Clubes clubes : listaClubes) {
tableView.getItems().add(clubes);
}
return tableView;
}
@FXML
private void atualizarTabela(ActionEvent event) {
try {
TabelaClubes = listarClubesTabela(conexao.getClubesPesquisa(txtNomeClube.getText()));
} catch (SQLException ex) {
Logger.getLogger(ConsultarJogoController.class.getName()).log(Level.SEVERE, null, ex);
}
PainelClubes.getChildren().add(TabelaClubes);
}
}
|
C | UTF-8 | 2,858 | 2.859375 | 3 | [] | no_license | #define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <mpi.h>
void check_cpu_bind_pid ( int num_thds, int num_cores, int thd_id )
{
int k, j, e;
cpu_set_t set;
pid_t pid= getpid();
sched_getaffinity( pid, sizeof ( set ), &set );
e = -1;
for ( j = 0; j < num_cores; ++j ) {
e = CPU_ISSET ( j, &set );
if ( e ) {
flockfile(stderr);
fprintf ( stderr, "thread %d is bound to core %d\n", thd_id, j );
funlockfile(stderr);
break;
}
}
if ( e == -1 ) {
flockfile(stderr);
fprintf ( stderr, "thread %d is not bound to any core!\n", thd_id );
funlockfile(stderr);
}
return;
}
void cpu_bind_pid( int num_thds, int num_cores, int thd_id, int strat )
{
cpu_set_t set;
const size_t cpu_set_size = sizeof ( cpu_set_t );
int kcore, k, st_core;
pid_t pid = getpid();
if (thd_id==0) {
flockfile(stderr);
fprintf ( stderr, "# threads = %d # cores = %d strategy = %d\n", num_thds, num_cores, strat );
funlockfile(stderr);
}
kcore=0xFFFF;
switch ( strat ) {
case 0:
kcore = (thd_id % num_cores);
break;
case 1:
st_core = num_cores - 1;
kcore = num_cores - 1;
for ( k = 0; k < thd_id; ++k ) {
kcore -= 1;
if ( kcore < 0 ) {
kcore = st_core;
}
}
break;
case 2:
st_core = num_cores - 2;
kcore = num_cores - 1;
for ( k = 0; k < thd_id; ++k ) {
kcore -= 2;
if ( kcore < 0 ) {
kcore = st_core;
st_core= (st_core==(num_cores-1))?(num_cores-2):(num_cores-1);
}
}
break;
default:
st_core = 1;
kcore = 0;
for ( k = 0; k < thd_id; ++k ) {
kcore += 2;
if ( kcore >= num_cores ) {
kcore = st_core;
st_core = ( st_core == 0 ) ? 1 : 0;
}
}
break;
}
CPU_ZERO ( &set );
CPU_SET ( kcore, &set );
sched_setaffinity ( pid, cpu_set_size, &set );
return;
}
int main(int argc,char **argv)
{
int rank,nproc;
const int ncores=8;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&nproc);
cpu_bind_pid(nproc,ncores,rank,0);
check_cpu_bind_pid(nproc,ncores,rank);
cpu_bind_pid(nproc,ncores,rank,1);
check_cpu_bind_pid(nproc,ncores,rank);
cpu_bind_pid(nproc,ncores,rank,2);
check_cpu_bind_pid(nproc,ncores,rank);
cpu_bind_pid(nproc,ncores,rank,3);
check_cpu_bind_pid(nproc,ncores,rank);
MPI_Finalize();
return EXIT_SUCCESS;
}
|
PHP | UTF-8 | 2,335 | 3.015625 | 3 | [] | no_license | <?php
class Adresse{
private $_id;
private $_nom;
private $_adresse;
private $_cp;
private $_ville;
private $_clientId;
public function __construct($_id, $_nom, $_adresse, $_cp, $_ville, $_clientId){
$this->_id = $_id;
$this->_nom = $_nom;
$this->_adresse = $_adresse;
$this->_cp = $_cp;
$this->_ville = $_ville;
$this->_clientId = $_clientId;
}
public function getID(){
return $this->_id;
}
public function setID($_id){
$this->_id = $_id;
}
public function getNom(){
return $this->_nom;
}
public function setSet($_nom){
$this->_nom = $_nom;
}
public function getAdresse(){
return $this->_adresse;
}
public function setAdresse($_adresse){
$this->_adresse = $_adresse;
}
public function getCp(){
return $this->_cp;
}
public function setCp($_cp){
$this->_cp = $_cp;
}
public function getVille(){
return $this->_ville;
}
public function setVille($_ville){
$this->_ville = $_ville;
}
public function getClientId(){
return $this->_clientId;
}
public function setClientId($_clientId){
$this->_clientId = $_clientId;
}
public static function getAllUserAdresse($bdd, $id){
$query = $bdd->prepare("SELECT * FROM adresse WHERE clientID = ?");
$query->execute(array($id));
$queryResult = $query->fetchAll();
$adresse = array();
foreach ($queryResult as $q) {
array_push($adresse, new Adresse($q["id"], $q["nom"], $q["adresse"], $q["cp"], $q["ville"], $id));
}
return $adresse;
}
public static function createAdresse($bdd, $nom, $adresse, $cp, $ville, $id){
$query = $bdd->prepare("INSERT INTO adresse (nom, adresse, cp, ville, clientID) VALUES (?, ?, ?, ?, ?)");
$query->execute(array($nom, $adresse, $cp, $ville, $id));
return $queryID = $bdd->lastInsertId();
}
public static function getAdresseCommande($bdd, $id, $clientID){
$query = $bdd->prepare("SELECT * FROM adresse WHERE id = ?");
$query->execute(array($id));
$queryResult = $query->fetchAll();
$queryClient = $bdd->prepare("SELECT * FROM client WHERE id = ?");
$queryClient->execute(array($clientID));
$queryClientResult = $queryClient->fetch();
$adresse = array();
foreach ($queryResult as $q) {
array_push($adresse, new Adresse($q["id"], $q["nom"], $q["adresse"], $q["cp"], $q["ville"], $queryClientResult["id"]));
}
return $adresse;
}
}
?> |
C++ | UTF-8 | 1,184 | 2.859375 | 3 | [] | no_license | #include "stdafx.h"
#include "GGE_node.h"
#include <iostream>
GGE::Node::Node(Node *parent, Vector2 offset) : parent(parent), offset(offset) {}
GGE::Behavior *GGE::Node::getBehavior(std::string type)
{
return behaviors[type];
}
void GGE::Node::addBehavior(Behavior *beh)
{
std::cout << "Adding behavior \"" << beh->getType() << "\"\n";
behaviors[beh->getType()] = beh;
}
void GGE::Node::init()
{
for (auto &pair : behaviors)
{
pair.second->init();
}
for (auto& node : nodes)
{
node.init();
}
}
void GGE::Node::update(float delta)
{
//std::cout << "Updating " << behaviors.size() << " behaviors." << std::endl;
for (auto &pair : behaviors)
{
pair.second->update(delta);
}
for (auto& node : nodes)
{
node.update(delta);
}
}
void GGE::Node::physicsUpdate()
{
for (auto &pair : behaviors)
{
pair.second->physicsUpdate();
}
for (auto& node : nodes)
{
node.physicsUpdate();
}
}
void GGE::Node::setRotation(float rotation)
{
this->rotation = rotation;
}
float GGE::Node::getRotation() const
{
return rotation;
}
void GGE::Node::setOffset(Vector2 offset)
{
this->offset = offset;
}
GGE::Vector2 GGE::Node::getOffset() const
{
return offset;
}
|
TypeScript | UTF-8 | 828 | 2.796875 | 3 | [] | no_license | export type Id = string
export interface Paginate<T> {
entities: T[]
totalCount: number
}
export interface PaginateFiltersQueryString {
offset?: string
limit?: string
}
export type OrderBy = 'desc' | 'asc'
export interface Entity {
id: Id
}
export interface PaginatedData<T> {
totalCount: number
hasNextPage: boolean
entities: Array<T>
}
export interface PaginatedFilters {
offset: number
limit: number
}
export interface PaginatedSearch<T extends object = any> extends PaginatedFilters {
sortBy?: Extract<keyof T, string>
orderBy?: 'asc' | 'desc'
}
export const paginateFilters2QueryString = ({offset, limit}: PaginatedFilters): PaginateFiltersQueryString => {
return {
offset: offset !== undefined ? offset + '' : undefined,
limit: limit !== undefined ? limit + '' : undefined,
}
}
|
C# | UTF-8 | 8,804 | 2.734375 | 3 | [
"CC0-1.0"
] | permissive | using Discord;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using TheOracle.GameCore;
using TheOracle.GameCore.Assets;
using TheOracle.GameCore.Oracle;
using WeCantSpell.Hunspell;
namespace TheOracle.BotCore
{
public static class Utilities
{
public static async Task<SocketMessage> NextChannelMessageAsync(this IChannel channel,
DiscordSocketClient client,
IUser user = null,
TimeSpan? timeout = null,
CancellationToken token = default(CancellationToken))
{
timeout = timeout ?? TimeSpan.FromSeconds(30);
var eventTrigger = new TaskCompletionSource<SocketMessage>();
var cancelTrigger = new TaskCompletionSource<bool>();
token.Register(() => cancelTrigger.SetResult(true));
async Task Handler(SocketMessage message)
{
var result = message.Channel.Id == channel.Id && (message.Author.Id == user.Id || user == null);
if (result) eventTrigger.SetResult(message);
}
client.MessageReceived += Handler;
var trigger = eventTrigger.Task;
var cancel = cancelTrigger.Task;
var delay = Task.Delay(timeout.Value);
var task = await Task.WhenAny(trigger, delay, cancel).ConfigureAwait(false);
client.MessageReceived -= Handler;
if (task == trigger)
return await trigger.ConfigureAwait(false);
else
return null;
}
public static decimal ConvertPercentToDecimal(string percentValue, CultureInfo culture = default)
{
if (culture == default) culture = CultureInfo.CurrentCulture;
var numFormat = culture.NumberFormat;
NumberFormatInfo nfi = new NumberFormatInfo()
{
CurrencyDecimalDigits = numFormat.PercentDecimalDigits,
CurrencyDecimalSeparator = numFormat.PercentDecimalSeparator,
CurrencyGroupSeparator = numFormat.PercentGroupSeparator,
CurrencyGroupSizes = numFormat.PercentGroupSizes,
CurrencyNegativePattern = numFormat.PercentNegativePattern,
CurrencyPositivePattern = numFormat.PercentPositivePattern,
CurrencySymbol = numFormat.PercentSymbol
};
var convertedValue = decimal.Parse(percentValue, NumberStyles.Currency, nfi);
return convertedValue / 100m;
}
public static bool Contains(this IEmote source, IEmote[] emotesToCheck)
{
return emotesToCheck.Any(check => check.Name == source.Name);
}
public static bool Contains(this IEmote source, IEmote emoteToCheck)
{
return source.Name == emoteToCheck.Name;
}
public static bool IsSameAs(this IEmote source, IEmote emoteToCheck)
{
if (source.Name == emoteToCheck.Name) return true;
List<Tuple<IEmote, IEmote>> EmotesThatAreTheSame = new List<Tuple<IEmote, IEmote>>
{
new Tuple<IEmote, IEmote>(new Emoji("0️⃣"), new Emoji("\u0030\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("1️⃣"), new Emoji("\u0031\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("2️⃣"), new Emoji("\u0032\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("3️⃣"), new Emoji("\u0033\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("4️⃣"), new Emoji("\u0034\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("5️⃣"), new Emoji("\u0035\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("6️⃣"), new Emoji("\u0036\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("7️⃣"), new Emoji("\u0037\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("8️⃣"), new Emoji("\u0038\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("9️⃣"), new Emoji("\u0039\u20E3")),
new Tuple<IEmote, IEmote>(new Emoji("\\⏺️"), new Emoji("⏺️")),
};
foreach (var tuple in EmotesThatAreTheSame)
{
if ((source.Contains(tuple.Item1) || source.Contains(tuple.Item2)) && (emoteToCheck.Contains(tuple.Item1) || emoteToCheck.Contains(tuple.Item2))) return true;
}
return false;
}
public static bool IsSameAs(this IEmote source, string emoteToCheck)
{
return source.IsSameAs(new Emoji(emoteToCheck));
}
public static GameName GetGameContainedInString(string value)
{
if (value.Length == 0) return GameName.None;
foreach (var s in Enum.GetNames(typeof(GameName)).Where(g => !g.Equals("none", StringComparison.OrdinalIgnoreCase)))
{
if (Regex.IsMatch(value, s, RegexOptions.IgnoreCase) && Enum.TryParse(s, out GameName game))
{
return game;
}
}
return GameName.None;
}
public static string RemoveGameNamesFromString(string value)
{
if (value.Length == 0) return value;
foreach (var s in Enum.GetNames(typeof(GameName)).Where(g => !g.Equals("none", StringComparison.OrdinalIgnoreCase)))
{
value = Regex.Replace(value, $"{s} ?", "", RegexOptions.IgnoreCase).Trim();
}
return value;
}
public static string ReplaceFirst(this string text, string search, string replace, StringComparison comparer = StringComparison.Ordinal)
{
int pos = text.IndexOf(search, comparer);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
public static bool UndoFormatString(this string data, string format, out string[] values, bool ignoreCase = true)
{
int tokenCount = 0;
format = Regex.Escape(format).Replace("\\{", "{");
for (tokenCount = 0; ; tokenCount++)
{
string token = string.Format("{{{0}}}", tokenCount);
if (!format.Contains(token)) break;
format = format.Replace(token,
string.Format("(?'group{0}'.*)", tokenCount));
}
RegexOptions options =
ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
Match match = new Regex(format, options).Match(data);
if (tokenCount != (match.Groups.Count - 1))
{
values = null;
return false;
}
else
{
values = new string[tokenCount];
for (int index = 0; index < tokenCount; index++)
values[index] =
match.Groups[string.Format("group{0}", index)].Value;
return true;
}
}
public static List<EmbedFieldBuilder> EmbedFieldBuilderFromList(this IList<string> list, string FieldName, bool Inline = false)
{
List<EmbedFieldBuilder> embedFields = new List<EmbedFieldBuilder>();
foreach (var item in list) embedFields.Add(new EmbedFieldBuilder().WithIsInline(Inline).WithName(FieldName).WithValue(item));
return embedFields;
}
public static WordList CreateDictionaryFromOracles(OracleService oracles = null, List<Asset> Assets = null)
{
var words = new List<string>();
if (oracles != null)
{
foreach (var oracle in oracles?.OracleList)
{
words.Add(oracle.Name);
if (oracle.Aliases?.Count() > 0) words.AddRange(oracle.Aliases);
words.Add(oracle.Category);
}
}
if (Assets != null)
{
foreach(var asset in Assets)
{
words.Add(asset.Name);
words.Add(asset.AssetType);
}
}
//var SingleWords = new List<string>();
//foreach (var s in words.Where(w => w != null)) SingleWords.AddRange(s.Split(' '));
try
{
var wordList = WordList.CreateFromWords(words.Where(w => w != null));
return wordList;
}
catch (Exception ex)
{
throw;
}
}
}
} |
Python | UTF-8 | 1,918 | 3.390625 | 3 | [] | no_license | '''
Atividade machine-learning, Checkpoint 3
Nome: Lucas Venancio Coutinho
'''
from sklearn import tree # |||| ||||
features = [[54, 64, 199], [90, 94, 178], [69, 123, 119], [78, 109, 138], [99, 88, 121], [93, 113, 179], [92, 49, 132], [63, 96, 127], [57, 79, 149], [96, 60, 107], [107, 164, 93],[117, 163, 83],[126, 153, 125],[119, 193, 188],[106, 160, 130],[113, 169, 66],[122, 197, 23],[115, 178, 168],[114, 155, 68],[100, 198, 47],[136, 313, 345],[211, 285, 376],[250, 339, 325],[287, 230, 264],[158, 258, 295],[129, 255, 352],[181, 366, 294],[137, 202, 246],[241, 307, 244],[212, 218, 222]]
#Uma pessoa normal será representada por 0, Uma pessoa alterada será representada por 1 e uma pessoa diabética será representada por 2
labels = [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2]
classif = tree.DecisionTreeClassifier() #Classificador
classif.fit(features, labels)
print("*"*60)
print("Programa para fazer um pré-diagnóstico de diabetes")
print("*"*60)
i = 0
while i == 0:
try:
jejum = float(input("Digite a sua glicose em jejum: "))
apos = float(input("Digite a sua glicose após 2h de injerir 75g de glicose: "))
casual = float(input("Digite sua Glicose Casual: "))
i = 1
except:
print("coloque apenas numeros")
x = classif.predict([[jejum, apos, casual]])
print("-"*40)
if x == 0:
print("Sua Glicose está Normal")
elif x == 1:
print("Sua Glicose está Diminuída")
elif x == 2:
print("Sua Glicose está acima do normal, provavelmete está com diabetes")
print("Lembre-se isto é um pré-diagnóstico, nunca se auto diagnostique sempre procre um médico")
|
Java | UTF-8 | 2,009 | 2.15625 | 2 | [] | no_license | package org.ndx.codingame.fantastic.actions.spells;
import org.ndx.codingame.fantastic.Constants;
import org.ndx.codingame.fantastic.Playground;
import org.ndx.codingame.fantastic.actions.Action;
import org.ndx.codingame.fantastic.actions.ActionVisitor;
import org.ndx.codingame.fantastic.entities.Entity;
import org.ndx.codingame.fantastic.entities.Wizard;
import org.ndx.codingame.fantastic.status.Status;
import org.ndx.codingame.lib2d.continuous.ContinuousPoint;
import org.ndx.codingame.lib2d.shapes.Segment;
import org.ndx.codingame.lib2d.shapes.Vector;
public class AccioSpell extends AbstractSpell {
public static final String ACCIO = "ACCIO";
private double score = -1;
private final Wizard wizard;
private final Segment defended;
public AccioSpell(final Segment defended, final Wizard wizard, final Entity entity) {
super(ACCIO, entity, Constants.MAGIC_ACCIO_COST);
this.defended = defended;
this.wizard = wizard;
}
@Override
public double getScore() {
if(score<0) {
final Vector extent = new Vector(wizard.direction.second, target.direction.second);
final Vector extendedMove = new Vector(target.position,
new ContinuousPoint(target.position.x+target.speed.x*3, target.position.x+target.speed.x*3));
if(defended.intersectsWith(extendedMove.toLine())) {
score = Math.max(Playground.WIDTH-Math.abs(2*extent.getX()), 0);
if(defended.intersectsWith(extendedMove)) {
score *= 2;
}
} else {
score = -cost;
}
}
return score;
}
@Override
public boolean conflictsWith(final Status status, final Action current) {
return current.accept(new SpellConflictAdapter(status, this) {
@Override
protected Boolean doVisit(final AccioSpell accioSpell) {
return true;
}
});
}
@Override
public <Type> Type accept(final ActionVisitor<Type> visitor) {
return visitor.visit(this);
}
@Override
public void updateStatus(final Status status) {
super.updateStatus(status);
status.get(AccioStatus.class).applyOn(target);
}
}
|
SQL | UTF-8 | 1,165 | 3.015625 | 3 | [] | no_license | -- Table: bouquet
CREATE TABLE bouquet (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), assemble_price DECIMAL);
INSERT INTO bouquet (id, name, assemble_price) VALUES (1, 'married', 12.7);
-- Table: flower
CREATE TABLE flower (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), length INTEGER, freshness INTEGER, price DECIMAL, petals INTEGER, spike BOOLEAN, bouquet_id INTEGER);
INSERT INTO flower (id, name, length, freshness, price, petals, spike, bouquet_id) VALUES (1, 'chamomile', 10, 1, 12.5, 6, NULL, 1);
INSERT INTO flower (id, name, length, freshness, price, petals, spike, bouquet_id) VALUES (2, 'rose', 12, 1, 15.6, NULL, 1, 1);
INSERT INTO flower (id, name, length, freshness, price, petals, spike, bouquet_id) VALUES (3, 'rose', 11, 2, 15.2, NULL, 1, 1);
INSERT INTO flower (id, name, length, freshness, price, petals, spike, bouquet_id) VALUES (4, 'rose', 15, 1, 13, NULL, 1, 1);
INSERT INTO flower (id, name, length, freshness, price, petals, spike, bouquet_id) VALUES (5, 'rose', 15, 1, 13, NULL, 1, 1);
INSERT INTO flower (id, name, length, freshness, price, petals, spike, bouquet_id) VALUES (6, 'rose', 15, 1, 13, NULL, 1, 1);
|
PHP | UTF-8 | 6,730 | 2.5625 | 3 | [] | no_license | <?php
class Empleado extends ActiveRecord{
protected $id;
protected $cedula;
protected $nombre;
protected $apellido;
protected $email;
protected $tipo;
protected $decanato_id;
protected $estatus;
public function getId() { return $this->id; }
public function getCedula() { return $this->cedula; }
public function getNombre() { return $this->nombre; }
public function getApellido() { return $this->apellido; }
public function getEmail() { return $this->email; }
public function getTipo() { return $this->tipo; }
public function getEstatus() { return $this->estatus; }
public function getDecanato_id() { return $this->decanato_id; }
public function setDecanato_id($x) { $this->decanato_id = $x; }
public function setId($x) { $this->id = $x; }
public function setCedula($x) { $this->cedula = $x; }
public function setNombre($x) { $this->nombre = $x; }
public function setApellido($x) { $this->apellido = $x; }
public function setEmail($x) { $this->email = $x; }
public function setTipo($x) { $this->tipo = $x; }
public function setEstatus($x) { $this->estatus = $x; }
public function getNombreApellido($id) {
$aux='';
$empleado = $this->findFirst("id='$id'");
if ($empleado){
$aux= "{$empleado->getNombre()} {$empleado->getApellido()}";
}
return $aux;
}
public function consultaEmpleados($cedula='',$start='*',$limit='*') {
$aux = array();
$i=0;
$total=0;
$total= $this->count("estatus !='E'");
$sql = " SELECT e.id AS empleadoId,cedula,e.decanato_id AS decanatoId, e.nombre AS nombre ,apellido, email, ";
$sql .= " e.estatus AS estatus,d.nombre AS decanato, tipo ";
$sql .= " FROM empleado e, decanato d ";
$sql .= " WHERE e.decanato_id=d.id AND e.estatus!='E' ";
if ($cedula!=''){
$sql .= " AND e.cedula LIKE '$cedula%'";
}
$sql .= " ORDER BY e.cedula, e.tipo ";
if ($start!='*' && $limit!='*'){
$sql .= " LIMIT ".$start.",".$limit." ";
}
$db = Db::rawConnect();
$result = $db->query($sql);
while($row = $db->fetchArray($result)){
$aux[$i]['empleadoId'] = $row['empleadoId'];
$aux[$i]['cedula'] = $row['cedula'];
$aux[$i]['nombre'] = utf8_encode($this->adecuarTexto($row['nombre']));
$aux[$i]['apellido'] = utf8_encode($this->adecuarTexto($row['apellido']));
$aux[$i]['correo'] = utf8_encode($row['email']);
$aux[$i]['decanatoId'] = $row['decanatoId'];
$aux[$i]['decanato'] = utf8_encode($row['decanato']);
$aux[$i]['estatus'] = utf8_encode($this->getTextoEstatus($row['estatus']));
$aux[$i]['tipo'] = utf8_encode($this->getTextoTipo($row['tipo']));
$i++;
}
return array('total'=>$total,
'resultado' => $aux);
}
protected function getTextoEstatus($valor){
$texto='';
switch (strtoupper($valor)) {
case 'A':
$texto='Activo';
break;
case 'E':
$texto='Eliminado';
break;
case 'I':
$texto='Inactivo';
break;
}
return $texto;
}
protected function getTextoTipo($valor){
$texto='';
switch (strtoupper($valor)) {
case 'A':
$texto='Administrador';
break;
case 'C':
$texto='Coordinador';
break;
case 'S':
$texto='Analista';
break;
}
return $texto;
}
public function buscar($pCedula){
$resp=array();
$resp['success']= false;
$resp['errorMsj']= '';
$resp['datos']=array();
$errorMsj ='';
$emp = $this->findFirst("cedula='$pCedula'");
if ($emp){
$errorMsj ='Empleado ya registrado.';
$resp['datos']['id']=$emp->getId();
$resp['datos']['cedula']=$emp->getCedula();
$resp['datos']['email']=$emp->getEmail();
$resp['datos']['tipo']=utf8_encode($emp->getTipo());
$resp['datos']['apellido']=utf8_encode($this->adecuarTexto($emp->getApellido()));
$resp['datos']['nombre']=utf8_encode($this->adecuarTexto($emp->getNombre()));
$resp['datos']['decanatoId']=$emp->getDecanato_id();
}
$resp['errorMsj']= $errorMsj;
$resp['success']= true;
return ($resp);
}
public function guardar($cedula,$nombre,$apellido,$correo,$categoria,$idDecanato){
$success=false;
$enviarCorreo=false;
$id=0;
$emp = $this->findFirst("cedula='$cedula'");
if ($emp){
$emp->setNombre($nombre);
$emp->setApellido($apellido);
$emp->setEmail($correo);
$emp->setTipo($categoria);
$emp->setDecanato_id($idDecanato);
$emp->setEstatus('A');
$id= $emp->getId();
$success = $emp->update();
}else{
$this->setCedula($cedula);
$this->setNombre($nombre);
$this->setApellido($apellido);
$this->setTipo($categoria);
$this->setEmail($correo);
$this->setDecanato_id($idDecanato);
$this->setEstatus('I');
$enviarCorreo = true;
$success= $this->save();
$emp = $this->findFirst("cedula='$cedula'");
$id= $emp->getId();
}
return array("success"=>$success,
"correo"=> $enviarCorreo,
"id"=>$id);
}
public function activarEmpleado($id) {
$flag=false;
$emp= $this->findFirst("id='$id'");
if ($emp){
$emp->setEstatus('A');
$flag=$emp->update();
}
return $flag;
}
public function actualizar($id,$nombre,$apellido,$correo){
$success=false;
$emp = $this->findFirst("id='$id'");
if ($emp){
$emp->setNombre($nombre);
$emp->setApellido($apellido);
$emp->setEmail($correo);
$success = $emp->update();
}
return $success;
}
public function eliminar($id){
$success=false;
$emp = $this->findFirst("id='$id'");
if ($emp){
$emp->setEstatus('E');
$success = $emp->update();
}
return $success;
}
public function buscarbyId($id){
$resp=array();
$emp = $this->findFirst("id='$id'");
if ($emp){
$resp['cedula']=$emp->getCedula();
$resp['email']=$emp->getEmail();
$resp['tipo']=utf8_encode($emp->getTipo());
$resp['apellido']=utf8_encode($this->adecuarTexto($emp->getApellido()));
$resp['nombre']=utf8_encode($this->adecuarTexto($emp->getNombre()));
}
return ($resp);
}
public function existeCoordinador($decanato){
$success=false;
$emp = $this->findFirst("estatus='A' AND tipo='C' AND decanato_id=$decanato");
if ($emp){
$success = true;
}
return $success;
}
public function getEmpleadosByDecanato($idDecanato){
$arrEmpleados = array();
$i = 0;
$empleados = $this->find("estatus = 'A' AND tipo = 'C' AND decanato_id = ".$idDecanato);
foreach ($empleados as $empleado){
$arrEmpleados[$i]['id'] = $empleado->getId();
$arrEmpleados[$i]['nombre'] =$empleado->getNombre().' '.$empleado->getApellido();
$arrEmpleados[$i]['cedula'] = $empleado->getCedula();
$i++;
}
return $arrEmpleados;
}
}
?>
|
JavaScript | UTF-8 | 1,585 | 2.640625 | 3 | [] | no_license | import React, { useEffect, useState } from "react";
import "./styles/app.scss";
import News from "./components/News";
import Parser from "rss-parser";
function App() {
const [news, setNews] = useState(() => {
const localData = localStorage.getItem("news");
return localData ? JSON.parse(localData) : [];
});
useEffect(() => {
localStorage.setItem("news", JSON.stringify(news));
}, [news]);
const [rssLink, setRssLink] = useState("");
let parser = new Parser({
customFields: {
item: [["media:content", "media", { keepArray: true }]],
},
});
const handleInupt = (e) => {
setRssLink(e.target.value);
};
const fetchNews = async (link) => {
let feed = await parser.parseURL(link);
setNews(feed);
};
const handleSubmit = (e) => {
fetchNews(rssLink);
};
const handleClean = (e) => {
setNews([]);
};
return (
<div className="App">
<button className="custom-button clean-button" onClick={handleClean}>
Išvalyti viską
</button>
<div className="header text-center p-4">
<h1 className="p-3">FollowUp</h1>
<input
type="text"
placeholder="RSS Link"
id="rssInput"
className="w-50 p-3 rounded"
onChange={handleInupt}
></input>
<button
className="custom-button"
type="submit"
onClick={handleSubmit}
className="d-block p-3 w-25 m-auto"
>
PRIDĖTI
</button>
<News news={news} />
</div>
</div>
);
}
export default App;
|
Go | UTF-8 | 342 | 2.78125 | 3 | [] | no_license | package json
import (
"encoding/json"
"fmt"
"testing"
)
func TestDecode(t *testing.T) {
jsonRequest := "{\"FirstName\":\"Muhammad\",\"LastName\":\"Azzam\",\"Age\":25,\"Married\":false,\"Hobbies\":[\"Gaming\",\"Reading\"]}"
jsonBytes := []byte(jsonRequest)
person := &Person{}
json.Unmarshal(jsonBytes, person)
fmt.Println(person)
} |
C++ | UTF-8 | 268 | 2.515625 | 3 | [] | no_license | #include<iostream>
#include "HeapSort.h"
#include "Heap.h"
#include "ToolFuncs.h"
using namespace std;
void HeapSort(int array[], int len)
{
MakeMaxHeap(array, len);
for(int i=len-1;i>0;--i){
swap(array[0], array[i]);
MaxHeap(array, i, 0);
}
}
|
C# | UTF-8 | 2,574 | 2.640625 | 3 | [] | no_license | public class ComputerSettingResponse
{
internal ComputerSetting Settings { get; set; }
}
internal class ComputerSetting
{
internal string Id { get; set; }
internal string HospitalName { get; set; }
internal string ComputerType { get; set; }
internal string Environment { get; set; }
internal string LabelPrinterName { get; set; }
internal string DocumentPrinterName { get; set; }
}
string xmlString = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<response>
<computer_setting id=""1"" hospital_name=""foo"" computer_type=""bar"" environment=""staging"" label_printer_name=""labels"" document_printer_name=""docs""/>
</response> ";
XDocument xDoc = XDocument.Parse(xmlString);
//XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
string ns = string.Empty;
List<ComputerSettingResponse> collection = new List<ComputerSettingResponse>
(
from list in xDoc.Descendants(ns + "response")
from item1 in list.Elements(ns + "computer_setting")
where item1 != null
select new ComputerSettingResponse
{
//note that the cast is simpler to write than the null check in your code
//http://msdn.microsoft.com/en-us/library/bb387049.aspx
Settings = new ComputerSetting
(
)
{
Id = item1.Attribute("id") == null ? string.Empty : item1.Attribute("id").Value,
HospitalName = item1.Attribute("hospital_name") == null ? string.Empty : item1.Attribute("hospital_name").Value,
ComputerType = item1.Attribute("computer_type") == null ? string.Empty : item1.Attribute("computer_type").Value,
Environment = item1.Attribute("environment") == null ? string.Empty : item1.Attribute("environment").Value,
LabelPrinterName = item1.Attribute("label_printer_name") == null ? string.Empty : item1.Attribute("label_printer_name").Value,
DocumentPrinterName = item1.Attribute("document_printer_name") == null ? string.Empty : item1.Attribute("document_printer_name").Value,
}
}
);
/* if you know there is only one */
ComputerSettingResponse returnItem = collection.FirstOrDefault();
|
Rust | UTF-8 | 3,205 | 2.78125 | 3 | [
"MIT"
] | permissive | use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::cell::RefCell;
use std::rc::Rc;
use error::*;
use eval::PyRes;
use object::{PyObject, PyInnerObject};
use object::excobj::*;
use object::typeobj::*;
fn pystr_add(lv: Rc<PyObject>, rv: Rc<PyObject>) -> PyRes<Rc<PyObject>> {
match lv.inner {
PyInnerObject::StrObj(ref l_obj) => {
match rv.inner {
PyInnerObject::StrObj(ref r_obj) => {
return Ok(PyObject::from_string(format!("{}{}", l_obj.s, r_obj.s)));
},
_ => {}
}
},
_ => {}
}
pyerr_set_string(
PY_TYPEERROR_TYPE.with(|tp| Rc::clone(tp)),
"__eq__ expects str objects"
);
Err(())
}
fn pystr_eq(lv: Rc<PyObject>, rv: Rc<PyObject>) -> PyRes<Rc<PyObject>> {
match lv.inner {
PyInnerObject::StrObj(ref l_obj) => {
match rv.inner {
PyInnerObject::StrObj(ref r_obj) => {
return Ok(PyObject::from_bool(l_obj.s == r_obj.s));
},
_ => {}
}
},
_ => {}
}
pyerr_set_string(
PY_TYPEERROR_TYPE.with(|tp| Rc::clone(tp)),
"__eq__ expects str objects"
);
Err(())
}
fn pystr_hash(obj: Rc<PyObject>) -> PyRes<u64> {
let mut hasher = DefaultHasher::new();
match obj.inner {
PyInnerObject::StrObj(ref obj) => obj.s.hash(&mut hasher),
_ => {
pyerr_set_string(
PY_TYPEERROR_TYPE.with(|tp| Rc::clone(tp)),
"__hash__ expects str objects"
);
return Err(());
}
};
Ok(hasher.finish())
}
fn pystr_len(v: Rc<PyObject>) -> PyRes<Rc<PyObject>> {
match v.inner {
PyInnerObject::StrObj(ref obj) => Ok(PyObject::from_i32(obj.s.len() as i32)),
_ => {
pyerr_set_string(
PY_TYPEERROR_TYPE.with(|tp| Rc::clone(tp)),
"__len__ expects str objects"
);
return Err(());
}
}
}
thread_local! (
pub static PY_STRING_TYPE: Rc<PyObject> = {
let strtp = PyTypeObject {
tp_name: "str".to_string(),
tp_hash: Some(Rc::new(pystr_hash)),
tp_fun_eq: Some(Rc::new(pystr_eq)),
tp_fun_add: Some(Rc::new(pystr_add)),
tp_len: Some(Rc::new(pystr_len)),
..Default::default()
};
Rc::new(PyObject {
ob_type: PY_TYPE_TYPE.with(|tp| { Some(Rc::clone(tp)) }),
ob_dict: None,
inner: PyInnerObject::TypeObj(Rc::new(RefCell::new(strtp))),
})
}
);
pub struct PyStringObject {
pub s: String,
}
impl PyObject {
pub fn from_str(s: &str) -> Rc<PyObject> {
PyObject::from_string(s.to_string())
}
pub fn from_string(raw_string: String) -> Rc<PyObject> {
PY_STRING_TYPE.with(|tp| {
let inner = PyStringObject { s: raw_string };
Rc::new(PyObject {
ob_type: Some(Rc::clone(&tp)),
ob_dict: None,
inner: PyInnerObject::StrObj(Rc::new(inner))
})
})
}
}
|
C++ | UTF-8 | 3,257 | 2.6875 | 3 | [] | no_license | #ifndef __TEXT_H__
#define __TEXT_H__
#include <string>
#include <GL/glew.h>
#include "BaseUIComponent.h"
#include "Font.h"
#include "Shader.h"
#include "VertexUI.h"
#include "Anchor.h"
#include "Colorable.h"
namespace UI
{
class Text : public BaseUIComponent, public Colorable
{
private:
#pragma region Attributes
GLuint _VAO;
GLuint _VBO;
GLuint _EBO;
Anchor _textAnchor;
GLfloat _textScale;
std::wstring _text;
Resources::Font* _font;
Resources::Shader* _shader;
std::vector<VertexUI> _characters;
std::vector<GLuint> _charactersTex;
#pragma endregion
#pragma region Private Methods
Text& initBuffers() noexcept;
Text& resetGLBuffers();
Text& setEBO() noexcept;
bool computeCharacterCoordinates(std::vector<VertexUI>& charactersPos,
GLfloat xpos, GLfloat ypos,
GLfloat w, GLfloat h) noexcept;
bool clampGlyph(GLfloat xpos, GLfloat ypos, GLfloat w, GLfloat h,
GLfloat& uMin, GLfloat& uMax,
GLfloat& vMin, GLfloat& vMax) noexcept;
Vec3 anchoredPosition() noexcept;
GLfloat stringWidth() noexcept;
GLfloat biggestHeight() noexcept;
#pragma endregion
public:
#pragma region Constructors / Destructors
Text() noexcept;
Text(const Text& t) noexcept;
Text(Resources::Font* font, Resources::Shader* shader) noexcept;
~Text() = default;
#pragma endregion
#pragma region Operators
Text& operator=(const Text& t) noexcept;
#pragma endregion
#pragma region Methods
BaseUIComponent& render(Mat transformParent) noexcept override;
//Update the text area with the new stats.
//Need to be called after modifications of the text
Text& update() noexcept;
#pragma endregion
#pragma region Accessors
BaseUIComponent& setWidth(GLuint width) noexcept override;
BaseUIComponent& setHeight(GLuint height) noexcept override;
inline Anchor textAnchor() const { return _textAnchor; }
inline Anchor& textAnchor() { return _textAnchor; }
inline GLfloat textScale() const { return _textScale; }
inline GLfloat& textScale() { return _textScale; }
inline std::wstring text() const { return _text; }
inline std::wstring& text() { return _text; }
inline Resources::Font* font() const { return _font; }
inline Resources::Font* font() { return _font; }
#pragma endregion
};
} // namespace UI
#endif // __TEXT_H__ |
Python | UTF-8 | 1,383 | 3.359375 | 3 | [] | no_license |
# Tags: Array, Two Pointer, Facebook, MS, Amazon
# https://leetcode.com/problems/3sum/discuss/162647/15-line-Python-easy-to-understand-solution-with-Hash
# https://leetcode.com/problems/3sum/discuss/7498/Python-solution-with-detailed-explanation
# https://leetcode.com/problems/3sum/discuss/187872/Python-simple-O(n2)-solution-with-explanation
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 3: # Base case
return []
if len(nums) == 3:
if (nums[0] + nums[1] + nums[2]) == 0:
return [nums]
else:
return []
sol = {} # The solution set must not contain duplicate triplets, so we take hash having triplet as key
nums = sorted(nums)
for i in range(len(nums) - 3):
a = nums[i]
start = i + 1
end = len(nums) - 1
while (start < end):
b = nums[start]
c = nums[end]
if (a + b + c) == 0:
sol[a, b, c] = [a, b, c]
end = end - 1
elif (a + b + c) > 0:
end = end - 1
else:
start = start + 1
return sol.values()
|
Python | UTF-8 | 1,018 | 2.703125 | 3 | [] | no_license | import pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sentence_normalizer import normalize_sentence
# Load tsv file into dataframe
data = pd.read_csv('data_sets/classified_titles.tsv', sep='\t')
positions_categories = pd.Categorical(data["Classification"])
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
data["Position"],
positions_categories.codes,
train_size=0.85,
stratify=positions_categories.codes
)
X_train = [normalize_sentence(x) for x in X_train]
X_test = [normalize_sentence(x) for x in X_test]
with open('data_sets/x_train.pkl', 'wb') as file:
pickle.dump(X_train, file)
with open('data_sets/x_test.pkl', 'wb') as file:
pickle.dump(X_test, file)
with open('data_sets/y_train.pkl', 'wb') as file:
pickle.dump(y_train, file)
with open('data_sets/y_test.pkl', 'wb') as file:
pickle.dump(y_test, file)
with open('data_sets/positions_categories.pkl', 'wb') as file:
pickle.dump(positions_categories, file)
|
JavaScript | UTF-8 | 451 | 3.859375 | 4 | [] | no_license | // Pedir para o usuário digitar um número e mostrar a tabuada desse numero de 1 a 1000
// Deve ter a possibilidade do usuário digitar outro número e também de limpar a tabuada gerada previamente
let output = document.querySelector('#output');
let mensagem = '';
/*
function mostrarTabuada() {
alert("mostarTabuada chamada");
}
*/
output.innerHTML = mensagem;
function mostrarTabuada() {
console.log("mostrarTabuada foi invocada");
} |
JavaScript | UTF-8 | 1,534 | 3.125 | 3 | [] | no_license | //NOTE: In order to use this library, you will need to ensure you have jQuery on your HTML page.
$(document).ready(function(){
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if(all[i].className.indexOf("NBV-") > -1){
syncVar(all[i].className.split('-')[1]);
}
}
});
function getFileContent(pathToFile,varToFill){
$.ajax({
url : pathToFile,
dataType: "text",
success : function (data) {
loadItem(data, varToFill);
}
});
}
function loadItem(txt,theVar){
$(".NBV-"+theVar).text(txt);
}
function syncVar(varToFind){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "var.xml", true);//https://nucleonbytes.github.io/NBLib/NB%20VarVar/
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
var allText = txtFile.responseText;
var xmlDoc = $.parseXML( allText );
var xx = $(xmlDoc).find('NucleonBytesVariables').find(varToFind).first().html();
var yy = $(xmlDoc).find('NucleonBytesVariables').find(varToFind).first().attr('src');
if (xx==""){
if(yy==""){
//empty variable or not found
}
else
{
getFileContent(yy,varToFind);
}
}
else
{
$(".NBV-"+varToFind).html(xx);
}
}
}
}
txtFile.send(null);
}
|
Java | UTF-8 | 1,602 | 2.125 | 2 | [] | no_license | package org.prj.arachne.domain.weather;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.prj.arachne.domain.member.MemberAccount;
import org.prj.arachne.domain.weather.valueObj.Grid;
import org.prj.arachne.domain.weather.valueObj.simpleWeather.Precipitation;
import javax.persistence.*;
import java.util.Date;
@Entity
@AllArgsConstructor
@NoArgsConstructor
@ToString
@ApiModel(value = "간단 날씨정보 모델")
@Data
public class SimpleWeather {
@Id
@GeneratedValue
@JsonIgnore
private Long id;
@ManyToOne
@JoinColumn(name="weather_owner_id")
@JsonIgnore
private MemberAccount weatherOwner;
//기상예보 위치
@Embedded
@ApiModelProperty(value = "지역정보",dataType = "Grid")
private Grid grid;
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-dd HH:mm:ss",timezone="Asia/Seoul")
private Date releaseTime;
//강수량
@Embedded
@ApiModelProperty(value = "강수량 관련")
private Precipitation precipitation;
//하늘 상태
private String skyState;
private String temperatureToday;
private String temperatureMax;
private String temperatureMin;
private String humidity;
//바람방향 세기
private String windirection;
private String windspeed;
}
|
Python | UTF-8 | 350 | 3.203125 | 3 | [] | no_license | n = int(input("n: "))
a = list(map(int, input("a: ").split()))
arr = []
for i in range(len(a)):
if len(arr) != 5:
arr.append(a[i])
if len(arr) == 5:
for j in range(len(arr)):
if a[i] < arr[j]:
arr[j] = a[i]
break
arr.sort()
arr = arr[::-1]
print(' '.join(map(str, arr))) |
PHP | UTF-8 | 2,450 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Models\Attribute;
class AttributesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('attributes.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$attribute = new Attribute;
return view('attributes.create', compact('attribute'));
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function store()
{
$this->validate(request(), [
'name' => 'required|max:255|unique:attributes',
], [
'name.unique' => 'Tên thuộc tính đã tồn tại.',
]);
$attribute = Attribute::forceCreate([
'name' => request('name'),
]);
flash()->success('Success!', 'Attribute successfully created.');
return redirect()->route('attributes.index');
}
/**
* Display the specified resource.
*
* @param \App\Models\Attribute $attribute
* @return \Illuminate\Http\Response
*/
public function show(Attribute $attribute)
{
return view('attributes.edit', compact('attribute'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Attribute $attribute
* @return \Illuminate\Http\Response
*/
public function edit(Attribute $attribute)
{
return view('attributes.edit', compact('attribute'));
}
/**
* Update the specified resource in storage.
*
* @param \App\Models\Attribute $attribute
* @return \Illuminate\Http\Response
*/
public function update(Attribute $attribute)
{
$this->validate(request(), [
'name' => 'required|max:255|unique:attributes,name,'.$attribute->id,
], [
'name.unique' => 'Tên thuộc tính đã tồn tại.',
]);
$attribute->forceFill([
'name' => request('name'),
])->save();
flash()->success('Success!', 'Attribute successfully updated.');
return redirect()->route('attributes.index');
}
public function getDatatables()
{
return Attribute::getDatatables();
}
}
|
C# | UTF-8 | 1,608 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | using System.Collections.Generic;
using UOS;
public struct GlobalPosition
{
public static GlobalPosition zero { get { return new GlobalPosition(0, 0); } }
public double latitude;
public double longitude;
public double delta;
public GlobalPosition(double latitude, double longitude, double delta = 0)
{
this.latitude = latitude;
this.longitude = longitude;
this.delta = delta;
}
public static GlobalPosition FromJSON(IDictionary<string, object> json, bool getDelta = true)
{
double latitude = ExtractDouble(json, "latitude");
double longitude = ExtractDouble(json, "longitude");
double delta = 0;
if (getDelta)
delta = ExtractDouble(json, "delta");
return new GlobalPosition(latitude, longitude, delta);
}
private static double ExtractDouble(IDictionary<string, object> json, string name)
{
object v = null;
if (json.TryGetValue(name, out v))
{
if (v is double)
return (double)v;
else
{
double d = 0;
if (double.TryParse(v.ToString(), out d))
return d;
else
throw new System.ArgumentException("parameter '" + name + "' is not a valid double");
}
}
else
throw new System.ArgumentException("parameter '" + name + "' not informed");
}
public override string ToString()
{
return string.Format("{0:f6},{1:f6},{2:f6}", latitude, longitude, delta);
}
}
|
Markdown | UTF-8 | 5,627 | 3.390625 | 3 | [] | no_license | 1) What is GIT?
Ans :- It is a distributed version control system and source code management system. It handle small and large projects with speed and efficiency.
2) What is a repository in GIT?
Ans :- A repository contains a directory named .git, where git keeps all of its metadata for the repository.
3) What is the command you can use to write a commit message?
Ans :- git commit -m "Message"
4) What is the difference between GIT and SVN?
Ans :- 1. Git is a distributed version control system, whereas SVN is a centralized version control system.
2. Git uses multiple repositories including a centralized repository and server while SVN does not have a centralized repository or server.
3. Git is less preferred for handling large files while SVN can handle multiple projects stored in the same repository
5) What are the advantages of using GIT?
Ans :- a)Data redundancy and replication
b)High availability
c)Only one.git directory per repository
d)Collaboration friendly
f)Any sort of projects can use GIT
6) What language is used in GIT?
Ans :- C language
7) What is the function of ‘GIT PUSH’ in GIT?
Ans :- Used to upload local repository content to a remote repository.
8) Why GIT better than Subversion?
Ans :- GIT is an open source version control system; it will allow you to run ‘versions’ of a project. Also it allows you keep the back track if necessary and undo those changes
9) What is “Staging Area” or “Index” in GIT?
Ans :- Before completing the commits, it can be formatted and reviewed in an intermediate area known as Staging Area
10) What is GIT stash?
Ans :- GIT stash takes the current state of the working directory and index and puts it on the stack and gives you back a clean working directory.
11) What is GIT stash drop?
Ans :-
12) How will you know in GIT if a branch has been already merged into master?
Ans :- Git branch---merged lists the branches that have been merged into the current branch
Git branch----no merged lists the branches that have not been merged
13) What is the function of git clone?
Ans :- It creates a copy of an existing Git repository. To get the copy of acentral repository, ‘cloning’ is the most common way used by programmers.
14) What is the function of ‘git config’?
Ans :- It is a convenient way to set configuration options for your Git installation.
15) What does commit object contain?
Ans :- a) Reference to parent commit objects
b) An SHAI name, a 40 character string that uniquely identifies the commit object.
16) How can you create a repository in Git?
Ans :- Run command “git init”. By running this command .git directory will be created in the project directory, the directory does not need to be empty.
17) What is ‘head’ in git and how many heads can be created in a repository?
Ans :- It is simply a reference to a commit object. A repository can contain any number of heads
18) What is the purpose of branching in GIT?
Ans :- You can create your own branch and jump between those branches.
19) What is the common branching pattern in GIT?
Ans :- Create one as “Main“branch and create another branch to implement new features.
20) How can you bring a new feature in the main branch?
Ans :- Use a command “git merge” or “git pullcommand”
21) What is a ‘conflict’ in git?
Ans :- A ‘conflict’ arises when the commit that has to be merged has some change in one place, andthe current commit also has a change at the same place.
22) How can conflict in git resolved?
Ans :- Edit the files to fix the conflicting changes and then add theresolved files by running “git add” after that to commit the repaired merge, run “git commit”.
23) To delete a branch what is the command that is used?
Ans :- command “git branch –d [head]”
24) What is another option for merging in git?
Ans :- “Rebasing” is an alternative to merging in git
25) What is GIT version control?
Ans :- you can track the history of a collection of files and includes the functionality to revert the collection of files to another version.
26) What is the function of ‘git diff ’ in git?
Ans :- shows the changes between commits, commit and working tree etc
27) What is ‘git status’ is used for?
Ans :- It shows you the difference between the working directory and the index, it ishelpful in understanding a git more comprehensively.
28) What is the difference between the ‘git diff ’and ‘git status’?
Ans :- git diff’ is similar to ‘git status’, but it shows the differences between various commits.
29) What is the function of ‘git checkout’ in git?
Ans :- It is used to update directories or specific files in your working tree
30) What is the function of ‘git rm’?
Ans :- To remove the file from the staging area
31) What is the function of ‘git stash apply’?
Ans :- used to bring back the saved changes onto the working directory.
32) What is the use of ‘git log’?
Ans :- To find specific commits in your project history- by author, date, content or history.
33) What is ‘git add’ is used for?
Ans :- adds file changes in your existing directory to your index
34) What is the function of ‘git reset’?
Ans :- It is used to reset your index as well as the working directory to the state ofyour last commit.
35) Explain what is commit message?
Ans :- provides useful information about what has changed
36) Name a few Git repository hosting services
Ans :- Pikacode Visual Studio Online GitHub GitEnterprise SourceForge.net
|
Shell | UTF-8 | 271 | 2.984375 | 3 | [] | no_license | #!/bin/bash
if [ $# != 1 ]
then
echo "argument error!"
echo "usage: ./build_clean.sh [PROJ_NAME]"
exit 0
fi
rm -rf ./build/*
sudo rm -rf /usr/local/lib/$1.*
sudo rm -rf /usr/lib/$1.*
sudo rm -rf /usr/local/include/$1
sudo rm -rf /usr/include/$1
echo "done!"
|
C# | UTF-8 | 844 | 3.453125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace problema5
{
class Program
{
static void Main(string[] args)
{
///5.Extrageti si afisati a k-a cifra de la sfarsitul unui numar.
///Cifrele se numara de la dreapta la stanga.
int nr = 0, n, k;
n = int.Parse(Console.ReadLine());
k = int.Parse(Console.ReadLine());
if (n == 0) Console.WriteLine(n);
else
while (n != 0)
{
if (nr == k)
Console.WriteLine(n % 10);
nr++;
n = n / 10;
}
Console.ReadKey();
}
}
}
|
Swift | UTF-8 | 480 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | //
// DiscographyMode.swift
// Metal Archives
//
// Created by Thanh-Nhon Nguyen on 20/06/2021.
//
import Foundation
enum DiscographyMode: Int, CustomStringConvertible, CaseIterable {
case complete = 0, main, lives, demos, misc
var description: String {
switch self {
case .complete: return "Complete"
case .main: return "Main"
case .lives: return "Lives"
case .demos: return "Demos"
case .misc: return "Misc."
}
}
}
|
TypeScript | UTF-8 | 379 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | /**
* Concentrates all the enumerations used by the graph to perform the transformation.
*
* Author: Gustavo L. Guidoni
*/
export enum AssociationType {
RELATION_TYPE = 'Relation',
GENERALIZATION_TYPE = 'Generalization',
GENERALIZATION_SET_TYPE = 'GeneralizationSet'
}
export enum Cardinality {
C1 = '1',
C0_1 = '0..1',
C1_N = '1..*',
C0_N = '0..*',
X = 'uninformed'
}
|
Markdown | UTF-8 | 1,965 | 2.890625 | 3 | [
"MIT"
] | permissive | ### Description
I have discovered an issue which is quite critical for our business - `CascadeInputTransparent` behaves differently on Android compared to the other platforms.
### Steps to Reproduce
1. Create a XAML page with the following content:
```
<Grid>
<Grid BackgroundColor="Blue" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped" />
</Grid.GestureRecognizers>
</Grid>
<Grid RowSpacing="0" ColumnSpacing="0" InputTransparent="True" CascadeInputTransparent="False">
<Grid BackgroundColor="Red" HorizontalOptions="Center" WidthRequest="300" VerticalOptions="Center" HeightRequest="300">
<Label>Parent - InputTransparent=True, CascadeInputTransparent=False</Label>
</Grid>
</Grid>
</Grid>
```
2. In the code-behind add the following `Tapped` event handler:
```
private void TapGestureRecognizer_OnTapped(object sender, EventArgs e)
{
Debug.WriteLine("Tap captured");
}
```
3. Run the app on Android, UWP and iOS
### Expected Behavior
Tapping the red rectangle should not fire the tapped event handler on the blue `Grid`.
### Actual Behavior
Tapping the red rectangle does not fire tapped event on the blue `Grid` on UWP and iOS, but it does fire on Android. The same goes for all other gestures.
In our project we have a map control instead of a `Grid` this behavior on Android causes that user can manipulate the map over any UI which is above the map, even if it has a solid background, which is not valid.
### Basic Information
- Version with issue: 3.0.0.482510
- Last known good version: -
- IDE: Visual Studio 15.7.2
- Platform Target Frameworks: <!-- All that apply -->
- iOS: 11.1
- Android: 8.1
- UWP: 16299
### Reproduction Link
Repro for the issue is [available here on my GitHub](https://github.com/MartinZikmund/Xamarin.Forms-input-inconsistency).
|
Java | UTF-8 | 1,962 | 2.8125 | 3 | [] | no_license | package Config;
import java.sql.*;
import java.util.*;
import javax.swing.JOptionPane;
public class connectionConfig {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String sql = null;
private static Connection MySQLConfig;
public static Connection configDB()throws SQLException{
try {
String url = "jdbc:mysql://localhost:3306/kuliah_siakad";
String user = "root";
String pass = "";
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
MySQLConfig = DriverManager.getConnection(url,user,pass);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Connection Failed: \n" + e.getMessage());
}
return MySQLConfig;
}
public connectionConfig(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/kuliah_siakad","root","");
st = con.createStatement();
} catch (Exception e){
JOptionPane.showMessageDialog(null, "Connection failed: \n"+e);
}
}
public List searchLogin(String username, String password){
List logLogin = new ArrayList();
int result;
sql = "select * from tbl_user where username='"+username+"' and password='"+password+"'";
try {
rs = st.executeQuery(sql);
while(rs.next()){
userConfig uc = new userConfig();
uc.setUsername(rs.getString("username"));
uc.setPassword(rs.getString("password"));
uc.setName(rs.getString("name"));
uc.setAccess(rs.getString("access"));
logLogin.add(uc);
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, "Login Failed: "+e);
}
return logLogin;
}
}
|
Markdown | UTF-8 | 1,071 | 2.84375 | 3 | [] | no_license | ## Frontity server with embedded files
This small proof of concept is a Node server that embeds Frontity's static files (like JavaScript files or images) in the server bundle.
The main goal is to be able to serve everything, including the client JavaScript files and small images, only with a serverless function, without the need to upload the static files to a different server.
## Usage
Run `npm start` to:
- Run `npx frontity build` to create both a `server.js` file and the `/static` files.
- Run Webpack to create an additional `serverless.js` file, which embeds the `server.js` and `/static` files from Frontity.
- Run `node serve.js` to start a small server that runs the `serverless.js` file simulating a serverless service.
Then visit http://localhost:3000 and Frontity should be working fine. I have added a special header `x-embedded` to the assets served by the `serverless.js` server.
**Note:** This is just a proof of concept not suited for production. This mechanish should be included in Frontity itself, without the need of an additional bundle.
|
Markdown | UTF-8 | 490 | 2.515625 | 3 | [] | no_license | 参考
https://www.cnblogs.com/grandyang/p/5727892.html
列出了三种处理办法,时间复杂度依次降低
1. 利用大堆根,建立 k 个元素的大根堆,堆顶元素最大,然后依次比较,当前元素比堆顶元素小,则将堆顶元素换出,当前元素入堆并调整堆。这个思路与大数据中的第 K 小一样。
2. 利用二分思想,关键还是利用矩阵的列有序的性质来进行
具体实现参加代码与前面链接页面的C++代码 |
PHP | UTF-8 | 1,209 | 2.984375 | 3 | [] | no_license | <?php
include_once '../../Database/dataConnect.php';
//Create class for user data
class userInfo extends dataConnect{
private $firstName;
private $lastName;
private $personId;
private $phoneNumber;
private $eMail;
public function __construct($firstName,$lastName,$personId,$phoneNumber,$eMail){
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->personId = $personId;
$this->phoneNumber = $phoneNumber;
$this->eMail = $eMail;
}
public function getName(){
return $this->firstName;
}
public function setName($firstName){
$this->firstName = $firstName;
}
public function getLastName(){
return $this->lastName;
}
public function setLastName($lastName){
$this->lastName = $lastName;
}
public function getPersonId(){
return $this->personId;
}
public function setPersonId($personId){
$this->personId = $personId;
}
public function getPhoneNumber(){
return $this->phoneNumber;
}
public function setPhoneNumber($phoneNumber){
$this->phoneNumber = $phoneNumber;
}
public function geteMail(){
return $this->eMail;
}
public function seteMail($eMail){
$this->eMail = $eMail;
}
}
|
TypeScript | UTF-8 | 829 | 4.21875 | 4 | [] | no_license | //Typescript - well - strong typing allows us to define types of our variables
let myString: string;
myString = `this is a string`;
//trying to assign a number to a string - myString, causes Error
myString = 4;
//TypeScript can also infer types
let anotherString = `this is a string without :string`;
anotherString = 7;
//if you do not initialize or specify a type, it is of type any
let yetAnotherString;
yetAnotherString = `this is a string`;
(<string>yetAnotherString)
yetAnotherString = 13;
//Other basic types
let aString: string;
let aNumber: number;
let aBoolean: boolean;
let anArray: Array<string>;
let anything: any;
//do not use, bad practice
let not: void;
let notAlso: undefined;
let notAgain: never;
let notForever: null;
not = undefined;
notForever = null;
notAgain = `this is definitly something`;
|
PHP | UTF-8 | 3,658 | 3 | 3 | [] | no_license | <?php
// require scraperwiki's HTML parsing script
require 'scraperwiki/simple_html_dom.php';
// define the URL you want to scrape
$html = scraperWiki::scrape("www.bbc.co.uk/news/uk-10629358");
$dom = new simple_html_dom();
$dom->load($html);
// select the table and data from that table
foreach($dom->find("table[@class='ba sortable'] tr") as $data){
$tds = $data->find("td");
// separate the military force from their regiment
$force = explode("<br />", $tds[4]);
// remove the text "Full story" from the incident entry
$incidenttext = str_replace("Full story", "", $tds[5]);
$incident = explode("</span>", $incidenttext);
// separate the location of the incident from the region
$location = explode("</span>", $tds[6]);
// separate the hometown from the home region
$birthplace = explode("<br />", $tds[3]);
// create the array
$record = array(
'birthregion' => strip_tags($birthplace[0]),
'birthcity' => strip_tags($birthplace[1]),
'force' => strip_tags($force[0]),
'servedwith' => strip_tags($force[1]),
'incidenttype' => strip_tags($incident[0]),
'incidentdetails' => html_entity_decode(strip_tags($incident[1])),
'location' => strip_tags($location[0]),
'locationdetail' => strip_tags($location[1]),
'name' => $tds[0]->plaintext,
'rank' => $tds[1]->plaintext,
'age' => $tds[2]->plaintext,
'date' => $tds[7]->plaintext
);
if ( $record['name'] == '' ) {
$record['name'] = 'No name specified';
}
// save array to scraperwiki, based on the 'Name' array, which will be checked every time scraperwiki updates
scraperwiki::save_sqlite(array('name'), $record);
}
// spare loop
/*
for ($i = 1; $i <= sizeof($record); $i++)
*/
?><?php
// require scraperwiki's HTML parsing script
require 'scraperwiki/simple_html_dom.php';
// define the URL you want to scrape
$html = scraperWiki::scrape("www.bbc.co.uk/news/uk-10629358");
$dom = new simple_html_dom();
$dom->load($html);
// select the table and data from that table
foreach($dom->find("table[@class='ba sortable'] tr") as $data){
$tds = $data->find("td");
// separate the military force from their regiment
$force = explode("<br />", $tds[4]);
// remove the text "Full story" from the incident entry
$incidenttext = str_replace("Full story", "", $tds[5]);
$incident = explode("</span>", $incidenttext);
// separate the location of the incident from the region
$location = explode("</span>", $tds[6]);
// separate the hometown from the home region
$birthplace = explode("<br />", $tds[3]);
// create the array
$record = array(
'birthregion' => strip_tags($birthplace[0]),
'birthcity' => strip_tags($birthplace[1]),
'force' => strip_tags($force[0]),
'servedwith' => strip_tags($force[1]),
'incidenttype' => strip_tags($incident[0]),
'incidentdetails' => html_entity_decode(strip_tags($incident[1])),
'location' => strip_tags($location[0]),
'locationdetail' => strip_tags($location[1]),
'name' => $tds[0]->plaintext,
'rank' => $tds[1]->plaintext,
'age' => $tds[2]->plaintext,
'date' => $tds[7]->plaintext
);
if ( $record['name'] == '' ) {
$record['name'] = 'No name specified';
}
// save array to scraperwiki, based on the 'Name' array, which will be checked every time scraperwiki updates
scraperwiki::save_sqlite(array('name'), $record);
}
// spare loop
/*
for ($i = 1; $i <= sizeof($record); $i++)
*/
?> |
Markdown | UTF-8 | 18,808 | 2.609375 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | > *The following text is extracted and transformed from the paycom.com privacy policy that was archived on 2019-05-29. Please check the [original snapshot on the Wayback Machine](https://web.archive.org/web/20190529113610id_/https%3A//paycom.com/privacy.php) for the most accurate reproduction.*
# Paycom Privacy Policies
Last modified: 05/22/2019
**INTRODUCTION** \- Paycom (“we”, “us”, or “our”) understands the need for transparency when it comes to the information we collect from visitors to and users of our website at [https://www.paycom.com](https://www.paycom.com/) (together with the mobile version of such site, and any related mobile applications, the “Website”). Accordingly, we have developed this Privacy Policy (this “policy”) to describe the types of information that we may collect from you, and our practices for collecting, using, maintaining, protecting and disclosing that information.
Please read this policy carefully to understand how we treat the information we collect. If you do not agree with this policy, your choice is to cease immediately your use of our Website. By accessing or using this Website, you agree to this policy. We may update this policy from time to time (see [Changes to Our Privacy Policy](https://web.archive.org/privacy.php#changes-to-our-privacy-policy)). Your continued use of this Website after we post any changes constitutes your acceptance of those changes, so please check the policy periodically for updates.
**INFORMATION WE COLLECT ABOUT YOU AND HOW WE COLLECT IT** \- We collect personal data that you voluntarily provide to us, such as name, postal address, e-mail address, telephone number, place of business and any other information that could be used to personally identify you (collectively, “personal data”). You may voluntarily provide personal data when you fill in forms on our Website, reach out to us directly by sending us correspondence, or use the Website to place orders or enter into any other transactions with us.
The Website and its servers may also collect other information from you, such as your industry, role in a business, and Human Resource needs, and technical information such as information regarding your internet connection, the hardware and software you use to access our Website, your IP address, page views, clicks, and other such information that does not personally identify you (collectively, “technical data”).
**AUTOMATIC DATA COLLECTION** \- We may use cookies, web beacons, pixels, and similar technologies to automatically collect certain information about your online activities over time and across third-party websites or other online services. See [Your Data Collection Choices](https://web.archive.org/privacy.php#data-collection-choices) for information on how you can opt out of and/or limit various tracking technologies. The technologies we use for this automatic data collection may include:
* _Cookies (or browser cookies)_. A cookie is a small file placed on the hard drive of your computer. You may refuse to accept browser cookies by activating the appropriate setting on your browser. However, if you select this setting you may be unable to access certain parts of our Website. Unless you have adjusted your browser setting so that it will refuse cookies, our system will issue cookies when you direct your browser to our Website.
* _Flash Cookies_. Certain features of our Website may use local stored objects (or Flash cookies) to collect and store information about your preferences and navigation to, from, and on our Website. Flash cookies are not managed by the same browser settings as are used for browser cookies. For information about managing your privacy and security settings for Flash cookies, see [Your Data Collection Choices](https://web.archive.org/privacy.php#data-collection-choices).
* Web Beacons. Pages of our Website and our e-mails may contain small electronic files known as web beacons (also referred to as clear gifs, pixel tags, and single-pixel gifs) that permit us, for example, to count users who have visited those pages or opened an email and for other related Website statistics (for example, recording the popularity of certain Website content and verifying system and server integrity).
We use information collected by the technologies described above, to help us improve our Website and to deliver a better and more personalized service, including by enabling us to:
* Estimate our audience size and usage patterns.
* Store information about your preferences, allowing us to customize our Website to your specific business needs.
* Speed up your searches.
* Recognize you when you return to our Website.
Some content or applications on the Website are served by third parties, including advertisers, ad networks and servers, content providers, and application providers. These third parties may use cookies alone or in conjunction with web beacons or other tracking technologies to collect information about you when you use our Website. The information they collect may be associated with your personal data or they may collect information, including personal data, about your online activities over time and across different websites and other online services. They may use this information to provide you with interest-based advertising or other targeted content. We do not control these third parties’ tracking technologies or how they may be used. If you have any questions about an advertisement, or other targeted content, you should contact the responsible provider directly. For information about how you can opt out of receiving targeted advertising from many providers, see [Your Data Collection Choices](https://web.archive.org/privacy.php#data-collection-choices).
**HOW WE USE YOUR INFORMATION** \- We may use personal data:
* to fulfill the purpose for which you provide it (for example to provide products, services, support, or information you request, to review your job application through our Careers page, or to respond to your correspondence or other requests);
* to carry out our obligations and enforce our rights arising from any contracts entered into between you and us, including for billing and collection;
* to contact you regarding any transactions you’ve entered into with us;
* to notify you about changes to our Website or any products or services we offer or provide through it; or
* in any other way we may describe when you provide the information, or for which you provide consent.
We may also use your information to market, advertise, promote or otherwise contact you about our products and services. If you do not want us to use your information in this way, see [Your Data Collection Choices](https://web.archive.org/privacy.php#data-collection-choices) for instructions on how to opt out of these communications. We may use technical data, which does not identify you personally, in any way we deem appropriate.
**DISCLOSURE OF YOUR INFORMATION** \- We may disclose personal data:
* to our subsidiaries and affiliates;
* to contractors, service providers, and other third parties who support our business operations (e.g., payment processors, sales or support representatives, hosting providers, marketing partners, and other business consultants) who are bound by contractual obligations to keep personal data confidential and use it only for the purposes for which we disclose it to them;
* to a buyer or other successor in the event of a merger, divestiture, restructuring, reorganization, dissolution, or other sale or transfer of some or all of our assets, whether as a going concern or as part of bankruptcy, liquidation, or similar proceeding, in which personal data held by us is among the assets transferred;
* any other entity disclosed by us when you provide the information, or for which you provide consent; or
* to comply with any court order, law, or legal process, including to respond to any government or regulatory request, to enforce or apply our website policies and other agreements, for billing and collection purposes, or if we believe disclosure is necessary or appropriate to protect our rights, property, or safety or that of our customers or others. This includes exchanging information with other companies and organizations for the purposes of fraud protection and credit risk reduction.
**YOUR DATA COLLECTION CHOICES** \- We strive to provide you with choices regarding the personal data you provide to us. We have created mechanisms to provide you with the following control over your information:
* _Tracking Technologies_. You can set your browser to refuse all or some browser cookies, or to alert you when cookies are being sent. To learn how you can manage your Flash cookie settings, visit the Flash player settings page on Adobe’s [website](https://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager07.html). If you disable or refuse cookies, please note that some parts of this site may then be inaccessible or not function properly.
* _Location_. Mobile applications may collect real-time information about the location of your device for geofencing, mileage tracking or similar purposes. If you do not want us to collect this information, you may decline our request or disable location services in your mobile device’s settings. However, opting out of the collection of location information will cause location-based features to be disabled and the online and/or mobile application may not function properly. We may also offer clients an option to use your approximate clock-in location based off an IP address. You may also opt out of this method via the application’s settings, however, opting out will interfere with the application’s functionality.
* _Stored Information and Files_. Our mobile application also may access metadata and other information associated with other files stored on your device. This may include, for example, photographs, audio and video clips, personal contacts, and address book information. You may opt out of this data collection in your mobile device’s settings, however, opting out will interfere with the application’s functionality.
* _Your Information and Third-Party Advertising_. We do not control third parties’ collection or use of your information to serve interest-based advertising. However, these third parties may provide you with ways to choose not to have your information collected or used in this way. You can opt out of receiving targeted ads from members of the Network Advertising Initiative (“NAI”) [https://optout.networkadvertising.org](https://optout.networkadvertising.org/) on the NAI’s website. You can opt out of receiving interest-based advertising from members of the Digital Advertising Alliance by utilizing their consumer choice tool at [https://optout.aboutads.info](https://optout.aboutads.info/). You can also opt-out by adjusting your internet and/or mobile browser preferences.
* _Promotional Offers from Paycom_. If you do not wish to have your email address or other contact information used by Paycom to promote our own or third parties’ products or services, you can opt out at any other time by sending us an email stating your request to [privacy@paycom.com](mailto:privacy@paycom.com). If we have sent you a promotional email, you may opt out using the unsubscribe or opt-out link in the email, if applicable, or by sending us a return email asking to be omitted from future email distributions. This opt-out does not apply to information provided to Paycom as a result of a product or service purchase, product service experience or other transactions.
* _Do Not Track Signals_. The Website currently does not recognize or respond to browser “do not track” signals.
* _Twitter_. One of the third parties we may use for advertising purposes is Twitter, Inc. Information about how Twitter uses data and how you may choose what information is collected may be found at [https://support.twitter.com/articles/20170405#](https://support.twitter.com/articles/20170405)
* _Google Analytics_. One of the third-party services we use for advertising purposes is Google Analytics. Information about how Google Analytics uses data can be found at [google.com/policies/privacy/partners/](https://www.google.com/policies/privacy/partners/).
* _YouTube API Services_. One of the third-party services we use for audiovisual content viewing is the YouTube API Services. Information about the YouTube API Services can be found at <https://developers.google.com/youtube/terms/api-services-terms-of-service>. By using the features of the Website utilizing the YouTube API Services, you agree to be bound by the YouTube Terms of Service, found at https://www.youtube.com/t/terms.
If you would like to access or correct your personal data, you may do so by visiting your account profile (if you have one) or by contacting us at [privacy@paycom.com](mailto:privacy@paycom.com).
**CHILDREN UNDER THE AGE OF 13** \- Our Website is not intended for children under 13 years of age. We do not knowingly collect personal data from children under 13. If you are under 13, do not use or provide any information on this Website or on or through any of its features/register on the Website, make any purchases through the Website, use any of the interactive or public comment features of this Website or provide any information about yourself to us, including your name, address, telephone number, email address, or any screen name or username you may use. If we learn we have collected or received personal data from a child under 13, we will promptly take commercially reasonable steps to delete that information. If you believe we might have any information from or about a child under 13, please contact us at [privacy@paycom.com](mailto:privacy@paycom.com).
**YOUR CALIFORNIA PRIVACY RIGHTS** \- California Civil Code Section § 1798.83 permits Website users that are California residents to request certain information regarding the disclosure of personal data to third parties for direct marketing purposes. To make such a request, please send an email to [privacy@paycom.com](mailto:privacy@paycom.com).
**DATA SECURITY** \- We have implemented at least industry standard measures designed to secure your personal data from accidental loss and from unauthorized access, use, alteration, and disclosure. The safety and security of your information also depends on you. You are responsible for keeping your username, password, and any other login credentials or user verification information confidential. You may not share this information with anyone. Unfortunately, the transmission of information via the internet is not completely secure, so we cannot guarantee the security of your personal data transmitted to our Website. Any transmission of personal data is at your own risk. We are not responsible for circumvention of any privacy settings or security measures contained on the Website.
In order to protect you and your data and that of our other users, we may suspend your access to the Website without notice, pending an investigation, if any breach of security is suspected.
For more information on our IT security practices, [click here](https://web.archive.org/PDF/SecurityStandards.pdf?v=2).
**CHANGES TO OUR PRIVACY POLICY** \- For any changes we make to this policy, including making material changes to how we treat our users’ personal data, we will post an updated policy on this page, along with a notice that the privacy policy has been updated on the Website home page. The date the privacy policy was last revised is identified at the top of the page. Please be aware, you are responsible for inspecting our website to make yourself up-to-date with our privacy policy.
**CLIENT DATA** \- We receive non-public personal data from or on behalf of our clients (employers) and their personnel regarding their personnel and their personnel’s dependents and family members. Such information is required for us to effectively provide our services to our clients, and may include Social Security numbers, payroll information, tax information, biometric information (such as retina or iris scans, fingerprint scans, voiceprints, scans of hand or face geometry, or other similar biometric identifiers), and other information our clients may provide in order for us to perform our services (collectively, “client data”). Although Paycom may use technical data for various purposes as described in this policy, as further specified in this “Client Data” section of this policy, Paycom will not share client data with a third party unless it is necessary to provide services on behalf of our clients. We use at least industry-standard security policies and measures to help prevent any unauthorized access to client data.
We process, use, and share client data as instructed or permitted by the applicable client. We may transmit client data over international borders as necessary for providing our services in accordance with our standard business practices and this policy, but we will maintain reasonable security policies regardless of where client data is stored or processed.
We will share any client data with the client and any third parties as instructed or permitted by the client. We may also share client data with other third-party data processors who facilitate our provision of the services requested by the client and who are prohibited from using client data except for such purpose. We may also be required to share client data with applicable government entities (for example, the IRS, state unemployment agencies, state income agencies, workers compensation auditors, 401(k) administrators and entities who participate in the NACHA program for funds transfer purposes) or as otherwise required by law.
Our clients may transmit their personnel’s biometric information to Paycom. Biometric information is stored while the employee is active within the Paycom system. Biometric information not tied to our clients' personnel or tied to our clients' personnel that are inactive within our system are permanently deleted from our servers on a nightly basis. Absent a valid warrant or subpoena issued by a court of competent jurisdiction, Paycom’s retention and destruction standards for fingerscan templates will be followed.
If you are one of our clients’ personnel, or the dependent or family member of one of our clients’ personnel, and you have any questions or concerns regarding your personal data or your privacy rights, or you would like to access or correct your personal data, please contact your employer.
**CONTACT INFORMATION** \- To ask questions or comment about this privacy policy and our privacy practices, contact us at: [privacy@paycom.com](mailto:privacy@paycom.com).
|
TypeScript | UTF-8 | 294 | 2.71875 | 3 | [
"MIT"
] | permissive | export default function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = window.atob(base64)
const len = binaryString.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
return bytes.buffer
}
|
Swift | UTF-8 | 1,282 | 2.578125 | 3 | [] | no_license | //
// SignalProducer+CADisplayLink.swift
// Pong
//
// Created by Nikita Belousov on 27.10.2019.
// Copyright © 2019 Nikita Belousov. All rights reserved.
//
import ReactiveSwift
import ReactiveCocoa
class DisplayLinkProxy: NSObject {
private let observer: Signal<TimeInterval, Never>.Observer
init(observer: Signal<TimeInterval, Never>.Observer) {
self.observer = observer
}
func keepInMemory() {}
@objc func step(displayLink: CADisplayLink) {
observer.send(value: displayLink.duration)
}
}
extension SignalProducer where Value == TimeInterval, Error == Never {
static func displayLink() -> SignalProducer<TimeInterval, Never> {
return SignalProducer<TimeInterval, Never>() { observer, lifetime in
let proxy = DisplayLinkProxy(observer: observer)
let displayLink = CADisplayLink(target: proxy, selector: #selector(DisplayLinkProxy.step(displayLink:)))
displayLink.add(to: .main, forMode: .default)
lifetime += AnyDisposable {
proxy.keepInMemory()
}
lifetime.observeEnded {
displayLink.invalidate()
}
}
}
}
|
PHP | UTF-8 | 3,419 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ALLOCATE TO STUDENT</title>
</head>
<body>
<?php include('header.php');
$resultSet=$conn->query("SELECT courses FROM tbl_courses");
?>
<div class="container">
<div class="row">
<div class="col">
<?php
$id=$_GET['id'];
$regno="SELECT regno,department FROM students WHERE file_no=$id";
$sql=$conn->query($regno);
if($sql->num_rows>0){
$row=$sql->fetch_assoc();
$file_no= strtoupper($row['regno']);
$department= strtoupper($row['department']);
}
$err_msg=$success="";
if(isset($_POST["add_dept"])){
$department=$_POST['department'];
$sql="INSERT INTO tbl_department(department) VALUES(?)";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$department);
if($stmt->execute()){
$success="new record inserted";
}else{
$err_msg="Oops , something went wrong";
}
}
$regno="SELECT regno,department FROM students WHERE file_no=$id";
$sql=$conn->query($regno);
if($sql->num_rows>0){
$row=$sql->fetch_assoc();
$file_no= strtoupper($row['regno']);
$department= strtoupper($row['department']);
}
$err_msg=$success="";
if(isset($_POST['allocate'])){
$courses=$_POST['courses'];
$sql="SELECT regno, course FROM tbl_allocate WHERE course=? AND regno=?";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ss',$courses,$file_no);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows >0){
$err_msg= "subject already exist! Please choose another";
}else{
$sql="INSERT INTO tbl_allocate(department,regno,course) VALUES(?,?,?)";
$stmt=$conn->prepare($sql);
$stmt->bind_param('sss',$department,$file_no,$courses);
if($stmt->execute()){
$success= "Inserted";
}
}
}
$conn->close();
?>
<form action="" method="post" class="text-center">
<div class="text-danger"><?php echo $err_msg ?></div>
<div class="text-success"><?php echo $success ?></div>
<br>
<div class="alert alert-primary pt-3"><?php echo $file_no ?></div>
<br>
<div class="alert alert-primary pt-3"><?php echo $department ?> - DEPARTMENT</div>
<br>
<select name="courses" class="form-select form-select-lg mb-3">
<?php
echo "<option disabled selected>Allocate course</option>";
while($rows = $resultSet->fetch_assoc()){
$courses=$rows['courses'];
echo "
<option value='$courses'>$courses</option>";
}
?>
</select>
<br>
<INPUT type="submit" value="ALLOCATE" class="btn btn-primary" name="allocate">
</form>
</div>
</div>
</div>
</body>
</html> |
Markdown | UTF-8 | 880 | 2.96875 | 3 | [] | no_license | # java.js
An object oriented JavaScript Framework that is similar to Java.
The objective is to create a framework that eases the transition of a Java programmer (or other programmer) into web design by familiar association. Also, the goal is to create a framework that makes web application design easier and more standardized like swing does for Java.
example of usage
```html
<script src="java.js/Frame.js"></script>
<script src="java.js/MenuBar.js"></script>
<script src="java.js/MenuItem.js"></script>
<script src="java.js/Menu.js"></script>
<body>
<div id="content"></div>
</body>
<script>
var con = new Frame('content');
var menu = new MenuBar();
var home = new MenuItem("Sites");
var item = new Menu("Commodore");
var esohp = new Menu("EShop");
home.add(item);
home.add(esohp);
menu.add(home);
con.add(menu);
</script>
```
Would add a menu bar at the top of the page.
|
Markdown | UTF-8 | 2,527 | 2.84375 | 3 | [] | no_license | # AudenTestRepo
## Contents
- [Tools Used](#Tools-Used)
- [Reasoning](#Reasoning)
- [Issues Faced](#Issues-Faced)
- [Next Steps](#Next-Steps)
### Tools Used
- Visual Studio
- Selenium Webdriver
- Selenium Chromedriver
- NUnit
- Specflow
- SpecRunner
- Git
- GitHub
### Reasoning
I have created three Scenarios as I felt like this was the minimum needed to satisfy the criteria required. I would continue to expand on these to add more variety if I was to spend a large amount of time on this as well as increase the amount Assertions and add in any other checks. The scenarios I used were a test using the minimum amount the slider could be. The Same again for the maximum value and finally one which sets teh value and attempts to set the payment date to be on a weekend to verify if it is possible.
To accomplish the task I have used a combination of Selenium, NUnit and Specflow as these are the main tools required for automating any webbased application using BDD (Behaviour Driven Development). Although other tools are available I am the most comfortable with these which helped speed up the setting of this project. I created the project in C# using Visual Studio as I had it readily available on the Machine I was working on. I also used Git and GitHub as my VCS to make life a bit easier with any transfers accross machines that need to happen.
### Issues Faced
So for this project I faced on issue mainly which was the automation of the slider. As I couldn't quite it to move the way I wanted it to. Hopefully what I was trying to do comes across but I decided to focus more on getting the MVP done and come back to the issue.
I had a small issue with running the tests as visual studio took a while to realise that they were there. This could be due to the fact I don't have as much experience with Visual studio than other IDE's.
### Next Steps
If I was to continue working on this project my first task would be to resolve the issue faced with moving the slider. I believe I must be missing something but haven't determined what it is. Yet. Along those Lines I would also add some more varied scenarios in as well. I did notice that there were some radio buttons that appeared for certain dates so I would need to add int he functionalit to cater for them as well but they appeared to be uncommon which is why I haven't already added them in although I have the solution already in mind.'
I would also add in additional checks for the repayments at the bottom to make sure all those values are checked. |
Swift | UTF-8 | 3,767 | 3.0625 | 3 | [] | no_license | //
// RatingView.swift
// Pebl2
//
// Created by Nick Florin on 1/7/17.
// Copyright © 2017 Nick Florin. All rights reserved.
//
import UIKit
////////////////////////////////////////////////////////////////////////
class RatingView: UIView {
var rating : CGFloat!
var orientation : String = "left" // Default
var starColor : UIColor = light_blue
var starMaskColor : UIColor = UIColor.white
/////////////////////////////////////
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.backgroundColor = UIColor.clear
}
override func layoutSubviews() {
if self.rating != nil {
self.applyRating(rating: self.rating)
}
}
/////////////////////////////////////
func applyRating(rating:CGFloat){
self.rating = rating
let imageWidth : CGFloat = self.bounds.height
var halfStar : Bool = false
let intRating = Int(floor(self.rating)) // Round down rating to nearest int
if intRating % 2 != 0 { // Odd Number
halfStar = true
}
// Determine X Starting Position
let numStars = Int(floor(self.rating/2.0))
for i in 0...numStars{
var startX : CGFloat!
var useHalfStar : Bool = false
// Right orientation by default, starts drawing star rating from right of frame
if self.orientation == "right"{
startX = self.bounds.width - CGFloat(i+1)*imageWidth
if halfStar && i == 0{ // Last star but first star drawn
useHalfStar = true
}
}
// Left orientation starts drawing star rating from left of frame
else{
startX = self.bounds.minX + CGFloat(i)*imageWidth
if halfStar && i == numStars{ // Last star and last star drawn
useHalfStar = true
}
}
self.drawStarLayer(startX: startX)
if useHalfStar == true { // Odd Number
self.maskStar(startX: startX)
}
}
}
/////////////////////////////////////
// Creates a Mask for Star to Make Half Star
func maskStar(startX:CGFloat){
let frame = CGRect(x:startX + 0.5*self.bounds.height,y:self.bounds.minY,width:self.bounds.height,height:self.bounds.height)
// Create Layers for Horizontal and Vertical Portions
let layer = CAShapeLayer()
let path = UIBezierPath(rect: frame)
layer.path = path.cgPath
layer.fillColor = starMaskColor.cgColor
layer.strokeColor = nil
self.layer.addSublayer(layer)
}
/////////////////////////////////////
// Draws the Layer for a Single Star
func drawStarLayer(startX:CGFloat){
let frame = CGRect(x:startX,y:self.bounds.minY,width:self.bounds.height,height:self.bounds.height)
// Create Layers for Horizontal and Vertical Portions
let layer = CAShapeLayer()
let path = UIBezierPath()
let w = frame.width
let r : CGFloat = 0.5*w
let theta : CGFloat = 2.0 * CGFloat(M_PI) * (2.0 / 5.0)
let flip : CGFloat = -1.0
let xCenter : CGFloat = startX + 0.5*w
path.move(to: CGPoint(x:xCenter,y:r*flip+r))
for k in 1...5 {
let x = r*sin(CGFloat(k)*theta)
let y = r*cos(CGFloat(k)*theta)
path.addLine(to: CGPoint(x: x+xCenter, y: y*flip+r))
}
layer.path = path.cgPath
layer.fillColor = starColor.cgColor
layer.strokeColor = nil
self.layer.addSublayer(layer)
}
}
|
Java | UTF-8 | 2,833 | 2.359375 | 2 | [] | no_license | package at.technikum.masterproject.customerservice.controlleradvice;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import at.technikum.masterproject.commons.responses.ErrorResponse;
import at.technikum.masterproject.commons.responses.ValidationErrorResponse;
import at.technikum.masterproject.customerservice.customerinformation.model.CustomerNotFoundException;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
@Slf4j
public class CommonControllerAdvice {
private static final String GENERIC_ERROR_MESSAGE = "Could not handle request. An error occurred.";
@ExceptionHandler(CustomerNotFoundException.class)
public ResponseEntity<ErrorResponse> handleCustomerNotFoundException(CustomerNotFoundException ex,
HttpServletRequest request) {
log.warn("Requested Customer was not found.");
return ResponseEntity
.status(NOT_FOUND)
.body(ErrorResponse.withMessage("Customer not found"));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ValidationErrorResponse> handleInvalidInput(MethodArgumentNotValidException ex,
HttpServletRequest request) {
log.warn("Invalid input for request {} {}.", request.getMethod(), request.getRequestURI());
return ResponseEntity
.status(BAD_REQUEST)
.body(ValidationErrorResponse.forException(ex));
}
@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<ErrorResponse> handleBadCredentialsException(BadCredentialsException ex,
HttpServletRequest request) {
log.warn("Invalid Credentials were used.");
return ResponseEntity
.status(FORBIDDEN)
.body(ErrorResponse.withMessage("Invalid Credentials."));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex, HttpServletRequest request) {
log.error(generateLogEntry(request, ex));
return ResponseEntity
.status(INTERNAL_SERVER_ERROR)
.body(ErrorResponse.withMessage(GENERIC_ERROR_MESSAGE));
}
private String generateLogEntry(HttpServletRequest request, Exception ex) {
return String.format("An error occurred while handling %s%s: %s",
request.getMethod(), request.getRequestURI(), ex.getMessage());
}
}
|
JavaScript | UTF-8 | 2,753 | 2.609375 | 3 | [] | no_license | /**
* MapObject class
*/
define(['layers/ImageLayer', 'Loadable', 'utils', 'map/MapObjectLayerBehavior'], function (ImageLayer, Loadable, utils, MapObjectLayerBehavior) {
/**
* @param config
*/
var MapObject = function (config) {
this._onLoad = [];
if (config) merge(this, config);
this._initLayer();
};
var Me = MapObject;
MapObject.prototype = {
/* ===============Defaults============== */
layer:null,
description:'No info',
/**
* @var bool|string|array
* true: can pass any case
* false: can't pass any case
* MapCell.movementTypes.fly -- fly only (add limitations for all other)
* [MapCell.movementTypes.fly, MapCell.movementTypes.walk] (add limitations for all other, no swim in this case)
*/
passable:false, //@todo rename to isPassable
/* =============End defaults============= */
placeTo:function (map, x, y) {
var self = this;
this.map = map;
this.mapCell = map.cells[x][y];
this.mapCell.onLoad(function (cell) {
self.onLoad(function () {
self.layer
.setParent(map.layer)
.setOffset(cell.layer.offset)
.update();
})
});
map.objects.push(this);
return this;
},
_initLayer:function () {
// @todo Replace to some abstract layer
ImageLayer.create(this.layer).done(function (layer) {
MapObjectLayerBehavior(this, layer)
this.layer = layer;
this.ready = true;
this._doOnLoad();
}.bind(this));
},
onLoad:function (callback) {
if (!this.ready)
this._onLoad.push(callback);
else
callback(this);
},
/**
* Execute onload handlers
*/
_doOnLoad:function () {
for (var i = 0; i < this._onLoad.length; i++) {
this._onLoad[i](this);
}
},
destroy:function () {
if (this.map && this.map.objects) {
utils.removeFromArray(this, this.map.objects)
}
if (this.layer && this.layer.destroy) {
this.layer.destroy();
}
},
select:function () {
//@todo
console.log('selected!');
},
getInfo:function () {
return this.description;
}
}
return MapObject;
}); |
JavaScript | UTF-8 | 908 | 4.375 | 4 | [] | no_license | // 3) If you have a stream that receives individual values and would like to pipe it such that it builds an array out of these values, emitting the updated array each time a new value is added to it, how would you do this? Please provide a code example.
// E.g.
// 1 -> 2 -> 3 -> 4
// Should produce:
// [1] -> [1,2] -> [1,2,3] -> [1,2,3,4]
// Answer :
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { from } from 'rxjs';
const numbers = from([1,2,3,4]);
let someArray = [];
const finalArray= numbers.pipe(take(4));
finalArray.subscribe(x =>{
someArray.push(x);
console.log(someArray)
});
// Alternative Way
import { interval, from } from 'rxjs';
import { take } from 'rxjs/operators';
const numbers = interval(1000);
let someArray = [];
const finalArray= numbers.pipe(take(4));
finalArray.subscribe(x =>{
someArray.push(x + 1);
console.log(someArray)
});
|
Java | UTF-8 | 628 | 3.25 | 3 | [] | no_license | package InterfaceDemo;
public class AdvancedCal implements InterfaceCal{
public static void main(String[] args) {
AdvancedCal obj=new AdvancedCal() ;
obj.calculateCos();
obj.calculateSin();
obj.add();
obj.sub();
}
public void calculateCos()
{
System.out.println("this method is from calculateCos");
}
public void calculateSin()
{
System.out.println("This method is from calculateSin");
}
@Override
public void add() {
System.out.println("This method is from add");
}
@Override
public void sub() {
System.out.println("This method is from sub");
}
}
|
C# | UTF-8 | 2,305 | 3.265625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FuelCalculator.Models;
namespace FuelCalculator.Modules.Cars.Models
{
/// <summary>
/// Model do widoku z listą samochodów
/// </summary>
public class CarListEntry
{
/// <summary>
/// Konstruktor
/// </summary>
public CarListEntry()
{
RefuelingList = new List<Refueling>();
}
/// <summary>
/// Samochód
/// </summary>
public Car Car { get; set; }
/// <summary>
/// Lista tankowań
/// </summary>
public List<Refueling> RefuelingList { get; set; }
/// <summary>
/// Geter do wyświetlenia wartości
/// </summary>
public string Engine { get { return " [" + Car.Engine + "]"; } }
/// <summary>
/// Data utworzenia w systemie
/// </summary>
public string CreateTime { get { return Car.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"); } }
/// <summary>
/// Ilość tankowań
/// </summary>
public string FuelingCount { get { return RefuelingList.Count.ToString(); } }
/// <summary>
/// Wydana gotówka na paliwo
/// </summary>
public string FullCash { get { return RefuelingList.Sum(p => p.Price).ToString("n2"); } }
/// <summary>
/// Ilość paliwa na ilość przejechanych kilometrów
/// </summary>
public string FuelPerKilometers
{
get
{
return RefuelingList.Sum(p => p.FuelAmount).ToString("n2") + " / " + RefuelingList.Sum(p => p.Distance).ToString("n2");
}
}
/// <summary>
/// Średnie spalanie
/// </summary>
public string AverageFuel
{
get
{
if (RefuelingList.Count == 0)
return "Brak danych";
decimal fuelAmount = RefuelingList.Sum(p => p.FuelAmount);
decimal distance = RefuelingList.Sum(p => p.Distance);
if (distance == 0)
return "Błędne dane!";
return ((fuelAmount / distance) * 100).ToString("n2");
}
}
}
}
|
JavaScript | UTF-8 | 7,269 | 3.109375 | 3 | [] | no_license |
var startDate = document.getElementById('start-date'),
startTime = document.getElementById('start'),
duration = document.getElementById('duration-select'),
selectedDuration = getSelectedOption(duration).text,
finishDateAndTime = document.getElementById('end'),
deleteButton = document.querySelector('.delete'),
validationpara = document.getElementById('validationalert')
document.getElementById('form').addEventListener('submit',function(e) {
calculateFinishTime()
e.preventDefault();
})
function getSelectedOption(select) {
var opt;
for ( var i = 0, len = select.options.length; i < len; i++ ) {
option = select.options[i];
if ( option.selected === true ) {
break;
}
}
return option;
}
function calculateFinishTime() {
var startDate = document.getElementById('start-date'),
startTime = document.getElementById('start'),
duration = document.getElementById('duration-select'),
selectedDuration = getSelectedOption(duration).text,
finishDateAndTime = document.getElementById('end')
finishDate = document.getElementById('end-date')
finishTime = document.getElementById('end-time')
if(startDate.value === '' || startTime.value === ''|| selectedDuration === 'choose fasting duration'){
var validationpara = document.getElementById('validationalert')
validationpara.innerHTML = 'please enter valid start dates, times or duration'
setTimeout(clearValidationParagraph, 3000)
console.log(startDate.value)
function clearValidationParagraph (){
validationpara.innerHTML = ''}
}else{
let m = new Date(`${startDate.value}:${startTime.value}`)
var m2 = m.setTime(m.getTime() + (selectedDuration * 60 * 60 * 1000))
m3 = new Date(m2)
console.log(m3.toString())
var NewMonth;
if (m3.getMonth() < 10){
NewMonth = ('0'+ (m3.getMonth() + 1))
}else{
NewMonth = (m3.getMonth() + 1)
}
var NewDate;
if (m3.getDate() < 10){
NewDate = '0'+ m3.getDate()
}else{
NewDate = m3.getDate()
}
var newYear = m3.getFullYear()
var newHours = m3.getHours()
if (m3.getHours() < 10){
newHours = '0' + m3.getHours()
}else{
newHours = m3.getHours()
}
var newMinutes;
if (m3.getMinutes() < 10) {
newMinutes = '0' + m3.getMinutes()
}else{
newMinutes =m3.getMinutes()
}
console.log(newYear, NewMonth, NewDate)
finishDate.value = (`${newYear}-${NewMonth}-${NewDate}`)
finishTime.value = (`${newHours}:${newMinutes}`)
console.log(finishTime.value)
addFastToList(startDate.value,startTime.value, selectedDuration, finishDate.value, finishTime.value)
//getFastFromLocalStorage()
}
//getFastFromLocalStorage()
}
function addFastToList(startdate, starttime, duration, enddate, endtime){
const list = document.getElementById('individual-fasts')
const row = document.createElement('tr')
if (totalNumberOfRows >=5 ){
return
}else{
row.innerHTML = `<td >${startdate}</td>
<td>${starttime}</td>
<td>${duration}</td>
<td>${enddate}</td>
<td >${endtime}</td>
<td class = 'delete'>X</td>`
list.appendChild(row)
}
var totalNumberOfRows = CountRows()
console.log(totalNumberOfRows)
function CountRows() {
var totalRowCount = 0;
var rowCount = 0;
var table = document.getElementById("individual-fasts");
var rows = table.getElementsByTagName("tr")
for (var i = 0; i < rows.length; i++) {
totalRowCount++;
if (rows[i].getElementsByTagName("td").length > 0) {
rowCount++;
}
}
return totalRowCount
}
storeFastInLocalStorage(startdate, starttime, duration, enddate, endtime)
setTimeout(clearFields, 2000)
}
function clearFields (){
startDate.value = ''
startTime.value = ''
finishTime.value =''
finishDate.value = ''
duration.value = ''
}
function storeFastInLocalStorage(startdate, starttime, duration, enddate, endtime){
fastperiod = [startdate, starttime, duration, enddate, endtime]
let fasts;
if(localStorage.getItem('fasts') === null){
fasts = []
}else{
fasts = JSON.parse(localStorage.getItem('fasts'))
}
if (fasts.length >= 5) {
var validationpara = document.getElementById('validationalert')
validationpara.innerHTML = 'a maximum of 5 fasts periods are allowed'
setTimeout(clearValidationParagraph, 3000)
console.log(startDate.value)
function clearValidationParagraph (){
validationpara.innerHTML = ''}
return fasts
}else{
fasts.push(fastperiod)
localStorage.setItem('fasts', JSON.stringify(fasts))
console.log(fasts.length)
}
}
function getFastFromLocalStorage(){
let fasts;
if(localStorage.getItem('fasts')=== null){
fasts =[]
}
else{
fasts = JSON.parse(localStorage.getItem('fasts'))
}
fasts.forEach(function(fast){
const list = document.getElementById('individual-fasts')
const row = document.createElement('tr')
row.innerHTML =
`<td>${fast[0]}</td>
<td>${fast[1]}</td>
<td>${fast[2]}</td>
<td>${fast[3]}</td>
<td>${fast[4]}</td>
<td class = 'delete'>X</td>`
list.appendChild(row)
console.log(fasts)
})
}
document.addEventListener('DOMContentLoaded', getFastFromLocalStorage)
var deleteFastRecord = document.querySelector('.fast-records')
deleteFastRecord.addEventListener('click', onDeleteRow)
function onDeleteRow(e){
if(! e.target.classList.contains('delete'))
{
return
}
const btn = e.target;
btn.closest('tr').remove()
console.log(btn.closest('tr'))
removeFastPeriodFromLocalStorage(btn.closest('tr'))
}
function removeFastPeriodFromLocalStorage(fast){
let fasts ;
if(localStorage.getItem('fasts') === null){
fasts = []
}else{
fasts = JSON.parse(localStorage.getItem('fasts'));
}
fasts.forEach(function(fast, index){
if(fast === fast){
fasts.splice(index,1);
console.log(fast)
}
})
localStorage.setItem('fasts', JSON.stringify(fasts));
} |
JavaScript | UTF-8 | 2,142 | 3.15625 | 3 | [] | no_license | //create a new product
//find a product by id
//get all products
//update a product by id
//remove a product
//remove all products
const conn = require('./dbConfig')
const Product = function(product) {
this.title = product.title;
this.image = product.image;
this.price = product.price;
this.rating = product.rating;
}
Product.create = (newProduct, result) => {
conn.query('INSERT INTO products SET ?', newProduct, (err, res) => {
if(err) {
console.log(`Error: ${err}`)
result(err, null)
return;
}
console.log("created product: ", {id: res.insertId, ...newProduct});
result(null, {id: res.insertId, ...newProduct});
});
};
Product.findById = (productId, result) => {
conn.query(`SELECT * FROM products WHERE id = ${productId}`, (err, res) => {
if(err) {
console.log(`Error: ${err}`);
result(err, null);
return;
}
if(res.length) {
console.log("Found product: ", res[0]);
result(null, res[0]);
return;
}
//case no product found
result({kind: "not found"}, null);
})
}
Product.getAll = result => {
conn.query("SELECT * FROM products", (err, res) => {
if(err) {
console.log(`Error: ${err}`);
result(err, null);
return;
}
console.log(`Products: ${res}`);
result(null, res)
})
}
Product.updateById = (productId, productData, result) => {
conn.query("UPDATE products SET title = ?, image = ?, price = ?, rating = ? WHERE id = ?", [productData.title, productData.image, productData.price, productData.rating, productId], (err, res) => {
if(err) {
console.log(`Error: ${err}`);
result(err, null);
return;
}
if(res.affectedRows == 0) {
result({kind: "not found"}, null)
return
}
console.log("updated product ", {id: id, ...productData})
result(null, {id: id, ...productData})
})
}
module.exports = Product |
PHP | UTF-8 | 1,626 | 2.640625 | 3 | [] | no_license | <?php
include ("includes/connection.php");
if(isset($_POST['sign_up'])){
$name = htmlentities(mysqli_real_escape_string($con,$_POST['user_name']));
$pass = htmlentities(mysqli_real_escape_string($con,$_POST['user_pass']));
$email = htmlentities(mysqli_real_escape_string($con,$_POST['user_email']));
$country = htmlentities(mysqli_real_escape_string($con,$_POST['user_country']));
$gender = htmlentities(mysqli_real_escape_string($con,$_POST['user_gender']));
$rand= rand(1, 2);
if($name == ''){
echo"<script>alert('we cannot verify your name')</script>";
}
if(strlen($pass)<8){
echo"<script>alert('Passwords should be minimum 8 character')</script>";
exit();
}
$check_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con, $check_email);
$check= mysqli_num_rows($run_email);
if($check==1)
{
echo"<script>alert('Email doesnot exist')</script>";
echo"<script>window.open('signup.php','_self')</script>";
exit();
}
if($rand==1){
$profile_pic ="images/img1.jpg";
}
else if($rand==2){
$profile_pic ="images/img4.jpg";
}
$insert = "insert into users(user_name,user_pass,user_email,user_profile,user_country,user_gender ) values('$name','$pass', '$email','$profile_pic', '$country', '$gender')";
$query = mysqli_query($con, $insert);
if($query){
echo"<script>alert('Congratulations $name , your account has been created successfully')</script>";
echo"<script>window.open('signin.php','_self')</script>";
}
else{
echo"<script>alert('Sorry Registration Failed.Try again')</script>";
echo"<script>window.open('signup.php','_self')</script>";
}
}
?>
|
Java | UTF-8 | 9,419 | 1.71875 | 2 | [] | no_license | package creativebrands.kazziworker.fragments.PendingRequests;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import creativebrands.kazziworker.MainActivity;
import creativebrands.kazziworker.PicassoClient;
import creativebrands.kazziworker.R;
import creativebrands.kazziworker.myRequestHandler;
import com.google.android.gms.ads.InterstitialAd;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public class PendingInfo extends AppCompatActivity {
TextView nametxt,date,datetxt,time,timetxt,jobdesc,jobdesctxt,landmark,landmarktxt,details;
String user_pno;
Button accepted,rejected;
private InterstitialAd mInterstitialAd;
String id,formattedDate;
ImageView userImage;
public static final String UPDATE_URL = "http://104.248.124.210/android/iKazi/phpFiles/rejectrequest.php";
public static final String ACCEPT_URL = "http://104.248.124.210/android/iKazi/phpFiles/acceptrequest.php";
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pending_info);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
//get current date
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
formattedDate = df.format(c);
nametxt=findViewById(R.id.name);
date=findViewById(R.id.textView_date);
datetxt=findViewById(R.id.date);
time=findViewById(R.id.textView_time);
timetxt=findViewById(R.id.time);
jobdesc=findViewById(R.id.textView_jobdesc);
jobdesctxt=findViewById(R.id.jobDescription);
landmark=findViewById(R.id.textView_landmark);
landmarktxt=findViewById(R.id.landmark);
rejected=findViewById(R.id.rejectbtn);
accepted=findViewById(R.id.acceptbtn);
details=findViewById(R.id.details);
userImage=findViewById(R.id.user_profile_image);
Typeface font=Typeface.createFromAsset(getAssets(),"RobotoSlab-Bold.ttf");
nametxt.setTypeface(font);
date.setTypeface(font);
datetxt.setTypeface(font);
time.setTypeface(font);
timetxt.setTypeface(font);
jobdesc.setTypeface(font);
jobdesctxt.setTypeface(font);
landmark.setTypeface(font);
landmarktxt.setTypeface(font);
rejected.setTypeface(font);
accepted.setTypeface(font);
details.setTypeface(font);
mInterstitialAd = new InterstitialAd(PendingInfo.this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
//ObtainBundleData in the object
final String name = bundle.getString("name");
String time = bundle.getString("time");
String date = bundle.getString("date");
String jobDescription = bundle.getString("jobdesc");
String landmark=bundle.getString("landmark");
user_pno=bundle.getString("pno");
id=bundle.getString("id");
String url=bundle.getString("url");
nametxt.setText(name);
timetxt.setText(time);
datetxt.setText(date);
timetxt.setText(time);
jobdesctxt.setText(jobDescription);
landmarktxt.setText(landmark);
PicassoClient.loadImage(url,userImage);
accepted.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int greenColorValue = Color.parseColor("#00ff00");
showDialog(PendingInfo.this,"accept "+name+"'s request",R.drawable.accepted,greenColorValue,1);
}
});
rejected.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int greenColorValue = Color.parseColor("#FFF60606");
showDialog(PendingInfo.this,"reject "+name+"'s request",R.drawable.cancel,greenColorValue,2);
}
});
//Do something here if data received
}
else
{
//Do something here if data not received
}
}
public void showDialog(Activity activity, String msg, int images, int color, final int whichbutton){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.dialog);
TextView text = dialog.findViewById(R.id.text_dialog);
text.setText(msg);
ImageView imageView=dialog.findViewById(R.id.popupimage);
imageView.setImageResource(images);
imageView.setBackgroundColor(color);
Typeface font1=Typeface.createFromAsset(getAssets(),"RobotoSlab-Bold.ttf");
text.setTypeface(font1);
Button dialogButton = dialog.findViewById(R.id.btn_dialog_yes);
dialogButton.setTypeface(font1);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(whichbutton==1){
acceptRequest();
}else {
rejectRequest();
}
dialog.dismiss();
}
});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
});
dialog.show();
}
public void rejectRequest(){
class rejectRequest extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
myRequestHandler rh=new myRequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(PendingInfo.this, "Loading...", null,true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equals("Successfully Uploaded")){
Intent intent=new Intent(PendingInfo.this, MainActivity.class);
startActivity(intent);
}
}
@Override
protected String doInBackground(Void... params) {
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
data.put("pno",user_pno);
data.put("date",formattedDate);
String result = rh.sendPostRequest(UPDATE_URL,data);
return result;
}
}
rejectRequest rejectRequest=new rejectRequest();
rejectRequest.execute();
}
public void acceptRequest(){
class acceptRequest extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
myRequestHandler rh=new myRequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(PendingInfo.this, "Loading...", null,true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(PendingInfo.this, ""+s, Toast.LENGTH_SHORT).show();
if(s.equals("Successfully Uploaded")){
Toast.makeText(PendingInfo.this, "complete!!! check your accepted requests", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(PendingInfo.this, MainActivity.class);
startActivity(intent);
}
}
@Override
protected String doInBackground(Void... params) {
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
data.put("pno",user_pno);
data.put("date",formattedDate);
String result = rh.sendPostRequest(ACCEPT_URL,data);
return result;
}
}
acceptRequest acceptRequest=new acceptRequest();
acceptRequest.execute();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
|
Java | UTF-8 | 1,628 | 2.359375 | 2 | [] | no_license | package com.jaats.agrovehicledriver.net.WSAsyncTasks;
import android.os.AsyncTask;
import java.util.HashMap;
import com.jaats.agrovehicledriver.model.HelpListBean;
import com.jaats.agrovehicledriver.net.invokers.HelpListInvoker;
/**
* Created by Jemsheer K D on 20 May, 2017.
* Package com.jaats.agrovehicledriver.net.WSAsyncTasks
* Project LaTaxiDriver
*/
public class HelpListTask extends AsyncTask<String, Integer, HelpListBean> {
private HelpListTaskListener helpListTaskListener;
private HashMap<String, String> urlParams;
public HelpListTask(HashMap<String, String> urlParams) {
super();
this.urlParams = urlParams;
}
@Override
protected HelpListBean doInBackground(String... params) {
System.out.println(">>>>>>>>>doInBackground");
HelpListInvoker helpListInvoker = new HelpListInvoker(urlParams, null);
return helpListInvoker.invokeHelpListWS();
}
@Override
protected void onPostExecute(HelpListBean result) {
super.onPostExecute(result);
if (result != null)
helpListTaskListener.dataDownloadedSuccessfully(result);
else
helpListTaskListener.dataDownloadFailed();
}
public static interface HelpListTaskListener {
void dataDownloadedSuccessfully(HelpListBean helpListBean);
void dataDownloadFailed();
}
public HelpListTaskListener getHelpListTaskListener() {
return helpListTaskListener;
}
public void setHelpListTaskListener(HelpListTaskListener helpListTaskListener) {
this.helpListTaskListener = helpListTaskListener;
}
}
|
Shell | UTF-8 | 5,266 | 3.34375 | 3 | [] | no_license | #!/bin/bash
ANDROID_API_VERSION=18
NDK_TOOLCHAIN_ABI_VERSION=4.9
ABI=$1
# echo "ABI"$ABI
TOOLCHAINS=$(pwd)/"toolchains"
TOOLCHAINS_PREFIX="arm-linux-androideabi"
TOOLCHAINS_PATH=${TOOLCHAINS}/bin
SYSROOT=${TOOLCHAINS}/sysroot
LDFLAGS=""
EXTRA_CONFIGURE_FLAGS=""
EXTRA_CFLAGS=""
CFLAGS="--sysroot=${SYSROOT} -I${SYSROOT}/usr/include -I${TOOLCHAINS}/include -isysroot ${SYSROOT}"
# CFLAGS="${CFLAGS} --sysroot=${SYSROOT} -I${SYSROOT}/usr/include -I${TOOLCHAINS}/include"
CPPFLAGS="${CFLAGS}"
CXXFLAGS="${CFLAGS}"
LDFLAGS="${LDFLAGS} -L${SYSROOT}/usr/lib -L${TOOLCHAINS}/lib"
CWD=$(pwd)
ARCH_PREFIX="armeabi"
function make_standalone_toolchain() {
echo "make standalone toolchain --arch=$1 --api=$2 --install-dir=$3"
rm -rf ${TOOLCHAINS}
$NDK_ROOT/build/tools/make_standalone_toolchain.py \
--arch=$1 \
--api=$2 \
--install-dir=$3 \
--stl=stlport \
-v
# --stl=gnustl \'gnustl', 'libc++', 'stlport'
}
function export_vars() {
CROSS_PREFIX=${TOOLCHAINS_PATH}/${TOOLCHAINS_PREFIX}-
echo "
export TOOLCHAINS=${TOOLCHAINS}
export TOOLCHAINS_PREFIX=${TOOLCHAINS_PREFIX}
export TOOLCHAINS_PATH=${TOOLCHAINS_PATH}
export SYSROOT=${SYSROOT}
export CROSS_PREFIX=${CROSS_PREFIX}
export CPP=${CROSS_PREFIX}cpp
export AR=${CROSS_PREFIX}ar
export AS=${CROSS_PREFIX}as
export NM=${CROSS_PREFIX}nm
export CC=${CROSS_PREFIX}gcc
export CXX=${CROSS_PREFIX}g++
export LD=${CROSS_PREFIX}ld
export RANLIB=${CROSS_PREFIX}ranlib
export STRIP=${CROSS_PREFIX}strip
export OBJDUMP=${CROSS_PREFIX}objdump
export OBJCOPY=${CROSS_PREFIX}objcopy
export ADDR2LINE=${CROSS_PREFIX}addr2line
export READELF=${CROSS_PREFIX}readelf
export SIZE=${CROSS_PREFIX}size
export STRINGS=${CROSS_PREFIX}strings
export ELFEDIT=${CROSS_PREFIX}elfedit
export GCOV=${CROSS_PREFIX}gcov
export GDB=${CROSS_PREFIX}gdb
export GPROF=${CROSS_PREFIX}gprof
# Don't mix up .pc files from your host and build target
export PKG_CONFIG_PATH=${TOOLCHAINS}/lib/pkgconfig
export CFLAGS=\" ${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION\"
export CXXFLAGS=\" ${CXXFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION\"
export CPPFLAGS=\" ${CPPFLAGS}\"
export LDFLAGS=\" ${LDFLAGS}\"
export EXTRA_CONFIGURE_FLAGS=\" ${EXTRA_CONFIGURE_FLAGS}\"
export EXTRA_CFLAGS=\" ${EXTRA_CFLAGS}\"
export ABI=${ABI}
export ARCH=${ARCH}
export ANDROID_API_VERSION=${ANDROID_API_VERSION}
" >toolchain.cfg
}
function x86_64_extra_flags() {
EXTRA_CONFIGURE_FLAGS="--disable-asm"
EXTRA_CFLAGS="-Dipv6mr_interface=ipv6mr_ifindex -fasm -Wno-psabi -fno-short-enums -fno-strict-aliasing -fomit-frame-pointer -march=k8"
}
echo "building $ABI..."
ARCH=$ABI
if [ $ABI = "armeabi" ]; then
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain arm $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=arm-linux-androideabi
ARCH_PREFIX=$ABI
EXTRA_CONFIGURE_FLAGS="--disable-asm"
EXTRA_CFLAGS="-march=armv5te"
ARCH="arm"
export_vars
elif [ $ABI = "armeabi-v7a" ]; then
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain arm $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=arm-linux-androideabi
ARCH_PREFIX=$ABI
EXTRA_CONFIGURE_FLAGS="--disable-asm"
# EXTRA_CFLAGS="-march=armv7-a -mfloat-abi=softfp -mfpu=neon"
EXTRA_CFLAGS="-fpic -ffunction-sections -funwind-tables -fstack-protector -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -fomit-frame-pointer -fstrict-aliasing -funswitch-loops -finline-limit=300"
ARCH="arm"
export_vars
elif [ $ABI = "arm64-v8a" ]; then
ANDROID_API_VERSION=21
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain arm64 $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=aarch64-linux-android
ARCH_PREFIX=$ABI
EXTRA_CONFIGURE_FLAGS="--enable-asm"
EXTRA_CFLAGS="-march=armv8-a"
ARCH="aarch64"
export_vars
elif [ $ABI = "x86" ]; then
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain x86 $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=i686-linux-android
ARCH_PREFIX=$ABI
# x86_64_extra_flags
EXTRA_CONFIGURE_FLAGS="--disable-asm"
EXTRA_CFLAGS="-march=i686 -mtune=intel -mssse3 -mfpmath=sse -m32"
export_vars
elif [ $ABI = "x86_64" ]; then
ANDROID_API_VERSION=21
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain x86_64 $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=x86_64-linux-android
ARCH_PREFIX=$ABI
# x86_64_extra_flags
EXTRA_CONFIGURE_FLAGS="--disable-asm"
EXTRA_CFLAGS="-march=x86-64 -msse4.2 -mpopcnt -m64 -mtune=intel"
export_vars
elif [ $ABI = "mips" ]; then
ANDROID_API_VERSION=21
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain mips $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=mipsel-linux-android
ARCH_PREFIX=$ABI
export_vars
elif [ $ABI = "mips64" ]; then
ANDROID_API_VERSION=21
# CFLAGS="${CFLAGS} -D__ANDROID_API__=$ANDROID_API_VERSION"
make_standalone_toolchain mips64 $ANDROID_API_VERSION ${TOOLCHAINS}
TOOLCHAINS_PREFIX=mips64el-linux-android
ARCH_PREFIX=$ABI
export_vars
else
echo $ABI
fi
echo "build-toolchains.sh execute complete."
cd $CWD
|
TypeScript | UTF-8 | 3,609 | 3.84375 | 4 | [] | no_license | import stately from "../src";
const store = stately({
a: "a",
b: {
c: "c",
d: 4
}
});
/**
* Single argument mutator
*/
const changeA = store.createMutator((state, a: string) => (state.a = a));
const latestState = changeA("🔥"); // Returns { a: string; b: { c: string; d: number; }; }
/**
* Invalid mutator
*/
const invalidChangeA = store.createMutator((state, a: number) => (state.a = a)); // Fails: Type 'number' is not assignable to type 'string'. ts(2322)
/**
* Multi argument mutator
*/
const changeAComplex = store.createMutator(
(state, a: string, b: string) => (state.a = `${a} stately is ${b}`)
);
changeAComplex("yo", "so 🔥");
changeAComplex("nope"); // Fails: Expected 2 arguments, but got 1. ts(2554)
/**
* Higher order mutator
*/
const changeAChanger = (a: string) =>
store.createMutator((state, b: string) => (state.a = `${a} stately is ${b}`));
const aChanger = changeAChanger("yo"); // Returns (b: string) => { a: string; b: { c: string; d: number; }; }
aChanger("so 🔥"); // Returns { a: string; b: { c: string; d: number; }; }
/**
* Mutator updating nested state
*/
const multiplyD = store.createMutator(
(state, multiplier: number) => (state.b.d = state.b.d * multiplier)
);
multiplyD(10);
multiplyD("ten"); // Argument of type '"ten"' is not assignable to parameter of type 'number'. ts(2345)
/**
* Simple selector
*/
const selectA = store.createSelector(state => state.a);
const a = selectA(); // Returns "a"
/**
* Selectors are immutable
*/
const selectB = store.createSelector(state => state.b);
const firstB = selectB(); // Returns { c: "c", d: 4 }
multiplyD(10);
const secondB = selectB(); // Returns { c: "c", d: 40 }
firstB.d === 4; // Returns true
secondB.d === 40; // Returns true
/**
* Selectors take arguments
*/
const selectAndAddToD = store.createSelector(
(state, add: number) => state.b.d + add
);
const firstAdditionToD = selectAndAddToD(10); // Returns 14
const secondAdditionToD = selectAndAddToD(100); // Returns 104
selectAndAddToD(); // Expected 1 arguments, but got 0. ts(2554)
selectAndAddToD("ten"); // Argument of type '"ten"' is not assignable to parameter of type 'number'. ts(2345)
/**
* Selectors that return new objects are not memoized (or equal)
*/
const selectorWithNewObj = store.createSelector(state => ({ newObj: state.b }));
const firstNewObjSelection = selectorWithNewObj();
const secondNewObjSelection = selectorWithNewObj();
firstNewObjSelection === secondNewObjSelection; // Returns false
/**
* Selectors that return new objects that implement memoization are memoized
*/
import memoize from "memoize-one";
const memoizedSelectorWithNewObj = store.createSelector(
memoize(state => ({ newObj: state.b }))
);
const firstMemoizedNewObjSelection = memoizedSelectorWithNewObj();
const secondMemoizedNewObjSelection = memoizedSelectorWithNewObj();
firstMemoizedNewObjSelection === secondMemoizedNewObjSelection; // Returns true
/**
* Async effects, optional arguments
*/
const asyncChangeA = store.createEffect(
(_state, a: string = "Stately so 🔥") =>
new Promise<Boolean>(resolve => {
console.log(`About to change a to ${a}`);
changeA(a);
console.log("Changed a");
resolve(true);
})
);
asyncChangeA(); // Returns Promise<Boolean>
asyncChangeA("yup...");
asyncChangeA("nope", "not allowed"); // Fails: Expected 0-1 arguments, but got 2. ts(2554)
/**
* Adding a subscription
*/
const unsubscribe = store.subscribe((previous, next) => {
console.log("The state has updated", { previous, next });
});
/**
* Removing a subscription
*/
unsubscribe();
|
C++ | UTF-8 | 2,145 | 2.546875 | 3 | [] | no_license |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <rdlib/StdFile.h>
#include <rdlib/strsup.h>
int main(int argc, char *argv[])
{
AStdFile file, ofile;
AStdData *ifp = Stdin;
uint_t wid = 256, hgt = 256, n = 5;
int i;
if (argc < 3) {
fprintf(stderr, "Usage: videosig [-s <w>x<h>] [-n <n>] [-if <input-file>] -of <output-file>\n");
exit(1);
}
for (i = 1; i < argc; i++) {
if (stricmp(argv[i], "-s") == 0) {
uint_t w, h;
if (sscanf(argv[++i], "%ux%u", &w, &h) == 2) {
wid = w;
hgt = h;
}
else fprintf(stderr, "Failed to decode widxhgt from '%s'\n", argv[i]);
}
else if (stricmp(argv[i], "-n") == 0) n = (uint_t)AString(argv[++i]);
else if (stricmp(argv[i], "-if") == 0) {
file.close();
if (file.open(argv[++i], "rb")) ifp = &file;
else fprintf(stderr, "Failed to open file '%s' for reading\n", argv[i]);
}
else if (stricmp(argv[i], "-of") == 0) {
ofile.close();
if (!ofile.open(argv[++i], "wb")) fprintf(stderr, "Failed to open file '%s' for writing\n", argv[i]);
}
}
uint_t nframes = 0;
if (ifp && ofile.isopen() && wid && hgt && n) {
std::vector<uint8_t> inbuf;
std::vector<uint8_t> outbuf;
inbuf.resize(wid * hgt * 3);
outbuf.resize(n * n * 3);
while (ifp->readbytes(&inbuf[0], inbuf.size()) == (slong_t)inbuf.size()) {
uint8_t *p = &outbuf[0];
uint_t i, j, div = 2 * (n + 1);
for (i = 0; i < n; i++) {
uint_t y = (((2 * i + 1) * hgt) / div) * hgt;
for (j = 0; j < n; j++) {
uint_t x = ((2 * j + 1) * wid) / div;
memcpy(p, &inbuf[3 * (x + y)], 3);
p += 3;
}
}
ofile.writebytes(&outbuf[0], outbuf.size());
nframes++;
}
}
ofile.close();
printf("Total %u frames processed\n", nframes);
return 0;
}
|
PHP | UTF-8 | 838 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models\Syst;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $cd_status_projeto
* @property string $tx_nome_status_projeto
* @property Osc.tbProjeto[] $osc.tbProjetos
*/
class StatusProjeto extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'syst.dc_status_projeto';
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'cd_status_projeto';
/**
* @var array
*/
protected $fillable = ['tx_nome_status_projeto'];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function osc.tbProjetos()
{
return $this->hasMany('App\Models\Syst\Osc.tbProjeto', 'cd_status_projeto', 'cd_status_projeto');
}
}
|
TypeScript | UTF-8 | 1,433 | 2.515625 | 3 | [] | no_license | module Hm.Data.JsonClient {
export var crud = {
insert: function (): any { },
update: function (): any { },
delete: function (): any{ },
select: function (): any { }
}
export class executionObject {
tableName: string;
execute: any;
oparationType: oparationType;
}
export enum oparationType {
insert = 0,
update = 1,
delete = 2,
select = 3
}
}
module Hm.Data.ExecuteQuery {
export enum webMethod {
Get = 0,
Post = 1
}
export class apiConnector {
callservice(url: string, data: any, method: webMethod): JQueryDeferred<any> {
var dfd = jQuery.Deferred();
$.ajax({
url: url,
method: (method == Hm.Data.ExecuteQuery.webMethod.Get) ? "GET" : "POST",
contentType: "application/json; charset=utf-8",
data: (method == webMethod.Get) ? data : JSON.stringify(data),
dataType: "json",
cache: false,
success: function (data) {
var value = data;
dfd.resolve(value);
},
error: function (xhr, textStatus, errorThrown) {
console.log(textStatus);
dfd.reject();
}
});
return dfd;
}
}
}
|
Java | UTF-8 | 1,891 | 2.234375 | 2 | [] | no_license | package leagueofcrafters.items;
import leagueofcrafters.LeagueofCrafters;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemLeague extends Item {
public Icon icon;
private String texture;
public static int abilityNum;
private boolean checked;
public static ItemStack itemStack;
public static int currentHealth;
public ItemLeague(int par1, String texturePath, int numToAdd) {
super(par1);
this.abilityNum = numToAdd;
texture = texturePath;
}
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister) {
this.itemIcon = par1IconRegister.registerIcon("league:" + texture);
icon = this.itemIcon;
}
//@Override
//public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5) {
// EntityPlayer player = null;
// itemStack = par1ItemStack;
// if (par3Entity != null)
// if (par3Entity instanceof EntityPlayer) {
// player = (EntityPlayer) par3Entity;
// int HEALTH = 20;
// if (player.inventory.hasItem(this.itemID)) {
// if (checked == false) {
// HEALTH += this.abilityNum;
// checked = true;
// currentHealth = HEALTH;
//// }
/// } else {
// currentHealth = 20;
// }
// // if (player.inventory.hasItem(LeagueofCrafters.warmogs)) {
// HEALTH += 10;
// } else {
// HEALTH -= 10;
// }
/// ((EntityLivingBase) player).getEntityAttribute(SharedMonsterAttributes.maxHealth).setAttribute(currentHealth);
// }
//}
}
|
Java | UTF-8 | 2,561 | 3.96875 | 4 | [] | no_license | package 简单难度.未排序数组中累加和为给定值的最长子数组长度;
import java.util.HashMap;
/**
* @Description:
* @Auther: lyuans
* @Date: 2020.12.17 1:48
* @Version: 1.0
*/
public class Solution {
/**
* max length of the subarray sum = k
*
* @param arr int整型一维数组 the array
* @param k int整型 target
* @return int整型
*/
/**
* 给定一个无序数组arr, 其中元素可正、可负、可0。给定一个整数k,求arr所有子数组中累加和为k的最长子数组长度
*/
public int maxlenEqualK(int[] arr, int k) {
// write code here
int sumLen = 0;
int maxl = 0;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for (int i = 0; i < arr.length; i++) {
sumLen += arr[i];
if (!map.keySet().contains(sumLen - k)) {
map.put(sumLen, i);
} else if (!map.containsKey(sumLen)) {
maxl = Math.max(i - map.get(sumLen - k), maxl);
}
}
return maxl;
}
/**
* 求一段无序数组中整数和负数数量相同的最长子数组,把正数换为1,负数换为-1,求和为0
*/
public int maxlenEqualK2(int[] arr, int k) {
// write code here
k = 0;
int sumLen = 0;
int maxl = 0;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.compare(arr[i], 0);
sumLen += arr[i];
if (!map.keySet().contains(sumLen - k)) {
map.put(sumLen, i);
} else if (!map.containsKey(sumLen)) {
maxl = Math.max(i - map.get(sumLen - k), maxl);
}
}
return maxl;
}
/**
* 数组中有1和0,求子数组中0和1数量相同的。把0换成-1 求和为0的
*/
public int maxlenEqualK3(int[] arr, int k) {
// write code here
k = 0;
int sumLen = 0;
int maxl = 0;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] == 0 ? -1 : arr[i];
sumLen += arr[i];
if (!map.keySet().contains(sumLen - k)) {
map.put(sumLen, i);
} else if (!map.containsKey(sumLen)) {
maxl = Math.max(i - map.get(sumLen - k), maxl);
}
}
return maxl;
}
}
|
Java | UTF-8 | 2,190 | 3.515625 | 4 | [] | no_license | import java.util.Scanner;
public class TicTacToeTomek {
public static void main(String[] args) {
new TicTacToeTomek().run();
}
Scanner sc = new Scanner(System.in);
int count = 1;
public void run()
{
int n = sc.nextInt();
sc.nextLine();
for( count = 1; count <= n; count++){
solve();
if(sc.hasNext())
sc.nextLine();
}
}
public void solve()
{
String [] table = new String [4];
for(int i=0;i<4;i++)
table[i] = sc.nextLine();
if(checkHorizontal(table))
return;
if(checkVertical(table))
return;
if(checkDiagonal(table))
return;
if(checkIsNotComplete(table))
System.out.println( "Case #" + count + ": " + "Game has not completed");
else
System.out.println( "Case #" + count + ": " + "Draw");
}
public boolean checkIsNotComplete(String [] table)
{
for(int i=0;i<4;i++)
if(table[i].contains("."))
return true;
return false;
}
public boolean checkLine(String line)
{
boolean isWin = true;
char winner = ' ';
int k;
if(line.contains("."))
return false;
for( k=0 ;k<4;k++)
if(line.charAt(k) != 'T'){
winner = line.charAt(k);
break;
}
for( ; k <4 ; k++ )
if( line.charAt(k) != winner && line.charAt(k) != 'T'){
isWin = false;
break;
}
if(isWin)
System.out.println( "Case #" + count + ": " + winner + " won");
return isWin;
}
public boolean checkHorizontal(String [] table)
{
for(int i=0;i<4;i++)
if(checkLine(table[i]))
return true;
return false;
}
public boolean checkVertical(String [] table)
{
String [] line = new String [4];
for(int i=0;i<4;i++)
{
line[i] = "";
for(int j=0;j<4;j++)
line[i] += table[j].charAt(i);
}
return checkHorizontal(line);
}
public boolean checkDiagonal(String [] table)
{
String [] line = new String [2];
line[0] = "";
for(int i=0;i<4;i++)
line[0] += table[i].charAt(i);
line[1] = "";
for(int i=0;i<4;i++)
line[1] += table[i].charAt(3-i);
for(int i=0;i<2;i++)
if(checkLine(line[i]))
return true;
return false;
}
}
|
C | UTF-8 | 509 | 2.578125 | 3 | [] | no_license | /******************************************************************************
* File: image.h
*
* Description: This file contains some of the core items needed throughout
* the imagizer.
*
*****************************************************************************/
#ifndef IMAGE_
#define IMAGE_
#define ROW_STRIDE 3 // Skip number for R G B in a char array.
// Image structure - Holds important data about an image.
typedef struct {
int width;
int height;
unsigned char *data;
} Image;
#endif |
Markdown | UTF-8 | 504 | 2.8125 | 3 | [] | no_license | ##Access to data records—The number-one problem with larger companies when starting to work with cloud providers is working through the internal politics to allow access to data from the cloud. Data record access, and the steps for successful access, should be considered before you move to the cloud:
How can we access our on-premise data from the cloud?
What records have to stay on-premise?
Are we bound by any compliance rules and regulations?
Is our data in the right format for what we need?
|
Java | UTF-8 | 2,512 | 2.359375 | 2 | [] | no_license | package com.c102c.app.utils;
import java.util.List;
import com.c102c.finalJKYTJ.R;
import android.R.integer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.LinearLayout;
public class FourColmunAdapter extends BaseAdapter {
private static final int LENGTH = 4;
private List<String[]> mData;
private Context mContext;
private Holder holder;
public FourColmunAdapter(Context context, List<String[]> data) {
// TODO Auto-generated constructor stub
mContext = context;
mData = data;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mData.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void deleteItemId(int position) {
mData.remove(position);
}
public void addItem(String[] item) {
mData.add(item);
}
public List<String[]> getListItem() {
return mData;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String[] line = mData.get(position);
if (convertView == null) {
holder = new Holder();
holder.dataET = new TextView[LENGTH];
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater
.inflate(R.layout.list_item_four_layout, null);
holder.dataET[0] = (TextView) convertView.findViewById(R.id.item_1);
holder.dataET[1] = (TextView) convertView.findViewById(R.id.item_2);
holder.dataET[2] = (TextView) convertView.findViewById(R.id.item_3);
holder.dataET[3] = (TextView) convertView.findViewById(R.id.item_4);
holder.layout = (LinearLayout) convertView
.findViewById(R.id.list_item_four_layout);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
for (int i = 0; i < LENGTH; i++) {
String item;
if (line[i].length() > 200) {
item = line[i].substring(0, 200) + "...";
} else {
item = line[i];
}
holder.dataET[i].setText(item);
}
return convertView;
}
public class Holder {
public TextView[] dataET;
public LinearLayout layout;
private void setTextColor(int color) {
for (int i = 0; i < dataET.length; i++) {
dataET[i].setTextColor(color);
}
}
}
} |
C++ | UTF-8 | 1,838 | 3.09375 | 3 | [
"MIT"
] | permissive | //
// main.cpp
// 28 - Implement strStr()
//
// Created by ynfMac on 2019/6/13.
// Copyright © 2019 ynfMac. All rights reserved.
//
#include <iostream>
using namespace std;
class Solution {
public:
int strStr1(string haystack, string needle) {
int n = haystack.size(),m = needle.size();
for (int i = 0; i <= n - m; i ++) {
int j = 0;
for (j = 0; j < needle.size(); j++) {
if(needle[j] != haystack[j + i]){
break;
}
}
if (j == needle.size() ) {
return i;
}
}
return -1;
}
int strStr(string haystack, string needle) {
if (haystack == needle) {
return 0;
}
if (needle == "") {
return 0;
}
if (needle.size() > haystack.size()) {
return -1;
}
int subStrCount = 0;
bool compare = false;
for ( int i = 0; i < haystack.size(); i++) {
if (compare) {
if (haystack[i] == needle[subStrCount]) {
subStrCount++;
} else {
i = i - subStrCount; // 回滚
subStrCount = 0;
compare = false;
}
} else {
if (haystack[i] == needle[0]) {
compare = true;
subStrCount++;
}
}
if (subStrCount == needle.size()) {
return i - subStrCount + 1;
}
}
return -1;
}
};
int main(int argc, const char * argv[]) {
int c = Solution().strStr1("mississippi", "pi");
cout << c << endl;
return 0;
}
|
JavaScript | UTF-8 | 5,056 | 3.046875 | 3 | [] | no_license | const mongoose = require("mongoose");
// mongoose provides something called a Schema -> blueprint for the database document
const bookSchema = new mongoose.Schema({
title: String,
author: String,
pages: Number,
releaseDate: Date,
isAvailable: Boolean,
genre: String,
});
const multipleBooks = [
{
title: "Hunger Games",
author: "SOmeone",
pages: 49,
releaseDate: new Date(),
isAvailable: false,
genre: "fantasy",
},
{
title: "Fight Club",
author: "Chuck Something",
pages: 0,
isAvailable: false,
genre: "unknown",
},
{
title: "Lord of the Rings",
author: "JRR Tolkien",
pages: 500,
isAvailable: true,
genre:
"the history of the world, without skipping or adding anything. true story",
},
];
const Book = mongoose.model("book", bookSchema);
// API
// C reate
// R ead
// U pdate
// D elete
// PRE CALLBACK HELL SCARE
// mongoose
// .connect("mongodb://localhost:27017/book-factory-of-our-dreams")
// .then(() => {
// console.log("Yay connecting to the database");
// Book.create({
// title: "Harry Potter",
// author: "JKidding Rowling",
// pages: 99999,
// releaseDate: new Date(),
// isAvailable: true,
// genre: "fantasy",
// })
// .then((createdBook) => {
// console.log("We created a book 📚:", createdBook);
// mongoose.connection
// .dropDatabase()
// .then(() => {
// mongoose.disconnect();
// })
// .catch((err) => {
// console.error("Oopsie dropping the database");
// });
// })
// .catch((err) => {
// console.error("Oopsie creating a book", err);
// });
// })
// .catch((err) => {
// console.error("Oppsie connecting to the database");
// });
mongoose
.connect("mongodb://localhost:27017/book-factory-of-our-dreams") // please connect to the database
.then(() => {
// then, when youre done create a book
console.log(`Connected... Yay`);
return Book.create({
title: "Harry Potter",
author: "JKidding Rowling",
pages: 99999,
releaseDate: new Date(),
isAvailable: true,
genre: "fantasy",
});
})
.then((createdBook) => {
// 👆 this value is the created book (or whatever was returned from the previous function)
// then, when youre done show me all of the books in the collection
return Book.find({});
})
.then((allBooks) => {
// 👆 this value is all of the books (or whatever was returned from the previous function)
// console.log("ALL BOOKS FROM DB", allBooks);
const theHarryPotterBook = allBooks[0];
return Book.findById(theHarryPotterBook._id);
})
.then((singleBook) => {
// 👆 this value is the one book you were looking by id (or whatever was returned from the previous function)
return Book.findByIdAndUpdate(
singleBook._id,
{ pages: 300 },
{ new: true }
);
})
.then((updatedBook) => {
console.log("updatedBook:", updatedBook);
return updatedBook;
})
.then((singleBook) => {
return Book.findByIdAndDelete(singleBook._id);
})
.then((deleted) => {
return Book.insertMany(multipleBooks);
})
.then((allAddedBooks) => {
console.log("allAddedBooks:", allAddedBooks);
return mongoose.connection.dropDatabase();
})
.catch((err) => {
// in case i screw up, do this
console.error("Overall Oopsie", err);
})
.finally(() => {
return mongoose.disconnect();
});
// MORE CALLBACK JELLY
// mongoose
// .connect("mongodb://localhost:27017/book-factory-of-our-dreams")
// .then(() => {
// Book.create({
// title: "Harry Potter",
// author: "JKidding Rowling",
// pages: 99999,
// releaseDate: new Date(),
// isAvailable: true,
// genre: "fantasy",
// }).then((createdBook) => {
// Book.find({}).then((allBooks) => {
// const theHarryPotterBook = allBooks[0];
// Book.findById(theHarryPotterBook._id).then((singleBook) => {
// Book.findByIdAndUpdate(
// singleBook._id,
// { pages: 300 },
// { new: true }
// ).then((updatedBook) => {
// Book.findByIdAndDelete(updatedBook._id).then(() => {
// mongoose.connection.dropDatabase().then(() => {
// console.log("FINITO");
// });
// });
// });
// });
// });
// });
// });
// Book.create({
// title: "Harry Potter",
// author: "JKidding Rowling",
// pages: 99999,
// releaseDate: new Date(),
// isAvailable: true,
// genre: "fantasy",
// })
// .then((createdBook) => {
// console.log("We created a book 📚:", createdBook);
// })
// .catch((err) => {
// console.error("Oopsie", err);
// });
// Promises
// then and catch
// then -> is the code that will be executed whenever our async code works wonderfully
// catch -> is the code that will be executed whenever our async code crashes, burns and rips out childrens hearts
|
Markdown | UTF-8 | 744 | 2.625 | 3 | [] | no_license |
# unity_gamedevelopement_extremerace
I developed a 2-D racing game for in-house project in my 2nd year using unity and visual studio(editor) and named it extreme race( actually very similar to need for speed (initial version)).Since I shifted to linux operating system a year ago and deleted unity and all the editors , so in short i dont have my actually working project with me but i have my reports
of both the games I developed and some of the codes. I learned it from youtube and various other websites since the link I shared below works on the old version of unity. (The codes in my repostiory are latest version)
Hope you too enjoy this!!
link- https://www.youtube.com/watch?v=r7J-wiJGK1w&list=PLytjVIyAOStpcOGg6HIHhnnOZAdxkAr1U
|
Java | UTF-8 | 607 | 2.078125 | 2 | [] | no_license | package com.yushilei.myapp.db;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
/**
* @auther by yushilei.
* @time 2017/3/14-14:00
* @desc
*/
@Table(name = "BlackBard")
public class BlackBard {
@Column(name = "cardNo", isId = true)
private String cardNo;
@Column(name = "info")
private String info = "";
public BlackBard() {
}
public BlackBard(String cardNo) {
this.cardNo = cardNo;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
}
|
Java | UTF-8 | 324 | 2.046875 | 2 | [] | no_license | package com.uairobot.util.ibot9;
import java.rmi.RemoteException;
import cn.eastrobot.www.ws.RobotServiceEx.RobotResponse;
public class Example {
public static void main(String[] args) throws RemoteException {
RobotResponse answer = IbotWSClient.getAnswer("���");
System.out.println(answer.getContent());
}
}
|
Java | UTF-8 | 3,175 | 1.835938 | 2 | [] | no_license | package com.tencent.mm.protocal.b;
public final class le
extends com.tencent.mm.al.a
{
public String ayg;
public String desc;
public boolean huq = false;
public boolean hur = false;
public boolean hwm = false;
public boolean hwn = false;
public boolean hwo = false;
public String info;
public String title;
public int type;
protected final int a(int paramInt, Object... paramVarArgs)
{
if (paramInt == 0)
{
paramVarArgs = (a.a.a.c.a)paramVarArgs[0];
if (title != null) {
paramVarArgs.U(1, title);
}
if (desc != null) {
paramVarArgs.U(2, desc);
}
if (ayg != null) {
paramVarArgs.U(3, ayg);
}
if (info != null) {
paramVarArgs.U(4, info);
}
if (hwo == true) {
paramVarArgs.bM(5, type);
}
return 0;
}
if (paramInt == 1) {
if (title == null) {
break label429;
}
}
label429:
for (int i = a.a.a.b.b.a.T(1, title) + 0;; i = 0)
{
paramInt = i;
if (desc != null) {
paramInt = i + a.a.a.b.b.a.T(2, desc);
}
i = paramInt;
if (ayg != null) {
i = paramInt + a.a.a.b.b.a.T(3, ayg);
}
paramInt = i;
if (info != null) {
paramInt = i + a.a.a.b.b.a.T(4, info);
}
i = paramInt;
if (hwo == true) {
i = paramInt + a.a.a.a.bI(5, type);
}
return i;
if (paramInt == 2)
{
paramVarArgs = new a.a.a.a.a((byte[])paramVarArgs[0], hfZ);
for (paramInt = com.tencent.mm.al.a.a(paramVarArgs); paramInt > 0; paramInt = com.tencent.mm.al.a.a(paramVarArgs)) {
if (!super.a(paramVarArgs, this, paramInt)) {
paramVarArgs.aVo();
}
}
break;
}
if (paramInt == 3)
{
a.a.a.a.a locala = (a.a.a.a.a)paramVarArgs[0];
le localle = (le)paramVarArgs[1];
switch (((Integer)paramVarArgs[2]).intValue())
{
default:
return -1;
case 1:
title = jMD.readString();
huq = true;
return 0;
case 2:
desc = jMD.readString();
hur = true;
return 0;
case 3:
ayg = jMD.readString();
hwm = true;
return 0;
case 4:
info = jMD.readString();
hwn = true;
return 0;
}
type = jMD.aVp();
hwo = true;
return 0;
}
return -1;
}
}
public final le mg(int paramInt)
{
type = paramInt;
hwo = true;
return this;
}
public final le wv(String paramString)
{
title = paramString;
huq = true;
return this;
}
public final le ww(String paramString)
{
desc = paramString;
hur = true;
return this;
}
public final le wx(String paramString)
{
ayg = paramString;
hwm = true;
return this;
}
public final le wy(String paramString)
{
info = paramString;
hwn = true;
return this;
}
}
/* Location:
* Qualified Name: com.tencent.mm.protocal.b.le
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
Java | UTF-8 | 1,408 | 1.921875 | 2 | [] | no_license | package com.cloudht.ft.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.cloudht.ft.dao.FtExpressCommodityDao;
import com.cloudht.ft.domain.FtExpressCommodityDO;
import com.cloudht.ft.service.FtExpressCommodityService;
@Service
public class FtExpressCommodityServiceImpl implements FtExpressCommodityService {
@Autowired
private FtExpressCommodityDao ftExpressCommodityDao;
@Override
public FtExpressCommodityDO get(Long ftExpressCommodityId){
return ftExpressCommodityDao.get(ftExpressCommodityId);
}
@Override
public List<FtExpressCommodityDO> list(Map<String, Object> map){
return ftExpressCommodityDao.list(map);
}
@Override
public int count(Map<String, Object> map){
return ftExpressCommodityDao.count(map);
}
@Override
public int save(FtExpressCommodityDO ftExpressCommodity){
return ftExpressCommodityDao.save(ftExpressCommodity);
}
@Override
public int update(FtExpressCommodityDO ftExpressCommodity){
return ftExpressCommodityDao.update(ftExpressCommodity);
}
@Override
public int remove(Long ftExpressCommodityId){
return ftExpressCommodityDao.remove(ftExpressCommodityId);
}
@Override
public int batchRemove(Long[] ftExpressCommodityIds){
return ftExpressCommodityDao.batchRemove(ftExpressCommodityIds);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.