language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 2,232
| 3.296875
| 3
|
[] |
no_license
|
""" Lesson 08 HPNorton furniture rental """
from pathlib import Path
import os
import logging
LOG_FORMAT = "%(asctime)s:%(lineno)-3d %(levelname)s %(message)s"
LOG_FILE_SYSTEM = 'system.log'
FORMATTER = logging.Formatter(LOG_FORMAT)
FILE_HANDLER_SYSTEM = logging.FileHandler(LOG_FILE_SYSTEM, mode='w')
FILE_HANDLER_SYSTEM.setFormatter(FORMATTER)
# General logging
SYSTEMLOG = logging.getLogger('SYSTEMLOG')
SYSTEMLOG.addHandler(FILE_HANDLER_SYSTEM)
SYSTEMLOG.setLevel("INFO")
def add_furniture(invoice_file, customer_name, item_code, item_description, item_monthly_price):
""" Creates or appends to invoice file using arguments provided """
directory_name = os.path.dirname(os.path.abspath(__file__))
try:
with open(Path(directory_name, invoice_file), 'a') as furniture_invoice:
furniture_invoice.write(f'{customer_name}, {item_code}, {item_description}, {item_monthly_price}\n')
SYSTEMLOG.info(f'Data added to invoice file: {customer_name}, {item_code}, {item_description}, {item_monthly_price}')
except IOError as fileerror:
SYSTEMLOG.error(f'File error {directory_name + invoice_file}, exception {type(fileerror).__name__}')
def single_customer(customer_name, invoice_file):
""" Provides a function """
def consumerentalitems(rental_items):
""" Add rental times to invoice file """
directory_name = os.path.dirname(os.path.abspath(__file__))
try:
with open(Path(directory_name,invoice_file), 'a') as output_file:
with open(Path(directory_name,rental_items), 'r') as input_file:
for line in input_file:
fields = line.strip().split(',')
output_file.write(f'{customer_name}, {fields[0]}, {fields[1]}, {fields[2]}\n')
SYSTEMLOG.info(f'Data added to invoice file {invoice_file}: {customer_name}, {fields[0]}, {fields[1]}, {fields[2]}')
except IOError as fileerror:
SYSTEMLOG.error(f'File error {directory_name + invoice_file}, exception {type(fileerror).__name__}')
return consumerentalitems
if __name__ == "__main__":
add_furniture('testfile', 'Elisa Miles','LR04','Leather Sofa', 25.00)
|
Java
|
UTF-8
| 880
| 2.65625
| 3
|
[] |
no_license
|
package Lab2;
import java.util.Scanner;
public class Lab2_2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Scanner scanner1 = new Scanner(System.in);
System.out.print("ชื่อ-สกุล: ");
String a = scanner.nextLine();
System.out.print("เลขบัตรประจำตัวประชน: ");
String b = scanner.nextLine();
System.out.print("ที่อยู่: ");
String c = scanner.nextLine();
System.out.print("อีเมล: ");
String e = scanner.nextLine();
System.out.print("โทร: ");
String t = scanner.nextLine();
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(e);
System.out.println(t);
}//main
}//class
|
Java
|
UTF-8
| 883
| 3.75
| 4
|
[] |
no_license
|
package com;
import java.util.Stack;
public class RecurssiveStackStort {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(30);
stack.push(-5);
stack.push(18);
stack.push(14);
stack.push(-3);
sortStack(stack);
System.out.println(" \n\nStack elements after sorting:");
printStack(stack);
}
private static void sortStack(Stack<Integer> stack) {
if(!stack.isEmpty()) {
int data=stack.pop();
sortStack(stack);
insert(stack, data);
}
}
private static void insert(Stack<Integer> stack, int data) {
if(stack.isEmpty() || data > stack.peek()) {
stack.push(data);
return;
}
int temp = stack.pop();
insert(stack, data);
stack.push(temp);
}
private static void printStack(Stack<Integer> stack) {
while(!stack.isEmpty()) {
System.out.print(stack.pop()+ " ");
}
}
}
|
C#
|
UTF-8
| 933
| 2.90625
| 3
|
[] |
no_license
|
using GeneralWPFClassLibrary;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using TechTalk.SpecFlow;
namespace GeneralWPF.Tests.ClassLibrary.CommandProcessing
{
[Binding]
public class CommandProcessingSteps
{
ExampleCommandProcessor proc;
[Given(@"a I have a new text command processor")]
public void GivenAIHaveANewTextCommandProcessor() => proc = new ExampleCommandProcessor();
[When(@"simulate a button firing the command ""(.*)""")]
public void WhenSimulateAButtonFiringTheCommand(string cmd) => proc.Execute(cmd);
[Then(@"the function should receive ""(.*)""")]
public void ThenTheFunctionShouldReceive(string cmd) => Assert.AreEqual(cmd, proc.CommandText);
}
internal class ExampleCommandProcessor : TextCommandProcessorBase
{
public string CommandText { get; set; } = string.Empty;
public override void ExecuteCommand(string commandText) => CommandText = commandText;
}
}
|
C++
|
UTF-8
| 1,223
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
#include "mario/net/EventLoop.h"
#include "mario/base/easylogging++.h"
#include <functional>
#include <stdint.h>
#include <unistd.h>
mario::EventLoop* g_loop;
int cnt = 0;
void printTid() {
LOG(INFO) << "pid = " << getpid() << ", tid = " << mario::CurrentThread::tid();
}
void print(const std::string msg) {
LOG(INFO) << "msg: " << msg;
if (++cnt == 20) {
g_loop->quit();
}
}
mario::TimerId toCancel;
void cancelSelf() {
LOG(INFO) << "cancelSelf()";
g_loop->cancel(toCancel);
}
INITIALIZE_EASYLOGGINGPP
int main() {
printTid();
mario::EventLoop loop;
g_loop = &loop;
LOG(INFO) << "main beign";
loop.runAfter(1, std::bind(print, "once 1"));
loop.runAfter(1.5, std::bind(print, "once 1.5"));
loop.runAfter(2.5, std::bind(print, "once 2.5"));
loop.runAfter(3.5, std::bind(print, "once 3.5"));
//loop.runEvery(2, std::bind(print, "every 2"));
mario::TimerId t = loop.runEvery(2, std::bind(print, "every 2"));
loop.runEvery(3, std::bind(print, "every 3"));
loop.runAfter(10, std::bind(&mario::EventLoop::cancel, &loop, t));
toCancel = loop.runEvery(5, cancelSelf);
loop.loop();
LOG(INFO) << "main stop.";
sleep(1);
}
|
Java
|
UTF-8
| 936
| 1.898438
| 2
|
[] |
no_license
|
package com.business.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.business.entity.WorkflowOrder;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Description: business
* <p>
* Created by w_kiven on 2020/12/2 15:43
*/
@Mapper
public interface WorkFlowOrderDao extends BaseMapper<WorkflowOrder> {
List<WorkflowOrder> selectList(String status);
/**
* 根据ID获取任务
*/
WorkflowOrder findById(@Param("jobTaskID") String taskId);
/*查询执行中的产品订单*/
List<WorkflowOrder> selectProductList(String orderStatus);
/*查询执行中的归档订单*/
List<WorkflowOrder> selectDataskList(String orderStatus);
/*查询执行中的QA订单*/
List<WorkflowOrder> selectQataskList(String orderStatus);
WorkflowOrder findDataskByJobId(@Param("jobTaskID") String jobTaskId);
}
|
Python
|
UTF-8
| 2,427
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
# Matt Grimm
# USAFA
# Sonar Test
# 19 October 2016
# Documentation: stackoverflow.com/questions/18994912/ending-an-infinite-while-loop
# electrosome.com/hc-sr04-ultrasonic-sensor-raspberry-pi/
import RPi.GPIO as GPIO
import time
import sys,signal
# This is something I wanted to learn real quick.
# It just allows you to press ctrl-c to exit the program.
def signal_handler(signal,frame):
print("\nprogram exiting")
GPIO.cleanup() # Good practice to cleanup at end.
sys.exit(0) # Exit with no errors.
signal.signal(signal.SIGINT,signal_handler) #Function is signal.signal(). If KEYBOARD INTERRUPT received (ctrl-c), then do the function.
# Setup everything.
GPIO.setmode(GPIO.BCM)
TRIG = 23
GPIO.setup(TRIG,GPIO.OUT)
print("Entering Loop")
while True:
print("Triggered")
for i in range(10):
GPIO.output(TRIG,1)
time.sleep(0.00001) # 10us to trigger to get a reading.
GPIO.output(TRIG,0)
print(i)
print("Waiting...")
time.sleep(2)
# See website for description of how to wire the setup and for additional info
# on how the HC-SR04 works.
# The website shows how to calculate distance effectively.
# I could not do this step becaues I did not have the correct resistors to
# provide the necessary voltage divider to lower the ECHO 5V output to a
# Raspberry Pi GPIO 3.3v rated voltage.
# What I ended up doing was connecting the ECHO output to an LED
# I can see that the LED is responding to the sonar picking SOMETHING up
# but that's about it. It would be nice to later test how accurate Python
# and the sensor are with distances. The website mentions a calibration (IE: use
# a ruler for known distance, then if it is always off by a certain amount, shift
# every reading by that amount. Don't forget to test at multiple distances).
# This could maybe account for Python being slow but may end up causing problems
# down the line if the calibration changes. However, it could prove useful and if
# it was a simple variable, we could change it quickly and easily.
# Important note at the bottom of the website provided: Python is slow when it comes
# to exact measurements due to being a higher level language.
# It would probably be smarter to use Geany to program in C for optimization
# but right now I would like to practice/learn Python while experimenting and not
# optimizing because it is a useful language to write code quickly in.
|
C++
|
UTF-8
| 1,253
| 2.6875
| 3
|
[] |
no_license
|
#include "pch.hpp"
#include "vibrant/mouse.hpp"
#include "vibrant/body.hpp"
namespace vibrant
{
using namespace entityx;
void MouseSystem::update(EntityManager &es, EventManager &events, MouseUpdate mouse)
{
Body::Handle body;
Mouseable::Handle mouseable;
for (entityx::Entity entity : es.entities_with_components(body, mouseable))
{
Mouseable previous_state = *mouseable.get();
bool hover = mouse.position.intersects(body->position, body->size, body->rotation);
mouseable->hover(hover);
bool left_up_on = false;
switch (mouse.left)
{
case ButtonState::Pressed:
mouseable->leftDownOn(hover);
break;
case ButtonState::Released:
mouseable->leftDownOn(false);
left_up_on = hover;
break;
/*
case ButtonState::Down:
break;
case ButtonState::DoubleClicked:
break;
*/
}
// emit events for changes in state
if (mouseable->hover() && !previous_state.hover()) events.emit<MouseEnter>(entity);
if (!mouseable->hover() && previous_state.hover()) events.emit<MouseLeave>(entity);
if (previous_state.leftDownOn() && left_up_on) events.emit<LeftClick>(entity);
}
}
} // namespace vibrant
|
Markdown
|
UTF-8
| 2,853
| 3.046875
| 3
|
[] |
no_license
|
# Parallel Tempering on Hierarchical Hidden Markov Models
The datasets analysed for this study can be found at https://link.springer.com/article/10.1007/s13253-017-0282-9
The R scripts are provided below in chronological order of development (i.e. as presented in the paper).
The average running times for the algorithms is appended at the end of this file.
----------------------------------------
mllk : Negative log-likelihood function and needed packages (based on the code produced by Leos-Barajas)
par.vec0 : Vector of parameter estimates obtained through MLE
MH : Single-update MH algorithm
MH_fun : Function for updating the parameter vector (related to MH)
Block1 : Block-update MH algorithm (Version 1: update of the means of each variable - simultaneously for all the states- is followed by the update of the corresponding standard deviations)
Block1_fun : Function for updating the parameter vector (related to Block1)
Block2 : Block-update MH algorithm (Version 2: update of the means of each all the covariates - simultaneously for all the states- is followed by the update of the standard deviations)
Block2_fun : Function for updating the parameter vector (related to Block1)
MH1 : Single-update MH algorithm (Version 1: related to the ordering adopted in Block1)
MH1_fun : Function for updating the parameter vector (related to MH1)
MH2 : Single-update MH algorithm (Version 2: related to the ordering adopted in Block2)
MH2_fun : Function for updating the parameter vector (related to MH2)
MH_tot : Single-update MH algorithm for the complete parameter set (including transition probabilities)
MH_tot_fun : Function for updating the parameter vector (related to MH_tot)
MH_temp* : MH algorithm with parallel tempering (code not parallelised)
MH_temp_fun* : Function for updating the parameter vector, function for computing the sum of prior distributions (related to MH_temp)
Temp_parallel : MH algorithm with parallel tempering running as many chains as the number of cores minus 1 (parallelised version)
Temp_parallel_fun : Functions for updating the parameter vector, computing the sum of prior distributions, updating of the parameter vector over the total number of iterations (related to Temp_parallel)
-----------------
| Method | Computational Time |
|-------|------------------|
| Frequentist | c. 25 minutes |
| Block1 (21 params) | 2.07 hours |
| Block2 (21 params) | 2.07 hours |
| MH (21 params) | 5.94 hours |
| MH1 (21 params) | 6.16 hours |
| MH2 (21 params) | 6.16 hours |
| MH_tot (51 params) |7.64 hours |
| MH_temp* (21 params, 4 chains) | 1.32 days |
| Temp_parallel (21 params, 4 chains) | 1.04 days |
| Temp_parallel (21 params, 7 chains) | 1.77 days |
-----------------
*Not used in order to derive inference, but as a temporary step for the implementation of the full code.
|
Shell
|
UTF-8
| 819
| 4.09375
| 4
|
[] |
no_license
|
#!/bin/bash
set -u
disk_device=${1:-}
file=
if [[ -f $disk_device ]]; then
file=$disk_device
sudo kpartx -av $file
disk_device=$(losetup --associated $file | cut -d: -f1)
echo "Using loop device: $disk_device for file: $file"
fi
if [[ ! -b $disk_device ]]; then
cat << EOL
Possible disks:
$(sudo lsblk -f)
$(losetup -a)
Usage:
$(basename $0) /dev/sda # use one of the above disks
-or-
$(basename $0) path/to/disk.img
EOL
exit 1
fi
get_wwn_by_device(){
# usage: get_disk_wwn /dev/sdX
ls -l /dev/disk/by-id/ | grep "/$(basename $1)$" | awk '{print $9}' | grep -v wwn
}
disk_id=$(get_wwn_by_device $disk_device)
if [[ -n $disk_id ]]; then
echo "Disk WWN:"
echo
echo " $disk_id"
echo
fi
sudo lsblk -f $disk_device
[[ -n $file ]] && sudo kpartx -d $file
|
C
|
UTF-8
| 1,800
| 2.578125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#pragma once
#include <stdint.h>
enum file_system_service_request
{
FILE_OPEN = 1,
FILE_CLOSE = 2,
FILE_READ = 3,
FILE_WRITE = 4,
GET_FILE_INFO = 5,
FILE_FIND = 6,
GET_SUBDIRECTORY_ENTRY = 7
};
struct raw_file_system_request
{
uint64_t data[128]; // 1ko for file system request, i think we have a lot of space
} __attribute__((packed));
struct file_open_request
{
uint64_t file_request_id; // if = 0 create if not re using the entry and close that file (later)
uint8_t file_directory[255]; // null terminated string
uint8_t mode[10];
} __attribute__((packed));
struct file_close_request
{
uint64_t file_request_id;
} __attribute__((packed));
struct file_read
{
uint8_t *target;
uint64_t at;
uint64_t length;
uint64_t file_request_id;
} __attribute__((packed));
struct file_write
{
uint8_t *data;
uint64_t length;
uint64_t file_request_id;
} __attribute__((packed));
// everything here are not implemented
struct file_find_request
{
uint8_t file_directory[255]; // null terminated string
} __attribute__((packed));
struct file_information
{
uint8_t file_type;
uint64_t access_time;
uint64_t modify_time;
uint64_t created_time;
uint16_t perm;
uint16_t owner_id;
uint16_t group_id;
uint64_t size;
} __attribute__((packed));
struct fill_file_info
{
uint64_t file_request_id;
file_information *target;
} __attribute__((packed));
struct file_system_service_protocol
{
uint16_t request_type;
union
{
raw_file_system_request raw;
file_open_request open;
file_close_request close;
file_read read;
file_write write; // is not implemented
fill_file_info info;
};
} __attribute__((packed));
void file_system_service();
|
Java
|
UTF-8
| 1,660
| 3.328125
| 3
|
[] |
no_license
|
package com.dsa.quicksort;
import java.util.Arrays;
public class QuickSortImpl implements QuickSort {
public static int[] unsortedArray = {11,16,2,8,1,9,4,7,91,17,1,90,16,15,4,3,2,90};
@Override
public int partition(int[] array,int beg,int end) {
System.out.println(array);
int partitionIndex = 0;
int pivot=array[end];
int pivotIndex=end;
int current=beg;
int index=beg;
for(int i=current;i<=end;i++,current++){
if(current<pivotIndex){
if(array[current]<pivot){
int temp=array[current];
array[current]=array[index];
array[index]=temp;
System.out.println(array);
index++;
}
}
else{
int temp0=array[pivotIndex];
array[pivotIndex]=array[index];
array[index]=temp0;
partitionIndex=index;
System.out.println(array);
}
}
return partitionIndex;
}
@Override
public void quickSort(int[] unsortedArray,int beg,int end) {
if(beg<end) {
int partitionIndex=partition(unsortedArray,beg,end);
quickSort(unsortedArray, 0, partitionIndex - 1);
quickSort(unsortedArray, partitionIndex + 1, end);
}
System.out.println(unsortedArray);
// Arrays.sort(unsortedArray);
}
public static void main(String[] args) {
QuickSort quickSort = new QuickSortImpl();
quickSort.quickSort(unsortedArray,0,unsortedArray.length-1);
}
}
|
Python
|
UTF-8
| 2,089
| 2.5625
| 3
|
[] |
no_license
|
# coding: utf-8
import tensorflow as tf
import math
import data_helpers
import sequence_labelling_model_bidirectional
sequences, labels = data_helpers.load_and_pad_seqences_and_labels()
sequences, labels = data_helpers.shuffle_data_and_labels(sequences, labels)
seq_train, seq_dev, labels_train, labels_dev = data_helpers.partition_data_and_labels(sequences, labels, 0.1)
x = tf.placeholder(dtype=tf.float32, shape=[None] + list(sequences.shape)[1:])
y = tf.placeholder(dtype=tf.float32, shape=[None] + list(labels.shape)[1:])
def GRU_cell(cell_size):
rnn_cell = tf.contrib.rnn.BasicLSTMCell(cell_size)
return rnn_cell
params = dict()
params["rnn_cell"] = GRU_cell
params["rnn_cell_size"] = 200
params["optimizer"] = tf.train.RMSPropOptimizer(0.002)
params["gradient_clipping"] = 0.0
model = sequence_labelling_model_bidirectional.SequenceLabellingModel(x,
y,
params)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
num_epochs = 100
for epoch in range(num_epochs):
print("-epoch {}:".format(epoch))
generator = data_helpers.batch_generator(seq_train,
labels_train,
100)
for i, seq_batch, labels_batch in generator:
feed_dict = {}
feed_dict[model.sequences] = seq_batch
feed_dict[model.labels] = labels_batch
_, loss, acc = sess.run([model.optimizer, model.loss, model.accuracy],
feed_dict)
# print("{} - loss: {}, accuracy: {}".format(i, loss, acc))
print("evaluating...")
feed_dict = {}
feed_dict[model.sequences] = seq_dev
feed_dict[model.labels] = labels_dev
loss, acc = sess.run([model.loss, model.accuracy],
feed_dict)
print("loss: {}, accuracy: {}".format(loss, acc))
|
Python
|
UTF-8
| 2,465
| 3.5625
| 4
|
[] |
no_license
|
import unittest
import sys
def custom_sort(arr):
"""
Your sorting algorithm here
"""
pass
def is_not_in_descending_order(a):
"""
Check if the list is not descending (means "rather ascending")
"""
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
return False
return True
class TestSort(unittest.TestCase):
def test_simple_cases(self):
self.cases = ([1], [], [1, 2], [1, 2, 3, 4, 5],
[4, 2, 5, 1, 3], [5, 4, 4, 5, 5],
list(range(1, 10)), list(range(9, 0, -1)))
for b in self.cases:
with self.subTest(case=b):
a = list(b)
sort_algorithm(a)
self.assertCountEqual(a, b, msg="Elements changed. a = " + str(a))
self.assertTrue(is_not_in_descending_order(a), msg="List not sorted. a = " + str(a))
def test_stability(self):
self.cases = ([[0] for _ in range(5)],
[[1, 2], [2, 2], [2, 3], [2, 2], [2, 3], [1, 2]],
[[5, 2], [10, 5], [5, 2], [10, 5], [5, 2], [10, 5]])
for b in self.cases:
with self.subTest(case=b):
a = list(b)
sort_algorithm(a)
b.sort() # here we are cheating: standard sort is stable
# to test stability we will check a[i] is b[i]
self.assertTrue(all(x is y for x, y in zip(a, b)))
def test_universality(self):
self.cases = ([4, 2, 8], list('abcdefg'),
[True, False],
[float(i) / 10 for i in range(10, 0, -1)],
[[1, 2], [2], [3, 4], [3, 4, 5], [6, 7]])
for b in self.cases:
with self.subTest(case=b):
a = list(b)
sort_algorithm(a)
self.assertCountEqual(a, b, msg="Elements changed. a = " + str(a))
self.assertTrue(is_not_in_descending_order(a), msg="List not sorted. a = " + str(a))
def sort_test_suite():
suite = unittest.TestSuite()
suite.addTest(TestSort('test_simple_cases'))
suite.addTest(TestSort('test_stability'))
suite.addTest(TestSort('test_universality'))
return suite
runner = unittest.TextTestRunner(stream=sys.stdout, verbosity=1)
for algo in (custom_sort,):
print('Testing function:', algo.__name__)
test_suite = sort_test_suite()
sort_algorithm = algo
runner.run(test_suite)
|
Shell
|
UTF-8
| 434
| 3.140625
| 3
|
[] |
no_license
|
VERSION=3350500
set -e
cd `dirname $0`
mkdir -p downloads
cd downloads
if [ ! -f sqlite-amalgamation-${VERSION}.zip ]; then
curl https://www.sqlite.org/2021/sqlite-amalgamation-${VERSION}.zip -o sqlite-amalgamation-${VERSION}.zip
fi
cd -
mkdir -p tmp
cd tmp
unzip ../downloads/sqlite-amalgamation-${VERSION}.zip
cp sqlite-amalgamation-${VERSION}/*.h ../include/
cp sqlite-amalgamation-${VERSION}/*.c ../src/
cd -
rm -fr tmp
|
Java
|
UTF-8
| 1,603
| 1.789063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.hswebframework.payment.payment.service;
import org.hswebframework.payment.payment.entity.PaymentOrderEntity;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.service.*;
import java.util.Date;
import java.util.List;
/**
* @author zhouhao
* @since 1.0.0
*/
public interface LocalPaymentOrderService extends
InsertService<PaymentOrderEntity, String>,
CreateEntityService<PaymentOrderEntity>,
QueryByEntityService<PaymentOrderEntity>,
QueryService<PaymentOrderEntity, String>,
UpdateService<PaymentOrderEntity, String> {
List<PaymentOrderEntity> queryPayingOrder(Date createTimeLt,int pageSize);
int updateTimeoutStatus(List<String> paymentIdList);
/**
* 动态查询商户订单
* @param entity
* @return
*/
PagerResult<PaymentOrderEntity> queryMerchantOrder(QueryParamEntity entity);
/**
* 商户根据ID查询order
* @param merchantId
* @param orderId
* @return
*/
PaymentOrderEntity queryOrderByMerchantIdAndOrderId(String merchantId,String orderId);
/**
* 代理商查询商户的订单
* @param agentId
* @param merchantId
* @return
*/
List<PaymentOrderEntity> queryAgentSingleMerchantOrder(String agentId,String merchantId);
PagerResult<PaymentOrderEntity> queryAgentAllMerchantOrder(String agentId, QueryParamEntity paramEntity);
PaymentOrderEntity queryOrderByIdAndMerchantId(String merchantId,String orderId);
}
|
C#
|
UTF-8
| 6,480
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using NLog;
namespace adrilight
{
internal class SerialStream : IDisposable
{
private ILogger _log = LogManager.GetCurrentClassLogger();
// private readonly byte[] _messagePreamble = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09};
static byte[] bytes = BitConverter.GetBytes(Settings.LedsPerSpot * SpotSet.Spots.Length - 1);
private readonly byte[] _messagePreamble = { 0x41, 0x64, 0x61, bytes[1], bytes[0], 0x00 };
private Thread _workerThread;
private CancellationTokenSource _cancellationTokenSource;
private readonly Stopwatch _stopwatch = new Stopwatch();
public void Start()
{
_log.Debug("Start called.");
if (_workerThread != null) return;
_cancellationTokenSource = new CancellationTokenSource();
_workerThread = new Thread(DoWork)
{
Name = "Serial sending",
IsBackground = true
};
_workerThread.Start(_cancellationTokenSource.Token);
}
public void Stop()
{
_log.Debug("Stop called.");
if (_workerThread == null) return;
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = null;
_workerThread?.Join();
_workerThread = null;
}
public bool IsRunning => _workerThread != null && _workerThread.IsAlive;
private byte[] GetOutputStream()
{
byte[] outputStream;
int counter = _messagePreamble.Length;
lock (SpotSet.Lock)
{
const int colorsPerLed = 3;
outputStream = new byte[_messagePreamble.Length + (Settings.LedsPerSpot*SpotSet.Spots.Length*colorsPerLed)];
Buffer.BlockCopy(_messagePreamble, 0, outputStream, 0, _messagePreamble.Length);
// Reverse order of LEDs, if you mounted them the other way around the screen
if (Settings.Reverse)
{
for (int j = SpotSet.Spots.Length - 1; j >= 0; j--)
{
for (int i = 0; i < Settings.LedsPerSpot; i++)
{
outputStream[counter++] = SpotSet.Spots[j].Green; // green
outputStream[counter++] = SpotSet.Spots[j].Red; // red
outputStream[counter++] = SpotSet.Spots[j].Blue; // blue
}
}
}
else
{
foreach (Spot spot in SpotSet.Spots)
{
for (int i = 0; i < Settings.LedsPerSpot; i++)
{
outputStream[counter++] = spot.Green; // green
outputStream[counter++] = spot.Red; // red
outputStream[counter++] = spot.Blue; // blue
}
}
}
}
return outputStream;
}
private void DoWork(object tokenObject)
{
var cancellationToken = (CancellationToken) tokenObject;
SerialPort serialPort = null;
if (String.IsNullOrEmpty(Settings.ComPort))
{
return;
}
//retry after exceptions...
while (!cancellationToken.IsCancellationRequested)
{
try
{
const int baudRate = 1000000;
string openedComPort = null;
while (!cancellationToken.IsCancellationRequested)
{
//open or change the serial port
if (openedComPort != Settings.ComPort)
{
serialPort?.Close();
serialPort = new SerialPort(Settings.ComPort, baudRate);
serialPort.Open();
openedComPort = Settings.ComPort;
}
//send frame data
byte[] outputStream = GetOutputStream();
serialPort.Write(outputStream, 0, outputStream.Length);
/*
//ws2812b LEDs need 30 µs = 0.030 ms for each led to set its color so there is a lower minimum to the allowed refresh rate
//receiving over serial takes it time as well and the arduino does both tasks in sequence
//+1 ms extra safe zone
var fastLedTime = (outputStream.Length - _messagePreamble.Length)/3.0*0.030d;
var serialTransferTime = outputStream.Length*10.0*1000.0/baudRate;
var minTimespan = (int) (fastLedTime + serialTransferTime) + 1;
*/
var minTimespan = 6;
Task.Delay(minTimespan, cancellationToken).Wait(cancellationToken);
MainForm.FPS_Serial++;
}
}
catch (OperationCanceledException)
{
_log.Debug("OperationCanceledException catched. returning.");
return;
}
catch (Exception ex)
{
_log.Debug(ex, "Exception catched.");
//to be safe, we reset the serial port
if (serialPort != null && serialPort.IsOpen)
{
serialPort.Close();
}
serialPort?.Dispose();
serialPort = null;
}
finally
{
if (serialPort != null && serialPort.IsOpen)
{
serialPort.Close();
serialPort.Dispose();
}
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Stop();
}
}
}
}
|
JavaScript
|
UTF-8
| 2,490
| 2.75
| 3
|
[] |
no_license
|
'use strict';
/**
* Config object
* It consists of configs for:
* Robot class
* Messenger class
* Playground class
*/
var config = {};
var path = require('path');
module.exports = config;
config.app = {
root: path.resolve(__dirname),
},
config.playground = {
startPointX: 0,
startPointY: 0,
lengthX: 5,
lengthY: 5
};
config.robot = {
aCommands: ['PLACE', 'MOVE', 'LEFT', 'RIGHT', 'REPORT'],
initialCommands: ['PLACE'],
aDirections: ['NORTH', 'EAST', 'SOUTH', 'WEST']
};
config.messenger = {
oMsgs: {
noInitialCommand: 'Warning! You haven\'t placed the robot on the playground yet. Type "PLACE X, Y, F" {ci} to put a robot on the playground.',
placeRobotFirst: 'Nothing to report - the robot is not on the playground yet. Place it first to begin - PLACE X, Y, F.',
wrongPlace: 'Warning! You cannot place the robot in that square, it can fall. That square is out of the playground.',
wrondDirection: 'Error! No such a direction. Available directions are: {availableDirections}',
noFace: 'Error! No FACE was provided. Correct form is: PLACE X, Y, FACE.',
faceNotString: 'Error! FACE is not a string.',
unknownCommand: 'Error! Command is incorrect or unknown. Available commands are: {availableCommands}',
robotPosition: 'Robot\'s position is: {x}, {y}, {f}',
noNegativeCoordinates: 'Error! No negative X or Y allowed. Try again.',
nonIntCoordinates: 'Warning! X and Y must be integers.',
wrongMove: 'Warning! You cannot move the robot that way, it can fall.',
default: 'Welcome to The Toy Robot game. Start with placing a robot typing PLACE X, Y, F {ci}.',
someCombinedMsg: 'For the {s} of testing: PLACE {x}, {y}, {z} in {country}',
fileNotFound: 'Error! File \'{fileName}\' was not found. Make sure you specified its path correctly.',
welcome: 'Welcome!{eol}Tell the Robot your first command. Begin by placing the Robot on the playground - PLACE X, Y, F {ci}. \'q\' to exit.',
},
oSubs: {
availableDirections: config.robot.aDirections.join(', '),
availableCommands: [config.robot.aCommands.reduce(function(prev,
cur) {
if (prev == 'PLACE')
prev = [prev, 'X, Y, F'].join(' ');
return prev + ' | ' + cur;
}), '.'].join(''),
ci: '(case insensitive, spaces are acceptable instead of commas)',
country: 'Dreamland'
}
};
|
Java
|
UTF-8
| 445
| 1.765625
| 2
|
[] |
no_license
|
package com.songshu.third_part_tools;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class ExportVo implements Serializable{
@ExcelFiled(colName="游戏名称")
public String gameName;
@ExcelFiled(colName="渠道名称")
public String channelName;
@ExcelFiled(colName="日期",dateFormat="yyyy-MM-dd HH:mm:ss")
public Date date;
@ExcelFiled(colName="金额",precision=2)
public double price;
}
|
PHP
|
UTF-8
| 1,553
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Rules;
use App\Link;
use Illuminate\Contracts\Validation\Rule;
class ValidateAliasRule implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$conditions = [];
$conditions[] = ['alias', '=', $value];
// If the query is for a specific link
if (request()->route('id')) {
// Exclude the link when validating the alias
$conditions[] = ['id', '!=', request()->route('id')];
$link = Link::findOrFail(request()->route('id'));
$conditions[] = ['domain_id', '=', $link->domain->id ?? null];
} else {
// If the request has a link under a domain
if (request()->input('domain')) {
$conditions[] = ['domain_id', '=', request()->input('domain')];
}
// Check for links that are not under a domain
else {
$conditions[] = ['domain_id', '=', null];
}
}
if (Link::where($conditions)->exists()) {
return false;
}
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return __('validation.unique');
}
}
|
PHP
|
UTF-8
| 5,328
| 3.015625
| 3
|
[] |
no_license
|
<?php
namespace Anax\Book\HTMLForm;
use Anax\HTMLForm\FormModel;
use Psr\Container\ContainerInterface;
use Anax\Book\Book;
/**
* Form to update an item.
*/
class UpdateForm extends FormModel
{
/**
* Constructor injects with DI container and the id to update.
*
* @param Psr\Container\ContainerInterface $di a service container
* @param integer $id to update
*/
public function __construct(ContainerInterface $di, $id)
{
parent::__construct($di);
$book = $this->getItemDetails($id);
$this->form->create(
[
"id" => __CLASS__,
"legend" => "Update details of the item",
],
[
"id" => [
"type" => "text",
"validation" => ["not_empty"],
"readonly" => true,
"value" => $book->id,
],
"title" => [
"type" => "text",
"validation" => ["not_empty"],
"value" => $book->title,
],
"author" => [
"type" => "text",
"validation" => ["not_empty"],
"value" => $book->author,
],
"pages" => [
"type" => "number",
"validation" => ["not_empty"],
"value" => $book->pages,
],
"published" => [
"type" => "date",
"value" => $book->published,
],
"image" => [
"type" => "url",
"value" => $book->image,
],
"category" => [
"type" => "select-multiple",
"label" => "Select one or more category:",
"size" => 6,
"options" => [
"art" => "art & photographi",
"biography" => "biography",
"children" => "children",
"craft & hobbies" => "hobbies",
"crime" => "crime",
"thriller" => "thriller",
"fiction" => "fiction",
"food" => "food",
"anime" => "anime",
"history" => "history",
"drama" => "drama",
"poetry" => "poetry",
"fantasy" => "fantasy",
"horror" => "horror",
"science" => "science",
"health" => "health",
"humour" => "humour",
"computing" => "computing",
"education" => "education",
],
"checked" => [$book->category],
],
"submit" => [
"type" => "submit",
"value" => "Save",
"callback" => [$this, "callbackSubmit"]
],
"reset" => [
"type" => "reset",
],
]
);
}
/**
* Get details on item to load form with.
*
* @param integer $id get details on item with id.
* @return Book
*/
public function getItemDetails($id) : object
{
$book = new Book();
$book->setDb($this->di->get("dbqb"));
$book->find("id", $id);
return $book;
}
/**
* Callback for submit-button which should return true if it could
* carry out its work and false if something failed.
*
* @return bool true if okey, false if something went wrong.
*/
public function callbackSubmit() : bool
{
$book = new Book();
$book->setDb($this->di->get("dbqb"));
$book->find("id", $this->form->value("id"));
$book->title = $this->form->value("title");
$book->author = $this->form->value("author");
$book->pages = $this->form->value("pages");
$book->published = $this->form->value("published");
$book->image = $this->form->value("image");
$book->category = implode(", ", $this->form->value("category"));
$book->save();
return true;
}
// /**
// * Callback what to do if the form was successfully submitted, this
// * happen when the submit callback method returns true. This method
// * can/should be implemented by the subclass for a different behaviour.
// */
// public function callbackSuccess()
// {
// $this->di->get("response")->redirect("book")->send();
// //$this->di->get("response")->redirect("book/update/{$book->id}");
// }
// /**
// * Callback what to do if the form was unsuccessfully submitted, this
// * happen when the submit callback method returns false or if validation
// * fails. This method can/should be implemented by the subclass for a
// * different behaviour.
// */
// public function callbackFail()
// {
// $this->di->get("response")->redirectSelf()->send();
// }
}
|
Java
|
UTF-8
| 78
| 1.75
| 2
|
[] |
no_license
|
package com.kdc.interfaces;
public interface ITest {
void sayHello();
}
|
Java
|
UTF-8
| 1,193
| 2.34375
| 2
|
[] |
no_license
|
package top.duyt.web.user.dto;
public class IndexImgDto {
/**
* 已上传的主页图片id
*/
private int imgId;
/**
* 主标题
*/
private String mainTitle;
/**
* 副标题
*/
private String subTitle;
/**
* 连接
*/
private String link;
/**
* 图像剪切起始的纵轴坐标
*/
private int cropedY;
public IndexImgDto() {
}
public IndexImgDto(int imgId, String mainTitle, String subTitle,
String link, int cropedY) {
this.imgId = imgId;
this.mainTitle = mainTitle;
this.subTitle = subTitle;
this.link = link;
this.cropedY = cropedY;
}
public int getImgId() {
return imgId;
}
public void setImgId(int imgId) {
this.imgId = imgId;
}
public String getMainTitle() {
return mainTitle;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public int getCropedY() {
return cropedY;
}
public void setCropedY(int cropedY) {
this.cropedY = cropedY;
}
}
|
Rust
|
UTF-8
| 4,651
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
use std::env;
use std::io::prelude::*;
use std::fs::File;
/// Struct representing the interpreter state
///
/// # todo list
/// * implement it
pub struct Interpreter {
/// Instruction pointer
ip: usize,
/// Data pointer
dp: usize,
/// Brainfuck machine memory
mem: Box<[u8]>,
/// Source code
prog: Vec<u8>,
}
/// Minimal memory size according to [Wikipedia](https://en.wikipedia.org/wiki/Brainfuck)
const MEMORY_SIZE: usize = 30000;
impl Interpreter {
/// Create new interpreter with empty program and default memory size.
pub fn new() -> Interpreter {
Interpreter {
ip: 0,
dp: 0,
mem: Box::new([0u8; MEMORY_SIZE]),
prog: Vec::new(),
}
}
/// Read tape with program (where 'tape' is represented by string)
/// Return number of valid brainfuck characters
pub fn read_tape(&mut self, input: String) -> usize {
let mut count = 0;
for c in input.chars() {
match c {
'+' | '-' | '>' | '<' | '[' | ']' | '.' | ',' => {
self.prog.push(c as u8);
count += 1;
},
_ => {}
}
}
count
}
/// Read next bf instruction
fn read_next_instruction(&mut self) {
match self.prog[self.ip] {
b'+' => {
self.mem[self.dp] += 1;
self.ip += 1;
},
b'-' => {
self.mem[self.dp] -= 1;
self.ip += 1;
},
b'<' => {
self.dp -= 1;
self.ip += 1;
},
b'>' => {
self.dp += 1;
self.ip += 1;
},
b'[' => {
if self.mem[self.dp] != 0 {
self.ip += 1;
} else {
while self.prog[self.ip] != b']' {
self.ip += 1;
}
self.ip += 1;
}
},
b']' => {
if self.mem[self.dp] != 0 {
while self.prog[self.ip] != b'[' {
self.ip -= 1;
}
}
self.ip += 1;
},
b'.' => {
print!("{}", self.mem[self.dp] as char);
self.ip += 1;
},
_ => {}
}
}
/// Run brainfuck program
pub fn run(&mut self) {
self.ip = 0;
self.dp = 0;
while self.ip < self.prog.len() {
self.read_next_instruction();
}
}
}
fn main() {
// Prints each argument on a separate line
let mut args = env::args();
let mut file_name;
match args.nth(1) {
Some(str) => {
file_name = str.clone()
},
None => {
println!("Usage: bfi <file name>");
return;
}
}
let mut file = File::open(file_name).unwrap();
let mut tape = String::new();
file.read_to_string(&mut tape);
let mut a = Interpreter::new();
a.read_tape(tape);
a.run();
}
#[cfg(test)]
#[test]
#[should_panic]
fn test_sth() {
panic!("Test");
}
#[cfg(test)]
#[test]
fn test_tape_reading() {
let mut bfi = Interpreter::new();
let ret = bfi.read_tape("abcd*()@+-[]<>.,".to_string());
assert!(bfi.prog == b"+-[]<>.,");
assert!(ret == 8);
}
#[cfg(test)]
#[test]
fn test_read_instruction() {
let mut bfi = Interpreter::new();
bfi.read_tape("+".to_string());
bfi.read_next_instruction();
assert!(bfi.mem[0] == 1);
let mut bfi = Interpreter::new();
let prog = "++-".to_string();
let len = prog.len();
bfi.read_tape(prog);
for _ in 0..len {
bfi.read_next_instruction();
}
assert!(bfi.mem[0] == 1);
let mut bfi = Interpreter::new();
let prog = ">+".to_string();
let len = prog.len();
bfi.read_tape(prog);
for _ in 0..len {
bfi.read_next_instruction();
}
assert!(bfi.mem[1] == 1);
let mut bfi = Interpreter::new();
let prog = ">><+".to_string();
let len = prog.len();
bfi.read_tape(prog);
for _ in 0..len {
bfi.read_next_instruction();
}
assert!(bfi.mem[1] == 1);
let mut bfi = Interpreter::new();
bfi.read_tape("[+++>>>]+++++".to_string());
bfi.read_next_instruction();
assert!(bfi.ip == 8);
let mut bfi = Interpreter::new();
bfi.read_tape("++[+-><]+".to_string());
bfi.mem[0] = 2;
bfi.ip = 7;
bfi.read_next_instruction();
assert!(bfi.ip == 3);
}
|
Python
|
UTF-8
| 276
| 2.84375
| 3
|
[] |
no_license
|
#nose testexample
#nosetests nose1.py
import unittest
class TddInPythonExample(unittest.TestCase):
def test_calculator_add_method_returns_correct_result(self):
calc = Calculator()
result = calc.add(2,2)
self.assertEqual(4, result)
|
Python
|
UTF-8
| 801
| 4.5
| 4
|
[] |
no_license
|
def cheese_and_crackers( cheese_count, boxes_of_crackers ):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers( 20, 30 )
print "OR, we can use variables from our script:"
# these variables are unique from the variables inside the function, since
# the scope of the variable is different
cheese_count = 10
boxes_of_crackers = 50
cheese_and_crackers( cheese_count, boxes_of_crackers )
print "We can even do math inside too:"
cheese_and_crackers( 10 + 20, 5 + 6 )
print "And we can combine the two, variables and math:"
cheese_and_crackers( cheese_count + 100, boxes_of_crackers + 1000 )
|
PHP
|
UTF-8
| 839
| 3.046875
| 3
|
[] |
no_license
|
<?php
$path = "pub/media/csv/Sullivans_Web_Price_List_New.txt";
if(file_exists($path))
{
$handle = fopen($path, "r");
$lines = [];
if (($handle = fopen($path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 2000, "\t")) !== FALSE) {
$lines[] = $data;
}
fclose($handle);
}
$dataArray = $lines;
//Code for creating CSV for Magento2 products
$filePath = 'pub/media/csv/Sullivans_Web_Price_List_New.csv';
$fh1 = @fopen($filePath, 'w');
foreach ( $dataArray as $data1 ) {
// Put the data into the stream
fputcsv($fh1, $data1);
}
// Close the file
fclose($fh1);
// Make sure nothing else is sent, our file is done
echo "CSV file have been generated on path :".$filePath;
}
else
{
echo "File -".$path ."doesn't exists!";
}
exit;
|
C++
|
UTF-8
| 1,176
| 3.03125
| 3
|
[] |
no_license
|
#include "Hypnowheel_Lib.h"
#include <Arduino.h>
// Abstraction for turning on an entire LED
void ledOn(byte led) {
led = led * 3; // Convert LED number to the pin number
ledArray[led].state = ON;
ledArray[led+1].state = ON;
ledArray[led+2].state = ON;
// Each LED is RBG and a set of three pins
// Color functionality will come later
}
// Abstraction for turning off an entire LED
void ledOff(byte led) {
led = led * 3; // Convert LED number to the pin number
ledArray[led].state = OFF;
ledArray[led+1].state = OFF;
ledArray[led+2].state = OFF;
// This one should be fine since LED off should
// turn off all pins
}
// Abstraction for turning on individual pins
void pinOn(byte led) {
ledArray[led].state = ON;
}
// Abstraction for turning off individual pins
void pinOff(byte led) {
ledArray[led].state = OFF;
}
// Abstraction for updating the LED display
void refresh() {
unsigned int i;
for(i = 0; i < NUM_LEDS*3; i++) {
if(ledArray[47-i].state == ON) {
digitalWrite(SDI, HIGH);
}
else {
digitalWrite(SDI, LOW);
}
digitalWrite(CLK, HIGH);
digitalWrite(CLK, LOW);
}
digitalWrite(LE, HIGH);
digitalWrite(LE, LOW);
}
|
PHP
|
UTF-8
| 2,554
| 2.765625
| 3
|
[] |
no_license
|
<?php
include_once '../src/GildedRose.php';
include_once '../test/ItemBuilder.php';
class GildedRoseTest extends PHPUnit_Framework_TestCase {
public function test_items_degradan_calidad(
) {
$unItem = ItemBuilder::newItem()
->withQuality(5)
->build();
GildedRose::updateQuality(array($unItem));
$this->assertEquals(4, $unItem->quality);
}
public function test_venta_pasada_calidad_degrada_doble(
) {
$unItem = ItemBuilder::newItem()
->withSellIn(-1)
->withQuality(5)
->build();
GildedRose::updateQuality(array($unItem));
$this->assertEquals(3, $unItem->quality);
}
public function test_calidad_nunca_negativa(
) {
$unItem = ItemBuilder::newItem()
->withQuality(0)
->build();
GildedRose::updateQuality(array($unItem));
$this->assertEquals(0, $unItem->quality);
}
public function test_aged_brie_incrementa_calidad(
) {
$agedBrie = ItemBuilder::newItem()
->withName("Aged Brie")
->withQuality(5)
->build();
GildedRose::updateQuality(array($agedBrie));
$this->assertEquals(6, $agedBrie->quality);
}
public function test_calidad_nunca_mayor_de_50(
) {
$agedBrie = ItemBuilder::newItem()
->withName("Aged Brie")
->withQuality(50)
->build();
GildedRose::updateQuality(array($agedBrie));
$this->assertEquals(50, $agedBrie->quality);
}
public function test_sulfuras_no_cambia(
) {
$sulfuras = ItemBuilder::newItem()
->withName("Sulfuras, Hand of Ragnaros")
->withSellIn(10)
->withQuality(10)
->build();
GildedRose::updateQuality(array($sulfuras));
$this->assertEquals(10, $sulfuras->sellIn);
$this->assertEquals(10, $sulfuras->quality);
}
public static function backstage_rules(
) {
return array(
"incr. 1 si sellIn > 10" => array(11, 10, 11),
"incr. 2 si 5 < sellIn <= 10 (max)" => array(10, 10, 12),
"incr. 2 si 5 < sellIn <= 10 (min)" => array(6, 10, 12),
"incr. 3 si 0 < sellIn <= 5 (max)" => array(5, 10, 13),
"incr. 3 si 0 < sellIn <= 5 (min)" => array(1, 10, 13),
"se pone a 0 si sellIn <= 0 (max)" => array(0, 10, 0),
"se pone a 0 si sellIn <= 0 (...)" => array(-1, 10, 0)
);
}
/**
* @dataProvider backstage_rules
*/
public function test_backstage_passes_incrementan_calidad_cada_vez_mas(
$sellIn,
$quality,
$expected
) {
$pass = ItemBuilder::newItem()
->withName("Backstage passes to a TAFKAL80ETC concert")
->withSellIn($sellIn)
->withQuality($quality)
->build();
GildedRose::updateQuality(array($pass));
$this->assertEquals($expected, $pass->quality);
}
}
?>
|
Java
|
UTF-8
| 411
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.aop.domain;
import org.springframework.stereotype.Component;
@Component
public class TestBeanImpl implements TestBean {
private String testStr = "testStr";
public String getTestStr() {
return testStr;
}
public void setTestStr(String testStr) {
this.testStr = testStr;
}
public void test(int numberA, int numberB) {
System.out.println("目标方法执行: "+ numberA/numberB);
}
}
|
Go
|
UTF-8
| 3,747
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
package manifest
import (
"fmt"
"reflect"
"testing"
"github.com/1dustindavis/gorilla/pkg/config"
)
var (
// store original data to restore after each test
origCachePath = config.CachePath
origManifest = config.Current.Manifest
origURL = config.Current.URL
origDownloadFile = downloadFile
origCatalogs = config.Current.Catalogs
)
// TestGetManifest verifies a single manifest is processed correctly
func TestGetManifest(t *testing.T) {
// Override the cachepath to use our test directory
config.CachePath = "testdata/"
defer func() { config.CachePath = origCachePath }()
// Store the actual result of `getManifest`
actualManifest := getManifest("example_manifest")
// Define what we expect it to return
expectedManifest := Item{
Name: "example_manifest",
Includes: []string{"included_manifest"},
Installs: []string{"Chocolatey", "GoogleChrome"},
Uninstalls: []string{"AdobeFlash"},
Updates: []string{"ChefClient", "CanonDrivers"},
}
// Compare the actual result with our expectations
structsMatch := reflect.DeepEqual(expectedManifest, actualManifest)
if !structsMatch {
t.Errorf("\nExpected: %#v\nActual: %#v", expectedManifest, actualManifest)
}
}
// TestGet verifies that multiple manifests are processed correctly
func TestGet(t *testing.T) {
// Override the cachepath and top manifest to use our test directory
config.CachePath = "testdata/"
config.Current.Manifest = "example_manifest"
config.Current.URL = "http://example.com/"
downloadFile = fakeDownload
defer func() {
config.CachePath = origCachePath
config.Current.Manifest = origManifest
config.Current.URL = origURL
downloadFile = origDownloadFile
}()
// Store the actual slice of manifest items from `Get`
actualManifests := Get()
// Define the slice of manifest items we expect it to return
expectedManifests := []Item{
{
Name: "example_manifest",
Includes: []string{"included_manifest"},
Installs: []string{"Chocolatey", "GoogleChrome"},
Uninstalls: []string{"AdobeFlash"},
Updates: []string{"ChefClient", "CanonDrivers"},
},
{
Name: "included_manifest",
Includes: []string(nil),
Installs: []string{"TestInstall1", "TestInstall2"},
Uninstalls: []string{"TestUninstall1", "TestUninstall2"},
Updates: []string{"TestUpdate1", "TestUpdate2"},
},
}
// Compare the actual result with our expectations
structsMatch := reflect.DeepEqual(expectedManifests, actualManifests)
if !structsMatch {
t.Errorf("\nExpected: %#v\nActual: %#v", expectedManifests, actualManifests)
}
}
// TestGetCatalogs verifies that catalogs included in a manifest get added to the config
func TestGetCatalogs(t *testing.T) {
// Override the cachepath, manifest, and catalogs
config.Current.Catalogs = []string{"alpha", "beta"}
config.CachePath = "testdata/"
config.Current.Manifest = "example_manifest_catalogs"
config.Current.URL = "http://example.com/"
downloadFile = fakeDownload
defer func() {
config.Current.Catalogs = origCatalogs
config.CachePath = origCachePath
config.Current.Manifest = origManifest
config.Current.URL = origURL
downloadFile = origDownloadFile
}()
// Run Get() to process the manifests and (hopefully) append the catalogs
Get()
// Define our expected catalogs
expectedCatalogs := []string{"alpha", "beta", "production1", "production2"}
// Compare our expectations to the actual catalogs
slicesMatch := reflect.DeepEqual(expectedCatalogs, config.Current.Catalogs)
if !slicesMatch {
t.Errorf("\nExpected: %#v\nActual: %#v", expectedCatalogs, config.Current.Catalogs)
}
}
func fakeDownload(string1 string, string2 string) error {
fmt.Println(string1)
fmt.Println(string2)
return nil
}
|
Python
|
UTF-8
| 6,030
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
from PIL import Image
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms, datasets, models
from torch import optim
class Network(nn.Module):
"""Neural Network"""
def __init__(self, input_units, output_units, hidden_units, drop_p=0.5):
"""Initialize Network."""
super().__init__()
self.hidden_layers = nn.ModuleList([nn.Linear(input_units, hidden_units[0])])
layer_sizes = zip(hidden_units[:-1], hidden_units[1:])
self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])
self.output = nn.Linear(hidden_units[-1], output_units)
self.dropout = nn.Dropout(p=drop_p)
def forward(self, x):
"""forward pass"""
for linear in self.hidden_layers:
x = F.relu(linear(x))
x = self.dropout(x)
x = self.output(x)
return F.log_softmax(x, dim=1)
def validation(model, validationloader, optimizer, criterion, device):
"""Validation pass."""
test_loss = 0
accuracy = 0
correct = 0
total = 0
for inputs, labels in validationloader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
test_loss += loss.item()
ps = torch.exp(outputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
return test_loss, accuracy
def deep_learning(model, trainloader, validationloader,criterion, optimizer, epochs, print_every, device):
"""Trains the neural network."""
epochs = epochs
print_every = print_every
steps = 0
model.to(device)
for e in range(epochs):
running_loss = 0
model.train()
for inputs, labels in trainloader:
steps += 1
# Transfering tensors to GPU
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
# Forward and backward pass
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
model.eval()
with torch.no_grad():
test_loss, accuracy = validation(model, validationloader, optimizer, criterion, device)
print("Epoch: {}/{}...".format(e+1, epochs),
"Training Loss: {:.3f}...".format(running_loss/print_every),
"Test Loss: {:.3f}...".format(test_loss/len(validationloader)),
"Test Accuracy: {:.3f}...".format(accuracy))
running_loss = 0
return model
def check_accuracy_on_test(model, testloader, optimizer, criterion, device):
"""Check accuracy on the test data."""
correct = 0
total = 0
model.to(device)
model.eval()
with torch.no_grad():
for inputs, labels in testloader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model.forward(inputs)
ps = torch.exp(outputs)
_, predicted = torch.max(ps.data, 1)
total += labels.size(0)
correct += (predicted == labels.data).sum().item()
print('Accuracy of the network on test images: %d %%' % (100 * correct / total))
print(correct)
print(total)
def load_checkpoint(filepath):
"""Load and return a model from a checkpoint"""
checkpoint = torch.load(filepath)
model = eval(checkpoint['model'])
classifier = Network(checkpoint['input_size'], checkpoint['output_size'], checkpoint['hidden_size'], drop_p=checkpoint['drop_p'])
model.fc = classifier
model.load_state_dict(checkpoint['state_dict'])
device = eval(checkpoint['device'])
model.class_to_idx = checkpoint['class_to_idx']
epochs = checkpoint['epochs']
print_every = checkpoint['print_every']
optimizer = eval(checkpoint['optimizer'])
criterion = eval(checkpoint['criterion'])
optimizer.state_dict = checkpoint['optimizer_state_dict']
return model, device, epochs, print_every, optimizer, criterion
def process_image(image):
"""Scales, crops, and normalizes a PIL image for a PyTorch model."""
pil_image = Image.open(image)
pil_image = pil_image.resize((256, 256))
pil_image = pil_image.crop((16, 16, 240, 240))
np_image = np.array(pil_image)
np_image = np_image.astype(np.float64)
np_image /= 255.0
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
np_image = (np_image - mean) / std
np_image = np_image.transpose((1, 0, 2))
np_image = np_image.transpose()
return np_image
def predict(image_path, model, device, topk=5):
"""Predict the class of an image with trained model."""
model_load, device, epochs, print_every, optimizer, criterion = load_checkpoint(model)
image = process_image(image_path)
inputs = torch.from_numpy(image)
inputs.unsqueeze_(0)
inputs = inputs.type(torch.FloatTensor)
inputs = inputs.to(device)
model_load.to(device)
model_load.eval()
with torch.no_grad():
outputs = model_load.forward(inputs)
outputs = torch.exp(outputs)
_, predicted = torch.max(outputs.data, 1)
ps = outputs.topk(topk)
classes = []
for idx in ps[1].data.cpu().numpy()[0]:
classes.append([c for c, i in model_load.class_to_idx.items() if i == idx][0])
return ps[0].data.cpu().numpy()[0], classes
|
PHP
|
UTF-8
| 2,255
| 2.5625
| 3
|
[] |
no_license
|
<?php
$connection = mysqli_connect("localhost", "root", "", "treasurehall");
if (!$connection) {
die("Connection failed:" . mysqli_connect_error());
}
// echo "Connection successful";
if (isset($_POST["regnumber_check"])) {
$regnumber = $_POST["regnumber"];
$query = " SELECT * FROM foreignexamstudents WHERE regnumber = '$regnumber' ";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
echo "returning";
} else {
echo "new";
}
exit();
}
if (isset($_POST["save"])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$regnumber = $_POST['regnumber'];
$nysccode = $_POST['nysccode'];
$options = $_POST['options'];
$gender = $_POST['gender'];
$status = $_POST['status'];
$phonenumber = $_POST['phonenumber'];
$phonenumber2 = $_POST['phonenumber2'];
$sponsor = $_POST['sponsor'];
$employer = $_POST['employer'];
$homeaddress = $_POST['homeaddress'];
$email = $_POST['email'];
$qualifications = $_POST['qualifications'];
$weekdays = $_POST['weekdays'];
$weekends = $_POST['weekends'];
$weekdayscount = $_POST['weekdayscount'];
$weekendscount = $_POST['weekendscount'];
$totalcount = $_POST['totalcount'];
$weekdaysamount = $_POST['weekdaysamount'];
$weekendsamount = $_POST['weekendsamount'];
$totalamount = $_POST['totalamount'];
$howdidyouknow = $_POST['howdidyouknow'];
$query = " INSERT into foreignexamstudents (firstname, lastname, regnumber, nysccode, options, gender, status, phonenumber, phonenumber2, sponsor, employer, homeaddress, email, qualifications, weekdays, weekends, weekdayscount, weekendscount, totalcount, weekdaysamount, weekendsamount, amount, totalamount, howdidyouknow) VALUES ('$firstname', '$lastname', '$regnumber', '$nysccode', '$options', '$gender', '$status', '$phonenumber', '$phonenumber2', '$sponsor', '$employer', '$homeaddress', '$email', '$qualifications', '$weekdays', '$weekends', '$weekdayscount', '$weekendscount', '$totalcount', '$weekdaysamount', '$weekendsamount', '$totalamount', '$howdidyouknow') ";
$result = mysqli_query($connection, $query);
if(!$result) {
echo "error saving data: " . mysqli_error($connection);
}
echo "User Registered sucessfully";
exit();
}
?>
|
C++
|
UTF-8
| 485
| 2.671875
| 3
|
[] |
no_license
|
#ifndef __FISHEYE_H__
#define __FISHEYE_H__
#include "Camera.h"
#include "Vector3D.h"
#include "Point2D.h"
class Fisheye : public Camera
{
public:
Fisheye();
~Fisheye();
public:
Vector3D ray_direction(const Point2D& p,
const int hres,
const int vres,
const float s,
float& r)const;
virtual void render_scene(World& w);
private:
float psi_max;
};
inline Fisheye::Fisheye() :psi_max(0)
{
}
inline Fisheye::~Fisheye()
{
psi_max = 0;
}
#endif
|
C
|
UTF-8
| 1,584
| 3.171875
| 3
|
[] |
no_license
|
/*
* @lc app=leetcode id=464 lang=c
*
* [464] Can I Win
*
* https://leetcode.com/problems/can-i-win/description/
*
* algorithms
* Medium (27.25%)
* Total Accepted: 36K
* Total Submissions: 132.1K
* Testcase Example: '10\n11'
*
* In the "100 game," two players take turns adding, to a running total, any
* integer from 1..10. The player who first causes the running total to reach
* or exceed 100 wins.
*
* What if we change the game so that players cannot re-use integers?
*
* For example, two players might take turns drawing from a common pool of
* numbers of 1..15 without replacement until they reach a total >= 100.
*
* Given an integer maxChoosableInteger and another integer desiredTotal,
* determine if the first player to move can force a win, assuming both players
* play optimally.
*
* You can always assume that maxChoosableInteger will not be larger than 20
* and desiredTotal will not be larger than 300.
*
*
* Example
*
* Input:
* maxChoosableInteger = 10
* desiredTotal = 11
*
* Output:
* false
*
* Explanation:
* No matter which integer the first player choose, the first player will lose.
* The first player can choose an integer from 1 up to 10.
* If the first player choose 1, the second player can only choose integers
* from 2 up to 10.
* The second player will win by choosing 10 and get a total = 11, which is >=
* desiredTotal.
* Same with other integers chosen by the first player, the second player will
* always win.
*
*
*/
bool canIWin(int maxChoosableInteger, int desiredTotal){
}
|
Python
|
UTF-8
| 2,759
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/python
#
import sys
import PIL
from PIL import Image
import numpy as np
import cv2
exif_orientation_table = [{'angle': 0, 'flip': False}, # 0-ingore
{'angle': 0, 'flip': False}, # 1-horizontal(normal)
{'angle': 0, 'flip': True}, # 2-mirror horizontal
{'angle': 180, 'flip': False},# 3-rotate 180
{'angle': 180, 'flip': True}, # 4-mirror veritical
{'angle': 90, 'flip': True}, # 5-mirror horizontal and rotate 270 CW
{'angle': 270, 'flip': False},# 6-rotate 60 CW
{'angle': 270, 'flip': True}, # 7-mirror horizontal and rotate 90 CW
{'angle': 90, 'flip': False} # 8-rotate 270 CW
]
def rotate_exif_img(src_img, rotate_flag):
# ingore index out of range
if rotate_flag >= len(exif_orientation_table) or rotate_flag < 0:
rotate_flag = 0
rotate_angle = exif_orientation_table[rotate_flag]['angle']
flip_flag = exif_orientation_table[rotate_flag]['flip']
if rotate_angle != 0:
dest_img = np.rot90(src_img, rotate_angle/90)
dest_img = dest_img.copy()
else:
dest_img = src_img
if flip_flag:
dest_img = dest_img[:, ::-1, :]
return dest_img
def load_exif_jpg(img_path):
pil_im = PIL.Image.open(img_path)
flag_key = 274
try:
exif_data = pil_im._getexif()
if exif_data and flag_key in exif_data.keys():
# print 'orientation:', exif_data[flag_key]
orientation_flag = int(exif_data[flag_key])
else:
orientation_flag = 0
except ZeroDivisionError:
# bug: Pillow==3.0
print 'error'
orientation_flag = 0
except:
# it is not a jpg format image
orientation_flag = 0
# convert to opencv format (RBG to BGR)
opencv_img = np.array(pil_im)[:, :, ::-1].copy()
final_img = rotate_exif_img(opencv_img, orientation_flag)
return final_img
if __name__ == '__main__':
argv = sys.argv
if len(argv) != 2:
print 'usage:\n\t{:s} jpg_img'.format(argv[0])
sys.exit()
# raw
im_raw = cv2.imread(argv[1])
resize_img = cv2.resize(im_raw, (0, 0), fx=0.5, fy=0.5)
cv2.imwrite('raw_resized.jpg', resize_img)
# rotate
final_img = load_exif_jpg(argv[1])
cv2.imwrite('exif_res.jpg', final_img)
# resize
resize_img = cv2.resize(final_img, (0, 0), fx=0.5, fy=0.5)
cv2.imwrite('exif_resized.jpg', resize_img)
# draw rectangle
cv2.rectangle(final_img, (100, 100), (200, 200), (0, 255, 0), 2)
cv2.imshow('test', final_img)
cv2.waitKey(0)
|
Java
|
UTF-8
| 175
| 1.859375
| 2
|
[] |
no_license
|
package com.delta2.colours.filters.image;
public class LightnessVignetteFilter extends VignetteFilter {
public LightnessVignetteFilter(double exp) {
super(2, exp);
}
}
|
C++
|
UTF-8
| 1,845
| 2.5625
| 3
|
[] |
no_license
|
#include "at/AnalysisWithTreeAndHist.h"
#include "at/AnalysisBase.h"
#include "rt/MiscTools.h"
#include <iostream>
using namespace std;
namespace at
{
// construct:
AnalysisWithTreeAndHist::AnalysisWithTreeAndHist
(
const std::string& root_file_name,
const std::string& tree_name,
const std::string& tree_title,
const bool print,
const std::string& suffix
)
: AnalysisBase(root_file_name)
, m_tree(new TTree(tree_name.c_str(), tree_title.c_str()))
{
m_tree->SetDirectory(m_root_file.get());
// begin job
BeginJob();
}
// destroy:
AnalysisWithTreeAndHist::~AnalysisWithTreeAndHist()
{
}
// function operator
int AnalysisWithTreeAndHist::operator () (long event)
{
return 0;
}
void AnalysisWithTreeAndHist::BeginJob()
{
// book the histograms
BookHists();
}
void AnalysisWithTreeAndHist::EndJob()
{
// write output
cout << "Writing tree and histograms to root file: " << m_root_file->GetName() << endl;
cout << "TTree " << m_tree->GetName() << " has " << m_tree->GetEntries() << " entries" << endl;
m_hist_container.Write(m_root_file.get());
m_root_file->cd();
m_tree->Write("", TObject::kOverwrite);
// write output
if (m_print)
{
std::string output_print_path = rt::dirname(m_root_file->GetName()) + "/" + m_suffix;
m_hist_container.Print(output_print_path, m_suffix);
}
// call base classes EndJob
AnalysisBase::EndJob();
}
// methods:
void AnalysisWithTreeAndHist::BookHists()
{
rt::TH1Container& h = m_hist_container;
h.Add(new TH1F("h_count","# of events", 3, -0.5, 2.5));
}
} // namespace at
|
Markdown
|
UTF-8
| 3,174
| 2.8125
| 3
|
[] |
no_license
|
```yaml
area: Nottinghamshire
og:
description: Police have made an arrest in connection with a report of a man tricking his way into a pensioner's home in Kirkby-in-Ashfield, telling her that he worked for the council, before stealing her handbag.
image: https://www.nottinghamshire.police.uk/_npt_customisations/images/socialmedia-crest-2018.jpg
site:
name: Nottinghamshire Police
title: Arrest after man posed as council worker during distraction burglary
type: article
url: https://www.nottinghamshire.police.uk/news-article/arrest-after-man-posed-council-worker-during-distraction-burglary
title: Arrest after man posed as council worker during distraction burglary | Nottinghamshire Police
url: https://www.nottinghamshire.police.uk/news-article/arrest-after-man-posed-council-worker-during-distraction-burglary
```
February 24, 2021
Share by email
Police have made an arrest in connection with a report of a man tricking his way into a pensioner's home in Kirkby-in-Ashfield, telling her that he worked for the council, before stealing her handbag.
A man knocked on the victim's door at around 1.50pm on 8 February 2021. Once inside he snatched her bag and ran out of her house in Hartley Road.
Following enquiries police arrested a 61-year-old man during the early hours of today (Wednesday 24 February 2021) on suspicion of burglary and he remains in custody.
Detective Sergeant Andrew Hall, of Nottinghamshire Police, said: "The victim was left very shaken by this incident and feels angry about what happened.
"Distraction burglars often prey on our most vulnerable residents, tricking their way into homes by making up stories, by pretending to work for an official company or asking for help to try to gain entry.
“Nobody should become a victim of crime in their own home, but there are things that can be done to minimise the risks.
“We need residents to be alert to the threat and want to remind them to be on their guard, especially if someone you’re not expecting – a man, woman or even a child – knocks on your door.
“Our advice is always to say no to cold-callers and to report any suspicious activity to police immediately.
"Residents, particularly the elderly and those who live alone, should remain vigilant and ensure that their home is secure at all times, keeping their doors and windows locked.
“We’d also urge those who know vulnerable people who are potentially at risk to share our message with them, to advise them of the signs, remind them to not let in unexpected callers and what to do if they are targeted.
“With more people feeling isolated and alone during the Covid-19 pandemic, distraction burglars may see this as an opportunity to target people.
“If you see somebody acting suspiciously report it to the police immediately by calling 101 or, in an emergency, call 999.”
For more advice on home security visit: https://www.nottinghamshire.police.uk/document/advice-home
For more advice on dealing with unexpected callers at your door visit https://www.nottinghamshire.police.uk/advice/prevention/distraction
Incident Number:
0315_08022021
Neighbourhood:
Kirkby In Ashfield
|
C#
|
UTF-8
| 1,382
| 2.671875
| 3
|
[] |
no_license
|
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Models;
using Newtonsoft.Json;
using SqsWriter.Sqs;
namespace SqsWriter.Controllers
{
[Route("api/[controller]")]
public class PublishController : Controller
{
private readonly ISqsClient _sqsClient;
private readonly ILogger<PublishController> _logger;
public PublishController(ISqsClient sqsClient, ILogger<PublishController> logger)
{
_sqsClient = sqsClient;
_logger = logger;
}
[HttpPost]
[Route("movie")]
public async Task<IActionResult> PublishMovie([FromBody]Movie movie)
{
await _sqsClient.PostMessageAsync(movie);
_logger.LogInformation("New Movie published with {Title}, {@Content}",
movie.Title, movie);
return StatusCode((int)HttpStatusCode.Created);
}
[HttpPost]
[Route("actor")]
public async Task<IActionResult> PublishActor([FromBody]Actor actor)
{
await _sqsClient.PostMessageAsync(actor);
_logger.LogInformation("New Actor published with {FirstName} and {LastName}, {@Content}",
actor.FirstName, actor.LastName, actor);
return StatusCode((int)HttpStatusCode.Created);
}
}
}
|
Java
|
UTF-8
| 2,295
| 1.789063
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: UserSetContactInfo.java
package com.facebook.katana.service.method;
import android.content.Context;
import android.content.Intent;
import com.facebook.katana.binding.AppSession;
import com.facebook.katana.binding.AppSessionListener;
import com.facebook.katana.model.FacebookApiException;
import com.facebook.katana.model.FacebookSessionInfo;
import com.facebook.katana.util.jsonmirror.JMException;
import java.io.IOException;
import java.util.*;
import org.codehaus.jackson.JsonParseException;
// Referenced classes of package com.facebook.katana.service.method:
// ApiMethod, ApiMethodCallback, FBJsonFactory, ApiMethodListener
public class UserSetContactInfo extends ApiMethod
implements ApiMethodCallback
{
protected UserSetContactInfo(Context context, Intent intent, String s, ApiMethodListener apimethodlistener, String s1)
{
super(context, intent, "POST", "userSetContactInfo", com.facebook.katana.Constants.URL.getApiUrl(context), apimethodlistener);
mParams.put("call_id", String.valueOf(System.currentTimeMillis()));
mParams.put("session_key", s);
mParams.put("cell", s1);
}
public static String setCellNumber(AppSession appsession, Context context, String s)
{
return appsession.postToService(context, new UserSetContactInfo(context, null, appsession.getSessionInfo().sessionKey, null, s), 1001, 1020, null);
}
public void executeCallbacks(AppSession appsession, Context context, Intent intent, String s, int i, String s1, Exception exception)
{
for(Iterator iterator = appsession.getListeners().iterator(); iterator.hasNext(); ((AppSessionListener)iterator.next()).onUserSetContactInfoComplete(appsession, s, i, s1, exception));
}
protected void parseResponse(String s)
throws FacebookApiException, JsonParseException, IOException, JMException
{
printJson(s);
if(s.startsWith("{") || !s.trim().equals("true"))
throw new FacebookApiException(mJsonFactory.createJsonParser(s));
else
return;
}
public static final String CELL_PARAM = "cell";
}
|
Swift
|
UTF-8
| 4,218
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// NewBooksViewController.swift
// BookStore
//
// Created by Soojin Ro on 10/06/2019.
// Copyright © 2019 Soojin Ro. All rights reserved.
//
import UIKit
import BookStoreKit
final class NewBooksViewController: UIViewController {
private(set) var books = [Book]()
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
reload()
}
private func setupTableView() {
tableView?.register(BookCell.self)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.rowHeight = 250
tableView?.estimatedRowHeight = 250
tableView?.tableFooterView = UIView()
tableView?.accessibilityIdentifier = "NewBooksTableView"
}
private func reload() {
state = .loading
bookStore.fetchNewReleases(completionHandler: handle)
}
private func handle(_ result: Result<NewBooksResponse, Error>) {
switch result {
case .success(let response):
books = response.books
state = books.isEmpty ? .empty : .finished
tableView?.reloadData()
case .failure:
state = .error
}
}
@IBAction private func retryButtonTapped(_ sender: UIButton) {
reload()
}
private lazy var bookStore: BookStoreService = unspecified()
@IBOutlet private weak var tableView: UITableView?
@IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView?
@IBOutlet private weak var statusLabel: UILabel?
@IBOutlet private weak var retryButton: UIButton?
private enum LoadingState {
case loading, finished, empty, error
}
private var state: LoadingState = .empty {
didSet {
switch state {
case .loading:
tableView?.isHidden = true
statusLabel?.text = "Loading"
retryButton?.isHidden = true
activityIndicatorView?.startAnimating()
case .finished:
tableView?.isHidden = false
statusLabel?.text = nil
retryButton?.isHidden = true
activityIndicatorView?.stopAnimating()
case .empty:
tableView?.isHidden = true
statusLabel?.text = "Nothing new 🙃"
retryButton?.isHidden = true
activityIndicatorView?.stopAnimating()
case .error:
tableView?.isHidden = true
statusLabel?.text = "Something went wrong 🤯"
retryButton?.isHidden = false
activityIndicatorView?.stopAnimating()
}
}
}
}
extension NewBooksViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(BookCell.self, for: indexPath)
let book = books[indexPath.row]
cell.identifier = book.isbn13
cell.titleLabel?.text = book.title
cell.subtitleLabel?.text = book.subtitle
cell.priceLabel?.text = book.price
cell.isbn13Label?.text = book.isbn13
if let thumbnailURL = book.thumbnailURL {
ImageProvider.shared.fetch(from: thumbnailURL) { (result) in
if case .success(let image) = result, cell.identifier == book.isbn13 {
cell.thumbnailImageView?.image = image
}
}
}
return cell
}
}
extension NewBooksViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let book = books[indexPath.row]
let bookInfoViewController = BookInfoViewController.instantiate(isbn13: book.isbn13, bookStore: bookStore)
present(bookInfoViewController, animated: true, completion: nil)
}
}
extension NewBooksViewController: BookStoreView {
func set(_ bookStore: BookStoreService) {
self.bookStore = bookStore
}
}
|
C#
|
UTF-8
| 1,536
| 2.6875
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using UnityEngine;
class RandomProcreation<G> : Procreation<G> where G : Gene, new()
{
public List<DNA<G>> BuildNextGeneration(List<DNA<G>> fittest, int generationSize, int survivorKeepPercentage, int mutationChance, int mutationRate, bool autoProcreation) {
List<DNA<G>> newDNAs = new List<DNA<G>>();
int survivorKeep = Mathf.RoundToInt(survivorKeepPercentage * Mathf.Pow(10, -2) * generationSize);
// add survivors
for (int i = 0; i < survivorKeep; i++)
{
newDNAs.Add(fittest[i]);
}
// procreate and mutate for the rest of population
while (newDNAs.Count < generationSize)
{
// choose random fittest cats
int randomParentIndex1 = Random.Range(0, fittest.Count);
int randomParentIndex2 = Random.Range(0, fittest.Count);
while(randomParentIndex1 == randomParentIndex2 && !autoProcreation)
{
randomParentIndex2 = Random.Range(0, fittest.Count);
}
DNA<G> dNAParent1 = fittest[randomParentIndex1];
DNA<G> dNAParent2 = fittest[randomParentIndex2];
DNA<G> newDNA = dNAParent1 + dNAParent2;
// mutate only mutationChance percentage of cats
float randomValue = Random.Range(0, 101);
if(randomValue < mutationChance)
newDNA.Mutate(mutationRate);
newDNAs.Add(newDNA);
}
return newDNAs;
}
}
|
Shell
|
UTF-8
| 242
| 2.984375
| 3
|
[] |
no_license
|
#!/bin/sh
mkdir -p /etc/mkinitfs/features.d
for i in files modules; do
for j in /etc/mkinitfs/$i.d/*; do
[ -e "$j" ] || continue
case "$j" in
*.apk-new) continue;;
esac
mv $j /etc/mkinitfs/features.d/${j##*/}.$i
done
done
exit 0
|
Java
|
UTF-8
| 250
| 1.6875
| 2
|
[] |
no_license
|
package src.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class MainTest {
/**
* Test the main
*/
@Test
public void test() {
assertEquals(2, 2);
}
}
|
PHP
|
ISO-8859-1
| 764
| 3.515625
| 4
|
[] |
no_license
|
<?
/**
=begin
titulo: Calculadora
enunciado: Dado um nmero, um operador e outro nmero, exibir a operao desejada.
exemplos:
5 x 6: 5 x 6 = 30
10 + 34: 10 + 34 = 44
21 - 1: 21 - 1 = 20
18 / 2: 18 / 2 = 9
3 % 2: operador % invalido!
dificuldade: 2
linguagem: php
solucao: Utilizar o switch para decidir qual operao executar
categorias: [aritmetica]
=end
*/
// ENTRADA
$n1 = $argv[1];
$op = $argv[2];
$n2 = $argv[3];
// LOGICA
switch($op):
case "+": $r = $n1 + $n2; break;
case "-": $r = $n1 - $n2; break;
case "/": $r = $n1 / $n2; break;
case "x":
case "*":
$r = $n1 * $n2;
break;
default:
exit("operador $op invalido!");
endswitch;
// SAIDA
echo "
$n1 $op $n2 = $r
";
?>
|
PHP
|
UTF-8
| 1,992
| 2.96875
| 3
|
[] |
no_license
|
<?php
require_once ('./model/Model.php');
class Comment extends Model {
protected $id;
protected $postId;
protected $author;
protected $authorEmail;
protected $comment;
protected $reported;
protected $moderated;
protected $date;
// Constructor
public function __construct(array $comment) {
$this->hydrate($comment);
}
// Getters
public function Id() {
return $this->id;
}
public function PostId() {
return $this->postId;
}
public function Author() {
return $this->author;
}
public function AuthorEmail() {
return $this->authorEmail;
}
public function Comment() {
return $this->comment;
}
public function Reported() {
return $this->reported;
}
public function Moderated() {
return $this->moderated;
}
public function Date() {
return $this->date;
}
// Setters
public function setId($id) {
$id = (int) $id;
if ($id > 0) {
$this->id = $id;
}
}
public function setPostId($postId) {
$postId = (int) $postId;
if ($postId > 0) {
$this->postId = $postId;
}
}
public function setAuthor($author) {
if (is_string($author)) {
$this->author = $author;
}
}
public function setAuthorEmail($authorEmail) {
if (is_string($authorEmail)) {
$this->authorEmail = $authorEmail;
}
}
public function setComment($comment) {
if (is_string($comment)) {
$this->comment = $comment;
}
}
public function setReported($reported) {
$reported = (int) $reported;
if ($reported > 0) {
$this->reported = $reported;
}
}
public function setModerated($moderated) {
$this->moderated = $moderated;
}
public function setDate($date) {
$this->date = $date;
}
}
|
Ruby
|
UTF-8
| 1,165
| 3.625
| 4
|
[] |
no_license
|
class PolyTreeNode
attr_reader :parent, :children, :value
def initialize(value, parent = nil, children = [])
@value = value
@parent = parent
@children = children
end
def parent=(node)
@parent.children.delete(self) if @parent
@parent = node
node.children << self if node && !node.children.include?(self)
end
def add_child(child_node)
child_node.parent = self
end
def remove_child(child_node)
raise "child_node is not a child" unless child_node.parent == self
child_node.parent = nil
end
def dfs(target_value)
return self if target_value == @value
@children.each do |child|
child_dfs = child.dfs(target_value)
return child_dfs if child_dfs
end
nil
end
def bfs(target_value)
queue = [self]
until queue == []
curr_node = queue.shift
return curr_node if curr_node.value == target_value
curr_node.children.each { |child| queue << child }
end
nil
end
end
if __FILE__ == $0
n1 = PolyTreeNode.new("root")
n2 = PolyTreeNode.new("child1")
n3 = PolyTreeNode.new("child2")
n1.add_child(n2)
n1.add_child(n3)
p n1.dfs("child1")
end
|
PHP
|
UTF-8
| 2,332
| 2.59375
| 3
|
[] |
no_license
|
<?php
use Dominio\Regras;
use Entidade\{Usuario, Modulo, Perfil};
/**
* @group Dominio
*/
class RegrasTest extends PHPUnit_Framework_TestCase
{
private static $regras;
public static function setUpBeforeClass()
{
self::$regras = self::getRegras();
}
/**
* @dataProvider acessos
*/
public function testUsuarioTemAcessoAoModulo($usuario, $modulo, $esperado)
{
$this->assertEquals($esperado, self::$regras->temAcesso($usuario, $modulo));
}
/**
* @depends testUsuarioTemAcessoAoModulo
*/
public function testUsuarioPodeCriarNoModulo()
{
$usuario = new Usuario('Nome Qualquer', 11122233344);
$modulo = new Modulo('FINANCEIRO', '/financeiro');
$this->assertTrue(self::$regras->podeCriar($usuario, $modulo));
}
public function acessos()
{
return [
[
new Usuario('Nome Qualquer', 11122233344),
new Modulo('FINANCEIRO', '/financeiro'),
true
],
[
new Usuario('Edy', 00000000000),
new Modulo('FINANCEIRO', '/financeiro'),
false
]
];
}
private static function getRegras()
{
// SQL
return new Regras([
[
'usuario' => new Usuario('Nome Qualquer', 11122233344),
'modulo' => new Modulo('FINANCEIRO', '/financeiro'),
'perfil' => new Perfil('OPERADOR', ['CRIAR', 'VISUALIZAR'])
],
[
'usuario' => new Usuario('João Silva', 99988877766),
'modulo' => new Modulo('FINANCEIRO', '/financeiro'),
'perfil' => new Perfil('ADMIN', ['CRIAR', 'VISUALIZAR', 'EDITAR', 'EXCLUIR'])
],
[
'usuario' => new Usuario('Maria Sousa', 66655544433),
'modulo' => new Modulo('FINANCEIRO', '/financeiro'),
'perfil' => new Perfil('GERENTE', ['CRIAR', 'VISUALIZAR', 'EDITAR'])
],
[
'usuario' => new Usuario('Edy', 00000000000),
'modulo' => new Modulo('PIABA', '/piabinha'),
'perfil' => new Perfil('ADMIN', ['CRIAR', 'VISUALIZAR', 'EDITAR', 'EXCLUIR'])
]
]);
}
}
|
Markdown
|
UTF-8
| 19
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
# jay-kim-portfolio
|
Java
|
UTF-8
| 647
| 2.390625
| 2
|
[] |
no_license
|
package io.github.wanmudong.spidersina.spider.demo.gecco;
/**
* @author :wanmudong
* @date :Created in 2019/5/17 10:39
* @description:
* @modified By:
* @version: $
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegrexUtil {
public static String match(String content) {
StringBuilder stringBuilder = new StringBuilder();
Pattern pattern = Pattern.compile("([\\u4e00-\\u9fa5]+)");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
stringBuilder.append(matcher.group(0));
}
return stringBuilder.toString();
}
}
|
Java
|
UTF-8
| 886
| 3.8125
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class Encryption {
public static void main(String[] args) {
int digits, digit1, digit2 , digit3, digit4;
System.out.println("Please enter a four-digit number:");
Scanner number = new Scanner(System.in);
digits = number.nextInt();
int temp = 0;
while (digits > 9999 || digits < 0)
{
System.out.println("The number you have entered is invalid due to being more or less than four digits.");
digits = number.nextInt();
}
digit1 = digits%10;
digits = digits/10;
digit2 = digits%10;
digits = digits/10;
digit3 = digits%10;
digits = digits/10;
digit4 = digits%10;
digit1 = (digit1+7)%10;
digit2 = (digit2+7)%10;
digit3 = (digit3+7)%10;
digit4 = (digit4+7)%10;
System.out.printf("The encrypted number:%d%d%d%d\n", digit2,digit1,digit4,digit3);
}
}
|
C#
|
UTF-8
| 1,209
| 2.953125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Clue.Models;
namespace Clue.Controllers
{
class CategoriesController
{
private GameMemory _context;
public CategoriesController()
{
_context = new GameMemory();
}
public ICollection<Category> GetCategory()
{
return _context.Categories;
}
public Category GetCategory(int Id)
{
Category category = _context.Categories.First(c => c.Id == Id);
return category;
}
public Category UpdateCategory(int Id, Category category)
{
Category SaveCategory = _context.Categories.First(c => c.Id == Id);
SaveCategory = category;
return SaveCategory;
}
public Category CreateCategory(Category category)
{
category.Id = _context.Categories.Count() + 1;
_context.Categories.Add(category);
return category;
}
public void DeleteCategory(Category category)
{
_context.Categories.Remove(category);
}
}
}
|
Go
|
UTF-8
| 508
| 3.25
| 3
|
[] |
no_license
|
package main
import (
"fmt"
"math"
)
func diagonalDifference(arr [][]int32) int32 {
var lsum, rsum int32 = 0, 0
var nTimes = len(arr)
for i := 0; i < nTimes; i++ {
for j := 0; j < nTimes; j++ {
if i == j {
lsum += arr[i][j]
}
if i+j == nTimes-1 {
rsum += arr[i][j]
}
}
}
diff := math.Abs(float64(lsum - rsum))
return int32(diff)
}
func main() {
arr := [][]int32{
{8, 9, 1},
{4, 5, 6},
{9, 8, 9},
}
result := diagonalDifference(arr)
fmt.Println(result)
}
|
SQL
|
UTF-8
| 4,444
| 4.15625
| 4
|
[] |
no_license
|
--drop table if exists "IBF-pipeline-output".dashboard_triggers_per_day;
truncate table "IBF-pipeline-output".dashboard_triggers_per_day;
insert into "IBF-pipeline-output".dashboard_triggers_per_day
select tpd.country_code
,'Current' as current_prev
-- ,case when date_part('day',age(current_date,to_date(date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
,"1","2","3","4","5","6","7","8","9","10"
--into "IBF-pipeline-output".dashboard_triggers_per_day
from "IBF-pipeline-output".triggers_per_day tpd
left join (select country_code, max(date) as max_date from "IBF-pipeline-output".triggers_per_day group by 1) max
on tpd.country_code = max.country_code
and tpd.date = max.max_date
--where to_date(date,'yyyy-mm-dd') >= current_date - 1
where tpd.date = max.max_date
;
--drop table "IBF-pipeline-output".dashboard_forecast_per_station cascade;
truncate table "IBF-pipeline-output".dashboard_forecast_per_station;
insert into "IBF-pipeline-output".dashboard_forecast_per_station
SELECT t0.country_code
,t0.station_code
,t0.station_name
,t0.trigger_level
,date
,case when date_part('day',age(current_date,to_date(date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
,'3-day' as lead_time
,fc_short as fc,fc_short_trigger as fc_trigger,fc_short_rp as fc_rp
,case when trigger_level = 0 then null else fc_short/trigger_level end as fc_perc
,fc_short_prob as fc_prob
,case when fc_short_prob >= 0.8 then 80 when fc_short_prob >=0.7 then 70 when fc_short_prob >=0.6 then 60 else 0 end as fc_trigger2
,t0.geom
,other_lead_time_trigger
,case when t3.station is null then 0 else 1 end as station_used
--into "IBF-pipeline-output".dashboard_forecast_per_station
FROM "IBF-pipeline-output".dashboard_glofas_stations t0
LEFT JOIN "IBF-pipeline-output".triggers_rp_per_station_short t1
ON t0.station_code = t1.station_code
AND t0.country_code = t1.country_code
LEFT JOIN (select to_date(date,'yyyy-mm-dd') as current_prev, max(fc_long_trigger) as other_lead_time_trigger from "IBF-pipeline-output".triggers_rp_per_station_long group by 1) t2
ON to_date(date,'yyyy-mm-dd') = t2.current_prev
LEFT JOIN (select "station_code_3day" as station from "IBF-pipeline-output".waterstation_per_district group by 1) t3
ON t3.station = t0.station_code
where to_date(date,'yyyy-mm-dd') >= current_date - 1
UNION ALL
SELECT t0.country_code
,t0.station_code
,t0.station_name
,t0.trigger_level
,date
,case when date_part('day',age(current_date,to_date(date,'yyyy-mm-dd'))) = 1 then 'Previous' else 'Current' end as current_prev
,'7-day' as lead_time
,fc_long,fc_long_trigger,fc_long_rp
,case when trigger_level = 0 then null else fc_long/trigger_level end as fc_perc
,fc_long_prob as fc_prob
,case when fc_long_prob >= 0.8 then 80 when fc_long_prob >=0.7 then 70 when fc_long_prob >=0.6 then 60 else 0 end as fc_trigger2
,t0.geom
,other_lead_time_trigger
,case when t3.station is null then 0 else 1 end as station_used
FROM "IBF-pipeline-output".dashboard_glofas_stations t0
LEFT JOIN "IBF-pipeline-output".triggers_rp_per_station_long t1
ON t0.station_code = t1.station_code
AND t0.country_code = t1.country_code
LEFT JOIN (select to_date(date,'yyyy-mm-dd') as current_prev, max(fc_short_trigger) as other_lead_time_trigger from "IBF-pipeline-output".triggers_rp_per_station_short group by 1) t2
ON to_date(date,'yyyy-mm-dd') = t2.current_prev
LEFT JOIN (select "station_code_7day" as station from "IBF-pipeline-output".waterstation_per_district group by 1) t3
ON t3.station = t0.station_code
where to_date(date,'yyyy-mm-dd') >= current_date - 1
;
--select * from "IBF-pipeline-output".dashboard_forecast_per_station
DROP TABLE IF EXISTS "IBF-pipeline-output".dashboard_forecast_per_district;
select case when length(cast(pcode as varchar)) = 3 then '0' || cast(pcode as varchar) else cast(pcode as varchar) end as pcode
,case when lead_time = '3-day' then "station_code_3day" when lead_time = '7-day' then "station_code_7day" end as station_code
,lead_time
,date
,current_prev
,fc,fc_trigger,fc_rp,fc_perc,fc_prob,fc_trigger2
,other_lead_time_trigger
INTO "IBF-pipeline-output".dashboard_forecast_per_district
FROM "IBF-pipeline-output".waterstation_per_district t0
LEFT JOIN "IBF-pipeline-output".dashboard_forecast_per_station t1
ON (t1.lead_time = '7-day' and t0."station_code_7day" = t1.station_code) OR (t1.lead_time = '3-day' and t0."station_code_3day" = t1.station_code)
;
|
Java
|
UTF-8
| 412
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
import org.junit.*;
import static org.junit.Assert.*;
public class ToDoTest {
@Test
public void ToDo_instantiatesCorrectly_true() {
ToDo myToDo = new ToDo("Learn to code");
assertEquals(true, myToDo instanceof ToDo);
}
@Test
public void task_instantiatesWithDescription_true() {
ToDo myToDo = new ToDo("Learn to code");
assertEquals("Learn to code", myToDo.getDescription());
}
}
|
C#
|
UTF-8
| 1,309
| 3.6875
| 4
|
[
"MIT"
] |
permissive
|
using System;
using System.Net.Http;
using System.Threading;
namespace WhatIsBackgroundThread
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var url = "https://www.google.com";
Thread thread1 = new Thread(LogEvery5Seconds);
thread1.IsBackground = true;
thread1.Start();
Thread thread = new Thread(new ThreadStart(() => { PingWebPage10Times(url); }));
thread.Start();
}
private static void LogEvery5Seconds()
{
int i = 0;
while (true)
{
Console.WriteLine($"Approximately {i * 5 } seconds elapsed since start of the program");
Thread.Sleep(5000);
i++;
}
}
private static void PingWebPage10Times(string url)
{
HttpClient client = new HttpClient();
for (int i = 0; i < 10; i++)
{
var responseMessage = client.GetAsync(url).Result;
Console.WriteLine($"S.No. {i}: The response for https://google.com is {responseMessage.StatusCode}");
Thread.Sleep(4000);
}
client.Dispose();
}
}
}
|
TypeScript
|
UTF-8
| 546
| 2.609375
| 3
|
[] |
no_license
|
import mongoose, { Schema, Document } from 'mongoose'
import { v4 as uuidv4 } from 'uuid'
export interface IAttempt extends Document {
_id: string
phone_number: number
attempts: number
}
const AttemptSchema: Schema<IAttempt> = new Schema({
_id: {
type: String,
default: uuidv4
},
phone_number: {
type: Number,
required: true,
unique: true
},
attempts: {
type: Number,
default: 0
}
})
export default mongoose.model<IAttempt>('attempts', AttemptSchema)
|
PHP
|
UTF-8
| 1,684
| 3.03125
| 3
|
[] |
no_license
|
<?php
require "config.php";
$db = dbConnect();
$team = strip_tags($_POST['team']);
$stmt = "SELECT teamId, name From team";
$result = $db->query($stmt);
startPage("User Input");
echo "<table align='center' frame='box' width='30%' border='1px' style='border-collapse: collapse'>";
echo "<th colspan='3' bgcolor='#a9a9a9'>Teams:</th>";
while($row = $result->fetch_assoc())
{
if($row['teamId'] % 2 == 0)
echo "<tr bgcolor='#a9a9a9'>";
else
echo "<tr bgcolor='white'>";
echo "<td>" . $row["name"] . "</td>";
echo "</tr>";
}
echo "</table><br/><br/>";
$result->free();
if($team != NULL) {
$stmt = "SELECT driverId, name FROM drivers WHERE team = (SELECT teamId FROM team WHERE name = '$team')";
$result = $db->query($stmt);
echo "<table align='center' frame='box' width='30%' border='1px' style='border-collapse: collapse'>";
echo "<th colspan='3' bgcolor='#a9a9a9'>".$team." Drivers:</th>";
while ($row = $result->fetch_assoc()) {
if ($row['driverId'] % 2 == 0)
echo "<tr bgcolor='#a9a9a9'>";
else
echo "<tr bgcolor='white'>";
echo "<td>" . $row["name"] . "</td>";
echo "</tr>";
}
echo "</table>";
$result->free();
}
$db->close();
?>
<h2 align="center">Enter A Team to Display The Drivers of That Team</h2>
<h3 align="center">Check Your Spelling!!!</h3>
<table align="center">
<form action="userInput.php" method="post">
<tr>
<td>Team Name:</td><td><input type="text" name="team"></td>
</tr>
<tr>
<td></td><td><input type="submit" value="submit"></td>
</tr>
</form>
</table>
<?php
endPage();
?>
|
Ruby
|
UTF-8
| 1,921
| 3.703125
| 4
|
[] |
no_license
|
quit = 0
while quit != 1
exact_Or_Approximate = "null"
puts"Welcome to the circle calculator!"
puts"Would you like to calculate:"
puts"area or circumference?"
uchoice = gets.chomp
if "area" == uchoice or uchoice == "a" or uchoice == "1" or uchoice == "Area" or uchoice == "A"
puts "What is the radius of your circle?"
r = gets
r = r.to_i
puts "Would you like that in exact form or approximate form?"
exact_Or_Approximate = gets.chomp
r = r**2
if exact_Or_Approximate == "exact" or exact_Or_Approximate == "Exact" or exact_Or_Approximate == "e" or exact_Or_Approximate == "E" or exact_Or_Approximate == "1"
r = r.to_s
puts "The area of your circle is pi" + r
elsif exact_Or_Approximate == "approximate" or exact_Or_Approximate == "Approximate" or exact_Or_Approximate == "a" or exact_Or_Approximate == "A" or exact_Or_Approximate == "2"
r = r*3.14
r = r.to_s
puts "The area of your circle is " + r
end
elsif uchoice == "circumference" or uchoice == "Circumference" or uchoice == "c" or uchoice == "C" or uchoice == "2"
puts "What is the diameter of your circle?"
d = gets.chomp
d = d.to_i
puts "Would you like that in exact form or approximate form?"
exact_Or_Approximate = gets.chomp
if exact_Or_Approximate == "exact" or exact_Or_Approximate == "Exact" or exact_Or_Approximate == "e" or exact_Or_Approximate == "E" or exact_Or_Approximate == "1"
d = d.to_s
puts "The circumference of your circle is pi" + d
elsif exact_Or_Approximate == "approximate" or exact_Or_Approximate == "Approximate" or exact_Or_Approximate == "a" or exact_Or_Approximate == "A" or exact_Or_Approximate == "2"
d = d*3.14
d = d.to_s
puts "The circumference of your circle is " + d
end
elsif uchoice == "quit"
quit = 1
else
puts"That is not an availible option."
end
end
puts"You have exited the circle calculator."
|
Python
|
UTF-8
| 1,077
| 3.5625
| 4
|
[] |
no_license
|
'''
给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。
你可以返回满足此条件的任何数组作为答案。
示例:
输入:[3,1,2,4]
输出:[2,4,3,1]
输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
提示:
1 <= A.length <= 5000
0 <= A[i] <= 5000
'''
from typing import List
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
len_ = len(A)
odd = even = 0
while odd < len_ and even < len_:
while odd < len_ and A[odd] % 2 == 0:
odd += 1
if odd >= len_:
break
even = odd
while even < len_ and A[even] % 2 == 1:
even += 1
if even >= len_:
break
A[odd], A[even] = A[even], A[odd]
odd += 1
even += 1
return A
if __name__ == '__main__':
A = [2, 2, 2, 4, 3, 5, 1, 1, 1, 1, 1, 1]
sol = Solution()
print(sol.sortArrayByParity(A))
|
Java
|
UTF-8
| 1,418
| 2.125
| 2
|
[] |
no_license
|
package com.gurjeet.customelistviewdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CountryActivity extends AppCompatActivity {
TextView title,population,area;
ImageView flag;
Button back;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country);
title=findViewById(R.id.txvCoName);
population=findViewById(R.id.txvPop);
area=findViewById(R.id.txvArea);
flag=findViewById(R.id.imvCountry);
back=findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(CountryActivity.this,MainActivity.class);
startActivity(intent);
}
});
title.setText(MainActivity.countries.get(MainActivity.index).getCountryName());
population.setText(MainActivity.countries.get(MainActivity.index).getPopulation());
area.setText(MainActivity.countries.get(MainActivity.index).getArea());
flag.setImageResource(MainActivity.countries.get(MainActivity.index).getFlagImage());
}
}
|
C++
|
UTF-8
| 702
| 3.375
| 3
|
[] |
no_license
|
// LeetCode
//
// Created by Hongyan on 01/10/17.
// Copyright © 2017 Hongyan. All rights reserved.
//
class Solution {
private:
void findLongestPalindrome(string& s, int i, int j, int& maxLen, int& startPos ) {
while(i >= 0 && j < s.length() && s[i] == s[j]) {
i--;
j++;
}
if(j - i - 1> maxLen) {
maxLen = j - i - 1;
startPos = i + 1;
}
}
public:
string longestPalindrome(string s) {
int n = s.length();
if(n < 2) return s;
int maxLen = 0;
int startPos = 0;
for(int i = 0; i < s.length(); i++) {
findLongestPalindrome(s, i, i, maxLen, startPos);
findLongestPalindrome(s, i, i + 1, maxLen, startPos);
}
return s.substr(startPos, maxLen);
}
};
|
C++
|
UTF-8
| 1,144
| 2.703125
| 3
|
[] |
no_license
|
#include "Module.h"
void Module::CommonLoad(CBReader *reader)
{
//load name
m_name = "";
while (true)
{
std::string str = reader->ReadString();
if (str.find("#") != std::string::npos)
{
break;
}
else
{
m_name.append(str + " ");
}
}
m_description = "";
while (true)
{
std::string str = reader->ReadString();
if (str.find("#") != std::string::npos)
{
break;
}
else
{
m_description.append(str + " ");
}
}
//load graphicspos
m_graphicpos = cocos2d::Vec2(reader->ReadInt(), reader->ReadInt());
//load type
m_category = reader->ReadInt();
//load cost
m_cost = reader->ReadInt();
}
Module::Module()
{
}
std::string Module::getName()
{
return m_name;
}
std::string Module::getDesc()
{
return m_description;
}
int Module::getCost()
{
return m_cost;
}
ModuleType Module::getType()
{
return m_type;
}
cocos2d::Vec2 Module::getGraphicpos()
{
return m_graphicpos;
}
short Module::getCategory()
{
return m_category;
}
int Module::getUID()
{
return m_uid;
}
void Module::setUID(int id)
{
m_uid = id;
}
|
C#
|
UTF-8
| 1,591
| 2.84375
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using BomberMan.Common;
using BomberMan.Common.Components.StateComponents;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace BomberMan.Screens
{
/// <summary>
/// Klasa bazowa dla wszytskich menu zawierających przyciski, które umożliwiają przełączanie widoku.
/// </summary>
public abstract class Menu : Screen
{
/// <summary>
/// Zwróć lub ustaw dostępne przyciski w opcjach.
/// </summary>
/// <value>
/// opcje menu.
/// </value>
protected Button[] OptionButtons { get; set; }
/// <summary>
/// zwróć lub ustaw ilość opcji w menu.
/// </summary>
/// <value>
/// The options.
/// </value>
protected int Options { get; set; }
/// <summary>
/// Utwóz nową instancję menu.
/// </summary>
/// <param name="options">ilość dostępnych opcji</param>
/// <param name="textures">dostępne tła dla przycisków</param>
protected Menu(int options, List<Texture2D> textures)
{
PrevSelectedOption = -1;
Options = options;
OptionButtons = new Button[options];
for (int i = 0; i < textures.Count; i++)
{
OptionButtons[i] = new Button
{
Angle = 0,
Color = Color.Transparent,
Texture = textures.ElementAt(i)
};
}
}
}
}
|
C++
|
UTF-8
| 1,008
| 2.53125
| 3
|
[] |
no_license
|
#ifndef BUILDABLEPROPERTY_H
#define BUILDABLEPROPERTY_H
#include <property.h>
enum Color
{
Red,
Blue,
Yellow,
Green
};
class BuildableProperty : public Property
{
public:
BuildableProperty(const unsigned &, const QString &, const Color &, const unsigned &, const unsigned &);
BuildableProperty(const BuildableProperty &);
Color getColor();
unsigned getRentOfProperty() override;
unsigned getCostPerLevelOfWifiCoverage();
unsigned getCostOfVendingMachine();
unsigned getLevelOfWifiCoverage();
unsigned getNumOfVendingMachines();
void increaseWifiCoverage();
void addVendingMachines();
QString getBoxInfo() override;
void resetter() override;
private:
Color propertyColor;
unsigned levelOfWifiCoverage;
unsigned numOfVendingMachines;
const unsigned RENTPERLEVELOFWIFICOVERAGE = 200, RENTOFVENDINGMACHINE = 300;
const unsigned COSTPERLEVELOFWIFICOVERAGE = 400, COSTOFVENDINGMACHINE = 600;
};
#endif // BUILDABLEPROPERTY_H
|
Java
|
UTF-8
| 576
| 2.15625
| 2
|
[] |
no_license
|
package package2;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utilities.Base;
public class ParameterTest extends Base {
//String url = "https://www.google.com/"; -- delete this after add in xml
@Parameters({"URL", "UserName"})
@Test
public void searchTest(String url, String loginName) {
System.out.println(url);
System.out.println(loginName);
}
@Parameters({"USerPassword", "Amount"})
@Test
public void searchTest2(String pass, String amount) {
System.out.println(pass);
System.out.println(amount);
}
}
|
JavaScript
|
UTF-8
| 230
| 2.890625
| 3
|
[] |
no_license
|
Array.prototype.unsplit = function(a){
var str = "";
for(var i = 0; i<this.length; i++){
str += arr[i];
if(!a && a!==""){
str += ",";
}
else if(a){
str+=a;
}
}
return str;
};
//Create your own join() function;
|
Markdown
|
UTF-8
| 5,840
| 2.84375
| 3
|
[] |
no_license
|
---
title: 'Ajax js'
date: '2020-01-02'
---
<div markdown='1' align='center'>
<img src='/img/ajax.png'/>
</div>
# AJAX
## Introducción
AJAX significa "JavaScript y XML asíncronos". Aunque el nombre incluye XML, JSON se usa con más frecuencia debido a su formato más simple y menor redundancia. AJAX permite al usuario comunicarse con recursos externos sin recargar la página web.
## Observaciones
AJAX significa A síncrono J avascript A nd X ML. No obstante, puede utilizar otros tipos de datos y, en el caso de xmlhttprequest, cambiar al modo sincrónico obsoleto.
AJAX permite que las páginas web envíen solicitudes HTTP al servidor y reciban una respuesta, sin necesidad de volver a cargar toda la página.
Ejemplos relacionados con AJAX
## Agregar un precargador AJAX
### Ejemplo
Esta es una forma de mostrar un precargador de GIF mientras se ejecuta una llamada AJAX. Necesitamos preparar nuestras funciones de agregar y quitar precargador:
function addPreloader() {
// if the preloader doesn't already exist, add one to the page
if(!document.querySelector('#preloader')) {
var preloaderHTML = '<img id="preloader" src="https://goo.gl/cNhyvX" />';
document.querySelector('body').innerHTML += preloaderHTML;
}
}
function removePreloader() {
// select the preloader element
var preloader = document.querySelector('#preloader');
// if it exists, remove it from the page
if(preloader) {
preloader.remove();
}
}
Ahora veremos dónde usar estas funciones.
var request = new XMLHttpRequest();
Dentro de la `onreadystatechangefunction` que debe tener una sentencia `if` con la condición: `request.readyState == 4 && request.status == 200`.
Si es verdadero : la solicitud ha finalizado y la respuesta está lista, ahí es donde usaremos `removePreloader()`.
De lo contrario, si es falso : la solicitud aún está en curso, en este caso ejecutaremos la `functionaddPreloader()`'
xmlhttp.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
// the request has come to an end, remove the preloader
removePreloader();
} else {
// the request isn't finished, add the preloader
addPreloader()
}
};
xmlhttp.open('GET', your_file.php, true); xmlhttp.send();
## Mostrando las principales preguntas de JavaScript del mes desde la API de Stack Overflow
### Ejemplo
Podemos realizar una solicitud AJAX a la API de Stack Exchange para recuperar una lista de las principales preguntas de JavaScript del mes y luego presentarlas como una lista de enlaces. Si la solicitud falla o devuelve un error de API, nuestro manejo de errores de promesa muestra el error en su lugar.
Vea los resultados en vivo en HyperWeb .
const url = 'http://api.stackexchange.com/2.2/questions?site=stackoverflow' + '&tagged=javascript&sort=month&filter=unsafe&key=gik4BOCMC7J9doavgYteRw((';
fetch(url)
.then(response => response.json())
.then(data => {
if (data.error_message) {
throw new Error(data.error_message);
}
const list = document.createElement('ol');
document.body.appendChild(list);
for (const {title, link} of data.items) {
const entry = document.createElement('li');
const hyperlink = document.createElement('a');
entry.appendChild(hyperlink);
list.appendChild(entry);
hyperlink.textContent = title;
hyperlink.href = link;
}
})
.then(null, error => {
const message = document.createElement('pre');
document.body.appendChild(message);
message.style.color = 'red';
message.textContent = String(error);
}
);
## Escuchar eventos AJAX a nivel global
### Ejemplo
// Store a reference to the native method
let open = XMLHttpRequest.prototype.open;
// Overwrite the native method
XMLHttpRequest.prototype.open = function() {
// Assign an event listener
this.addEventListener("load", event => console.log(XHR), false);
// Call the stored reference to the native method
open.apply(this, arguments);
};
## Envío y recepción de datos JSON a través de POST
### Ejemplo
Las promesas de solicitud de recuperación inicialmente devuelven objetos de respuesta. Estos proporcionarán información de encabezado de respuesta, pero no incluyen directamente el cuerpo de la respuesta, que puede que ni siquiera se haya cargado todavía. Métodos en el objeto Response, como `.json()` se pueden usar para esperar a que se cargue el cuerpo de la respuesta y luego analizarlo.
const requestData = { method : 'getUsers' };
const usersPromise = fetch('/api', {
method : 'POST',
body : JSON.stringify(requestData)
})
.then(response => {
if (!response.ok) {
throw new Error("Got non-2XX response from API server.");
}
return response.json();
})
.then(responseData => {
return responseData.users;
});
usersPromise.then(users => {
console.log("Known users: ", users);
},
error => {
console.error("Failed to fetch users due to error: ", error);
});
## Usando GET y sin parámetros
### Ejemplo
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
//parse the response in
xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
|
Python
|
UTF-8
| 962
| 2.921875
| 3
|
[] |
no_license
|
from PIL import Image
import random as rd
imgx = 512
imgy = 512
image = Image.new("RGB", (imgx, imgy))
for x in range(imgx):
for y in range(imgy):
image.putpixel((x,y),(0,0,0))
snakenum = 65
r= 0
g = 0
b = 0
lol = 0
global turn
global snakey
turn = 0
def pr():
global turn, snakey
turn = snakey
for x in range(snakenum):
snakey = 0
r = rd.randrange(255)
g = rd.randrange(255)
b = rd.randrange(255)
snakex = rd.randrange(imgx)
for x in range(3000):
if snakey <= 510:
lol = rd.randrange(10)
if lol < 2:
if snakex != 0:
snakex -= 1
else:
if snakey < imgy:
snakey +=1
image.putpixel((snakex, snakey),(r,g,b))
pr()
elif lol > 7:
if snakex != imgx:
snakex += 1
else:
if snakey < imgy:
snakey += 1
image.putpixel((snakex, snakey),(r,g,b))
pr()
else:
if snakey < imgy:
snakey += 1
image.putpixel((snakex, snakey),(r,g,b))
pr()
image.save("snake.png", "PNG")
|
JavaScript
|
UTF-8
| 1,704
| 3.640625
| 4
|
[] |
no_license
|
/*
Caldo o freddo
Scrivi un programma che dati sette valori relativi alle temperature della settimana
stabilisca la giornata più calda e quella più fredda.
Esempio:
Input: a = 10, b = -2, c = 31, d = 22, e = 15, f = -6, g = 7
Output: giornata più calda = 31, giornata più fredda = -6
http://www.imparareaprogrammare.it
*/
var a = 10;
var b = -2;
var c = 31;
var d = 22;
var e = 15;
var f = -6;
var g = 7;
if (a>b & a>c & a>d & a>e & a>f & a>g){
console.log('giornata più calda'+a);
}
else if (b>a & b>c & b>d & b>e & b>f & b>g) {
console.log('giornata più calda'+b);
}
else if (c>a & c>b & c>d & c>e & c>f & c>g) {
console.log('giornata più calda'+c);
}
else if (d>a & d>b & d>c & d>e & d>f & d>g) {
console.log('giornata piu calda'+d);
}
else if (e>a & e>b & e>c & e>d & e>f & e>g) {
console.log('giornata piu calda'+e);
}
else if (f>a & f>b & f>c & f>d & f>e & f>g) {
console.log('giornata più calda'+f);
}
else if (g>a & g>b & g>c & g>d & g>e & g>f) {
console.log('giornata più calda'+g);
}else {
console.log();
}
if (a<b & a<c & a<d & a<e & a<f & a<g){
console.log('giornata più fredda'+a);
}
else if (b<a & b<c & b<d & b<e & b<f & b<g) {
console.log('giornata più fredda'+b);
}
else if (c<a & c<b & c<d & c<e & c<f & c<g) {
console.log('giornata più fredda'+c);
}
else if (d<a & d<b & d<c & d<e & d<f & d<g) {
console.log('giornata piu fredda'+d);
}
else if (e<a & e<b & e<c & e<d & e<f & e<g) {
console.log('giornata piu fredda'+e);
}
else if (f<a & f<b & f<c & f<d & f<e & f<g) {
console.log('giornata più fredda'+f);
}
else if (g<a & g<b & g<c & g<d & g<e & g<f) {
console.log('giornata più fredda'+g);
}else {
console.log();
}
|
PHP
|
UTF-8
| 695
| 3.5
| 4
|
[] |
no_license
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>array asociativo equipo</title>
</head>
<body>
<?php
echo "Equipo antes de añadir a otro jugador";
$equipo1 = array (
'Jose' => 'Base',
'Elena' => 'Escolta',
);
echo "<br>";
foreach ($equipo1 as $position => $element){
echo $position . ": " . $element . '<br>';
}
echo "<br>";
echo "Equipo después de añadir a otro jugador";
$equipo1 ['Ramona'] = 'Ala';
$equipo1 ['Dionis'] = 'Alero';
echo "<br>";
foreach ($equipo1 as $position => $element){
echo $position . ": " . $element . '<br>';
}
?>
</body>
</html>
|
Java
|
UTF-8
| 1,096
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.routing.august;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class ThirdRouting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
// TODO Auto-generated method stub
/* from("file:src/main/data/in?noop=true")
.choice()
.when(simple("${file:ext} == 'txt'"))
.to("file:src/main/data/out/uk")
.when(simple("${file:ext} == 'xml'"))
.to("file:src/main/data/out/others");*/
//system
//backup prog
from("file:src/main/data/in?noop=true&move=D:/softwares/backup${date:now:yyyyMMdd}/${file:name.noext}.xml&recursive=false&sortBy=reverse:file:name")
.log(" reverse message ${body}")
.to("file:src/main/data/out/others");
}
});
context.start();
Thread.sleep(50000);
}
}
|
C#
|
UTF-8
| 2,411
| 2.6875
| 3
|
[] |
no_license
|
using ERP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using TestApp.ServiceReference1;
namespace TestApp
{
class MainViewModel : ViewModelBase
{
#region Fields
EmpserviceClient EmpService;
#endregion
#region Constructor
public MainViewModel()
{
EmpService = new EmpserviceClient();
RefreshEmployees();
CurrentEmployee = new Employee();
}
#endregion
#region Properties
private IEnumerable<Employee> _Employee;
public IEnumerable<Employee> Employee
{
get { return _Employee; }
set { _Employee = value; OnPropertyChanged("Employee"); }
}
private Employee _CurrentEmployee;
public Employee CurrentEmployee
{
get { return _CurrentEmployee; }
set { _CurrentEmployee = value; OnPropertyChanged("CurrentEmployee"); }
}
#endregion
#region RefreshMethods
private void RefreshEmployees()
{
EmpService.GetEmployeeCompleted += (s, e) =>
{
Employee = e.Result;
};
EmpService.GetEmployeeAsync();
}
#endregion
#region Button Commands
public ICommand SaveButton
{
get { return new RelayCommand(Save); }
}
#endregion
#region Methods
private void Save()
{
if (CurrentEmployee.Emp_id ==0)
{
if (EmpService.save_employee(CurrentEmployee))
{
MessageBox.Show("Success");
RefreshEmployees();
CurrentEmployee = new Employee();
}
else
MessageBox.Show("Fail");
}
else
{
if(EmpService.Update_Employee(CurrentEmployee))
{
MessageBox.Show("Update Success");
RefreshEmployees();
CurrentEmployee = new Employee();
}
else
MessageBox.Show("Update Fail");
}
}
#endregion
}
}
|
Python
|
UTF-8
| 2,481
| 3.671875
| 4
|
[] |
no_license
|
def pre_flop_strength_1():
# Sklansky hand groups: lower group value means better ranking of cards
# "http://www.thepokerbank.com/strategy/basic/starting-hand-selection/sklansky-groups/"
ranks = "23456789TJQKA"
suits = "cdhs"
# input hand for evaluation
hand = input('Enter the hand:').split() # ["Ah", "2h"]
# sorting the two hand cards in descending order (Expected order : "HigherCard(suit)LowerCard(suit)")
if ranks.index(hand[0][0]) < ranks.index(hand[1][0]):
hand[0], hand[1] = hand[1], hand[0]
# same suit pocket cards groups
if hand[0][1] == hand[1][1]:
same_suit_groups={ "AK":1,
"AQ":2, "AJ":2, "KQ":2,
"AT":3, "KJ":3, "QJ":3, "JT":3,
"KT":4, "QT":4, "J9":4, "T9":4, "98":4,
"A9":5,"A8":5,"A7":5,"A6":5,"A5":5,"A4":5,"A3":5,"A2":5,"Q9":5, "T8":5, "97":5, "87":5, "76":5,
"J8":6, "86":6, "75":6, "65":6, "54":6,
"64":7, "53":7, "43":7, "K9":7,"K8":7,"K7":7,"K6":7,"K5":7,"K4":7,"K3":7,"K2":7,
"J7":8, "96":8, "85":8, "74":8, "42":8, "32":8
}
# combining the value of cards into single string for dictionary lookup
hand_value = hand[0][0]+hand[1][0]
if hand_value in same_suit_groups:
group = same_suit_groups.get(hand_value)
else:
# According to Sklansky the remaining cards fall into group 9
group = 9
else:
# off suit pocket cards groups
off_suit_groups ={"AA":1, "KK":1, "QQ":1, "JJ":1,
"AK":2,"TT":2,
"AQ":3, "99":3,
"AJ":4, "KQ":4, "88":4,
"KJ":5, "QJ":5, "JT":5,"77":5, "66":5,
"AT":6, "KT":6, "QT":6,"55":6,
"J9":7, "T9":7, "98":7,"44":7,"33":7,"22":7,
"A9":8, "K9":8, "Q9":8, "J8":8,"T8":8, "87":8, "76":8, "65":8, "54":8
}
# combining the value of cards into single string for dictionary lookup
hand_value = hand[0][0]+hand[1][0]
if hand_value in off_suit_groups:
group = off_suit_groups.get(hand_value)
else:
# According to Sklansky the remaining cards fall into group 9
group = 9
print(group)
return group
pre_flop_strength_1()
|
Python
|
UTF-8
| 1,463
| 2.5625
| 3
|
[] |
no_license
|
import os
def getNIDdb(year=0, month=0, day=0):
nids = {}
for i in os.listdir('/usr/local/tcs/tums/rrd/'):
if not ".nid" in i:
continue
if not "total" in i:
continue
try:
n, iface, fdate = i.split('_')
d, m, y, j = fdate.split('-')
except:
continue
if year and int(y)!=year:
continue
if month and int(m)!=month:
continue
if day and int(d)!=day:
continue
if iface not in nids:
nids[iface] = []
nids[iface].append((i,int(y),int(m),int(d)))
return nids
def getNIDdaySummary(year, month):
"""Returns a NID summary info, highest day and largest combined value
for a particular month+year"""
niddbs = getNIDdb(year, month)
nds = {}
maxd = 0
maxunit = 0
for iface, nids in niddbs.items():
ds = {}
dl = []
for nid,y,m,d in nids:
try:
vi, vo= [float(i) for i in open('/usr/local/tcs/tums/rrd/'+nid).read().strip('\n').split(':')]
ds[d] = (vi, vo)
if vi+vo > maxunit:
maxunit = vi+vo
dl.append(d)
if d > maxd:
maxd = d
except Exception, e:
continue
dl.sort()
k = [(i,ds[i]) for i in dl]
nds[iface] = k
return nds, maxd, maxunit
|
Python
|
UTF-8
| 405
| 3.859375
| 4
|
[] |
no_license
|
def pascalTriangle(numRows):
res = []
if numRows == 0:
return res
first = [1]
res.append(first)
for i in range(1, numRows):
row = [1]
prev = res[i-1]
for j in range(1, i):
row.append(prev[j-1] + prev[j])
row.append(1)
res.append(row)
return res
print(pascalTriangle(5)) # [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
|
C
|
UTF-8
| 1,018
| 3.78125
| 4
|
[
"MIT"
] |
permissive
|
/**
* mario.c
*
* Ahasanul Basher Hamza
* ahasanulhamza133@gmail.com
*
* hamza133
*
* A program that recreates half-pyramid using hashes (#) for blocks
*
*
**/
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
// using do-while loop for asking user the right input
do
{
printf("height: ");
// using GetInt() function from cs50 library to take input from the user
n = GetInt();
// error checking
if(n == 0)
{
return 0;
}
}
while(n < 1 || n > 23);
// first loop is iterating over the rows
// second loop is iterating over the columns and printing spaces
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n - i - 1; j++)
{
printf(" ");
}
// third for loop is using for printing the hashes
for(int k = 0; k < i + 2; k++)
{
printf("#");
}
printf("\n");
}
}
|
Python
|
UTF-8
| 899
| 3.953125
| 4
|
[] |
no_license
|
# 4. Представлен список чисел. Определить элементы списка, не имеющие повторений.
# Сформировать итоговый массив чисел, соответствующих требованию.
# Элементы вывести в порядке их следования в исходном списке.
# Для выполнения задания обязательно использовать генератор.
# Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11].
# Результат: [23, 1, 3, 10, 4, 11]
from random import randint
random_list = [randint(1, 50) for x in range(15)]
result_list = [el for el in random_list if random_list.count(el) == 1]
print(f"Исходный список: {random_list}")
print(f"Результат: {result_list}")
|
JavaScript
|
UTF-8
| 2,312
| 3.953125
| 4
|
[] |
no_license
|
var engineAndISP = []; //declaring empty arrays
var engine = [];
function Engine(name,exhastSpeed) { //constructor used to input engine parameters
this.name = name;
this.exhastSpeed = exhastSpeed;
this.isp = 0;
}
function calcISP(engine,callback,options) { //function to calculate ISP. Takes in an engine object, a callback function to determine what to do, and any options on that callback function
engine.isp = Math.round(engine.exhastSpeed / 9.81); //simple calculation to get ISP of engine and storing the result in the objects isp parameter
if(!options) {
callback(engine.name + " Isp: " + engine.isp + " seconds"); //if no option parameter is called (in the case of the print function) omit the options parameter
}
else {
callback(options,engine.name + " Isp: " + engine.isp + " seconds"); //else include and read the options parameter
}
}
function print(param) { //print whatever parameter is passed to it out to the console
console.log(param);
}
function toArray(array,param) { //push whatever parameter is passed to it to the array specified
array.push(param);
}
function printArray(param) { //print the contents of an array line by line
for(var i=0; i<param.length; i++) {
print(param[i]);
}
}
function logArray(engineArray) { //take the contents of a specified array and pass it into the calcISP function, then log the results into the engineAndISP array
for(var i=0; i<engineArray.length; i++) {
calcISP(engineArray[i],toArray,engineAndISP);
}
printArray(engineAndISP); //print the engineAndISP array to the console
console.log("\n"); // line break (just to make everything look clean)
}
engine[0] = new Engine("Space Shuttle Main Engine",4400); //passing parameters into the Engine object contructor (name and exhast speed)
engine[1] = new Engine("Solid Rocket Booster",2500);
engine[2] = new Engine("Ion Thruster",29000);
engine[3] = new Engine("Nuclear Thermal Rocket",8300);
var ssme = engine[0]; //setting objects in the engine array equal to variable names for easier access when using print callback function
var srb = engine[1];
var ion = engine[2];
var nuclear = engine[3];
logArray(engine); //calling the logArray function the the console
calcISP(ion,print); //caling the calcISP function with the print callback function to log it to the console
|
Java
|
UTF-8
| 690
| 2.234375
| 2
|
[] |
no_license
|
package com.rest.shifts.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.time.LocalDateTime;
public class ShiftDto {
private int id;
private LocalDateTime from;
private LocalDateTime to;
private int workerId;
public ShiftDto(int id, LocalDateTime from, LocalDateTime to, int workerId) {
this.id = id;
this.from = from;
this.to = to;
this.workerId = workerId;
}
public int getId() {
return id;
}
public LocalDateTime getFrom() {
return from;
}
public LocalDateTime getTo() {
return to;
}
public int getWorkerId() {
return workerId;
}
}
|
Java
|
UTF-8
| 637
| 3.09375
| 3
|
[] |
no_license
|
package com.train;
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
int exit = 0;
while (exit != -1){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter number of tickets:\t");
int ticket = scanner.nextInt();
exit = ticket;
if (exit != -1) {
System.out.print("How many round-trip tickets:\t");
int roundTrip = scanner.nextInt();
Tickets tickets = new Tickets(ticket, roundTrip);
tickets.print();
}
}
}
}
|
Markdown
|
UTF-8
| 485
| 2.515625
| 3
|
[] |
no_license
|
# mini-questionnaire-app
This app allows pass questionnaires for registered users and create new questionnaires for admin
# it runs on http://localhost:8080/
# default users
DB has 2 users those you can use for testing:
username: 'user' password: 'user' - has only role 'USER';
username: 'admin' password: 'admin' - has roles 'USER' and 'ADMIN'
# default questionnaires
App also has two pre-constructed questionnaires. You can play with it, or build your own questionnaire!
|
C#
|
UTF-8
| 2,555
| 2.921875
| 3
|
[] |
no_license
|
using EugeneForUwp.Configuration;
using EugeneForUwp.Network;
namespace EugeneForUwp
{
public class Eugene
{
private ConfigurationFileReader _configFileReader;
private Configuration.Configuration _configuration;
private double _currentSoftwareVersion;
/// <summary>
/// Default constructor
/// <param name="configFileLocation">The absolute path of the configuration file</param>
/// <param name="currentSoftwareVersion">The current version number of the software</param>
/// </summary>
public Eugene(string configFileLocation, double currentSoftwareVersion)
{
_configFileReader = new ConfigurationFileReader(configFileLocation);
_configuration = new Configuration.Configuration(_configFileReader.FileContents);
_currentSoftwareVersion = currentSoftwareVersion;
}
/// <summary>
/// Constructor that reads the current local software version from the local Eugene file
/// </summary>
/// <param name="configFileLocation">The absolute path of the configuration file</param>
public Eugene(string configFileLocation)
{
_configFileReader = new ConfigurationFileReader(configFileLocation);
_configuration = new Configuration.Configuration(_configFileReader.FileContents);
_currentSoftwareVersion = double.Parse(_configuration.GetValue("localVersion"));
}
/// <summary>
/// Checks with the configuration file and the current version is outdated
/// </summary>
/// <returns>True if a new version is available</returns>
public async System.Threading.Tasks.Task<bool> CurrentVerionIsOutdatedAsync()
{
RemoteVersionChecker versionChecker = new RemoteVersionChecker(_configuration.GetValue("location"));
var remoteVersion = await versionChecker.GetRemoteVersionNumberAsync();
return remoteVersion > _currentSoftwareVersion;
}
/// <summary>
/// Checks on the remote location where the new software version can be downloaded
/// </summary>
/// <returns>The URL where the new software version is located</returns>
public async System.Threading.Tasks.Task<string> GetDownloadLocationAsync()
{
RemoteDownloadLocation downloadLocation = new RemoteDownloadLocation(_configuration.GetValue("location"));
return await downloadLocation.GetDownloadLocationAsync();
}
}
}
|
C++
|
UTF-8
| 494
| 2.640625
| 3
|
[] |
no_license
|
#include <cstdio>
int x[3000000];
int y[3000000];
int n, m;
const int M = 1000000007;
int main()
{
x[0] = 1;
for (int i = 1; i <= 2000000; i++)
{
x[i] = (long long)x[i - 1] * i % M;
}
y[1] = 1;
for (int i = 2; i <= 2000000; i++)
{
y[i] = (-(long long)(M / i) * y[M % i] % M + M) % M;
}
for (int i = 2; i <= 2000000; i++)
{
y[i] = (long long)y[i - 1] * y[i] % M;
}
scanf("%d%d", &n, &m);
printf("%lld\n", (long long)x[n + m - 2] * y[n - 1] % M * y[m - 1] % M);
return 0;
}
|
Java
|
UTF-8
| 1,171
| 2.21875
| 2
|
[] |
no_license
|
package com.percussion.pso.relationshipbuilder;
import static java.util.Arrays.asList;
import java.util.Collection;
import com.percussion.error.PSException;
import com.percussion.services.assembly.PSAssemblyException;
public class PSFolderRelationshipBuilder extends PSAbstractRelationshipBuilder {
private String m_jcrQuery;
@Override
public void add(int sourceId, Collection<Integer> targetIds) throws PSAssemblyException, PSException {
m_relationshipHelperService.addFolderRelationships(targetIds, asList(sourceId));
}
@Override
public void delete(int sourceId, Collection<Integer> targetIds) throws PSAssemblyException, PSException {
m_relationshipHelperService.deleteFolderRelationships(targetIds, asList(sourceId));
}
public Collection<Integer> retrieve(int sourceId) throws PSAssemblyException, PSException {
return m_relationshipHelperService.getFolders(sourceId, m_jcrQuery);
}
public String getJcrQuery() {
return m_jcrQuery;
}
public void setJcrQuery(String jcrQuery) {
m_jcrQuery = jcrQuery;
}
}
|
Java
|
UTF-8
| 1,711
| 3.140625
| 3
|
[] |
no_license
|
/**
* COPYRIGHT. Harry Wu 2010. ALL RIGHTS RESERVED.
* Project: EasyPhoto
* Author: Harry Wu <harrywu304@gmail.com>
* Created On: Jun 28, 2008 5:12:21 PM
*
*/
package org.shaitu.easyphoto.util;
import java.util.Collection;
/**
* String referred method
* @author lx5
*/
public class StringUtil {
/**
* check if a string is null or blank
* @param str
* @return
*/
public static boolean isNullOrBlank(String str) {
if (str == null || "".equals(str.trim())) {
return true;
}
return false;
}
/**
* concat objects in collection to a single string
* @param cc collection
* @return string
*/
public static String joinCollection(Collection cc) {
StringBuffer sb = new StringBuffer();
for (Object obj : cc) {
sb.append(obj.toString()).append(",");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* format string for print, if string not empty append space to the end
* @param str string to print
* @return formatted string
*/
public static String getPrintString(String str) {
if (str == null || "".equals(str.trim())) {
return "";
} else {
str = str + " ";
}
return str;
}
/**
* check if the string contains Chinese
* @param str
* @return
*/
public static boolean isContainChinese(String str) {
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
return true;
}
}
return false;
}
}
|
Java
|
UTF-8
| 1,933
| 3.75
| 4
|
[] |
no_license
|
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
/**
* This is a Predator class that inheritance all of the methods and shapes from the super class Creature
* In class it contains the a move method that allows the object to change its direction
* @author Semir
*
*/
public class Predator extends Creature
{
/**
* Takes all the information in the creature
* @param x
* @param y
* @param w
* @param h
*/
public Predator(int x, int y, int w, int h)
{
super(x,y,w,h, 1, 1, 2, Color.yellow);//direction,direction,speed,color to be yellow
}
/**
* Takes all the information from move method from the super class Creature
*/
public void move()
{
super.move();
}
/**
* Changes the move direction by GameComponent and action class method when clicked with a mouse it goes through to see which direction the predator is going
*/
public void turnRight()
{
if(super.getMovementDirection() == 1)
super.setMovementDirection(-2);
else if(super.getMovementDirection() == -2)
super.setMovementDirection(-1);
else if(super.getMovementDirection() == -1)
super.setMovementDirection(2);
else if(super.getMovementDirection() == 2)
super.setMovementDirection(1);
}
/**
* Changes the move direction by GameComponent and action class method when clicked with a mouse it goes through to see which direction the predator is going
*/
public void turnLeft()
{
if(super.getMovementDirection() == 1)
super.setMovementDirection(2);
else if(super.getMovementDirection() == 2)
super.setMovementDirection(-1);
else if(super.getMovementDirection() == -1)
super.setMovementDirection(-2);
else if(super.getMovementDirection() == -2)
super.setMovementDirection(1);
}
/**
* Takes all the information from draw method from the super class Creature
*/
public void draw(Graphics2D g2)
{
super.draw(g2);
}
}
|
Java
|
UTF-8
| 720
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.nimbusds.jose.util;
import java.util.Arrays;
import com.nimbusds.jose.util.ByteUtils;
import junit.framework.TestCase;
/**
* Tests the byte utilities.
*/
public class ByteUtilsTest extends TestCase {
public void testConcat() {
byte[] a1 = { (byte)1, (byte)2 };
byte[] a2 = { (byte)3, (byte)4 };
byte[] out = ByteUtils.concat(a1, a2);
assertTrue(Arrays.equals(new byte[]{(byte)1, (byte)2, (byte)3, (byte)4}, out));
}
public void testConcatWithNullValue() {
byte[] a1 = { (byte)1, (byte)2 };
byte[] a2 = null;
byte[] a3 = { (byte)3, (byte)4 };
byte[] out = ByteUtils.concat(a1, a2, a3);
assertTrue(Arrays.equals(new byte[]{(byte)1, (byte)2, (byte)3, (byte)4}, out));
}
}
|
JavaScript
|
UTF-8
| 628
| 4.3125
| 4
|
[] |
no_license
|
// Exercicios
console.log('ola');
// Qual o resultado da seguinte expressão?
var total = 10 + 5 * 2 / 2 + 20;
console.log(total);
// resposta = 35
// Crie uma expressões que retorna NaN
var mes = 'agosto';
var ano = 2020;
console.log(ano * mes);
// Somar a string '200' com o número 50 e retornar 250
var duz = +'200';
var cinq = 50;
console.log(duz + cinq);
// Incremente o número 5 e retorne o seu valor incrementado
var num = 5;
console.log(++num);
// Como dividir o peso por 2
var numero = '80';
var unidade = 'kg';
var dividir = numero / 2;
var peso = dividir + unidade;
console.log(peso);
|
Markdown
|
UTF-8
| 2,116
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: "AI for policing in southeast China"
tags: idc
permalink: policing
---
### AI for policing in Jiangxi province in southeast China.
In Nanchang, the capital of Jiangxi province in southeast China, a crowd of 60,000 people had gathered for a concert. This was about 1% of the population of the city.
Cameras at the stadium flagged a man in the crowd. Police monitoring the crowd using surveillance software were alerted about a possible match found in a national database of wanted men and women. The police look at the match and could choose to intervene and question or potentially arrest the person.

They decide that they want to intervene, and police officers reach his seat and arrest him for “economic crimes”.
The man caught at the concert said he thought he would be safe in a crowd of tens of thousands. He and some friends had bought the concert tickets, and had driven with his wife about 60 miles to see the show.
Chinese authorities are also building and deploying a predictive policing program based on big data analysis in Xinjiang. The program aggregates data about people – often without their knowledge – and flags those it deems potentially threatening to officials.
According to interviewees, some of those targeted are detained and sent to extralegal “political education centers” where they are held indefinitely without charge or trial, and can be subject to abuse. Since around April 2016, Human Rights Watch estimates, Xinjiang authorities have sent tens of thousands of Uyghurs and other ethnic minorities to these “political education centers.”
### Sources
1. [A suspect tried to blend in with 60,000 concertgoers. China’s facial-recognition cameras caught him.](https://www.washingtonpost.com/news/worldviews/wp/2018/04/13/china-crime-facial-recognition-cameras-catch-suspect-at-concert-with-60000-people/)
2. [China: Big Data Fuels Crackdown in Minority Region](https://www.hrw.org/news/2018/02/26/china-big-data-fuels-crackdown-minority-region)
|
JavaScript
|
UTF-8
| 4,380
| 4
| 4
|
[] |
no_license
|
// Level: MediumGiven an array of integers, print all combinations of size X.
// Questions to Clarify:
// Q. Can the array have duplicates?
// A. No, you can assume there are no duplicate numbers.
// Q. What to print if X is greater than the size of the array?
// A. Print nothing, as there will be no valid combinations.
// Q. What to print if the array is empty?
// A. Print nothing as there will be no combinations.
function printAllValidCombinations(arr, x) {
if (x > arr.length || !arr?.length) return;
let buffer = [];
printCombosHelper(arr, x, buffer, 0, 0);
}
function printCombosHelper(arr, x, buffer, startIdx, bufferIdx) {
//termination cases
//buffer is full print it out
if (bufferIdx === x) {
printCombos(buffer);
return;
}
//you've run out of array to print
if (startIdx === arr.length) {
return;
}
//fill in the buffer
for (let i = startIdx; i < arr.length; i++) {
buffer[bufferIdx] = arr[i];
printCombosHelper(arr, x, buffer, i + 1, bufferIdx + 1);
}
}
function printCombos(combo) {
console.log(combo);
}
// printAllValidCombinations([1, 2, 3, 4], 3);
// <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
// // Given an array of integers A, print all its subsets.For
// example:Input: [1, 2, 3]
// Output:[][1][2][3][1, 2][1, 3][2, 3][1, 2, 3]
// Q. Do we print out the empty set?
// A. Yes
// Q. Can we assume there are no duplicates?
// A. Yes
// Q. If the input is an empty array, do we just print out the empty set?
// A. Yes
// Q. If the input is null, should we throw an exception of simply print nothing?
// A. Let's just print nothing.
function printAllSubsets(a) {
let buffer = [];
printSubsetsHelper(a, buffer, 0, 0);
}
function printSubsetsHelper(a, buffer, startIdx, bufferIdx) {
// print buffer
printSubsets(buffer, bufferIdx);
//termination casses
if (bufferIdx === a.length || startIdx === a.length) return;
//Fill the buffer
for (let i = startIdx; i < a.length; i++) {
buffer[bufferIdx] = a[i];
printSubsetsHelper(a, buffer, i + 1, bufferIdx + 1);
}
}
function printSubsets(buffer, bufferIdx) {
console.log(buffer.slice(0, bufferIdx));
}
// printAllSubsets([1, 2, 3]);
// // <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
// Given an array A, print all permutations of size X.For example,
// Input:A = [1,2,3]X = 2
// Output:[1, 2][1, 3][2, 1][2, 3][3, 1][3, 2]
// Same clarifying questions and answers as above
function findPerms(a, x) {
let buffer = [],
isInBuffer = [];
permsHelper(a, x, buffer, 0, isInBuffer);
}
function permsHelper(a, x, buffer, bufferIdx, isInBuffer) {
// If buffer is full then print perm
if (bufferIdx === x) {
printPerm(buffer);
return;
}
// find the next value for the perm
for (let i = 0; i < a.length; i++) {
if (!isInBuffer[i]) {
//mark index so as not to repeat it
isInBuffer[i] = true;
// add value to buffer
buffer[bufferIdx] = a[i];
//recurse to find subsequent values
permsHelper(a, x, buffer, bufferIdx + 1, isInBuffer);
// remove i from isInBuffer because we are now done with it
isInBuffer[i] = false;
}
}
}
function printPerm(buffer) {
console.log(buffer);
}
// findPerms([1, 2, 3], 2);
//
// <><><><<><><><<><><><<><><><<><><><<><><><<><><><<><><><<><><><<><><><<><><><<><><><
// Coin Change Problem: Given a set of coin denominations, print out the different ways you can make a target amount. You can use as many coins of each denomination as you like.
// For example: If coins are [1,2,5] and the target is 5, output will be:
// [1,1,1,1,1]
// [1,1,1,2]
// [1,2,2]
// [5]
function makeTotal(a, target) {
if (!a?.length || target <= 0) return;
let buffer = [];
makeTotalHelper(a, target, buffer, 0, 0, 0);
}
function makeTotalHelper(a, target, buffer, bufferIdx, startIdx, total) {
//termination case
if (total === target) {
printBuffer(buffer);
return;
}
if (total > target) {
return;
}
//find next possible selections for buffer
for (let i = startIdx; i < a.length; i++) {
buffer.push(a[i]);
//recurse to check solution and find next values
makeTotalHelper(a, target, buffer, bufferIdx + 1, i, total + a[i]);
buffer.pop();
}
}
function printBuffer(buffer) {
console.log(buffer);
}
makeTotal([1, 2, 5], 5);
|
C++
|
UTF-8
| 2,350
| 3.59375
| 4
|
[] |
no_license
|
#include "pch.h"
#include "Bitmap.h"
Bitmap::Bitmap(int len)
{
// Setting the max number of elements in the Bitmap
length = len;
// Creating the array to store length number of objects
int numberOfElements = 1 + (length / (8 * sizeof(char)));
mapPtr = new char[numberOfElements];
// Initialise all elements to 0
for (int i = 0; i < numberOfElements; ++i)
mapPtr[i] = 0;
}
Bitmap::~Bitmap()
{
delete[] mapPtr;
}
bool Bitmap::add(int index)
{
// Get a mask with a 1 at the correct radix of the char (0 - 7)
// 0s everywhere else
// Save the oldCopy of the char at that index
// OR the mask with the oldCopy and add the new result into the mapPtr array
// if the oldCopy AND the mask = 0, a value was added, return true
// else no new value was added, return false
return false;
}
bool Bitmap::remove(int index)
{
// Get a mask with a 0 at the correct radix of the char (0 - 7)
// 1s everywhere else
// Save the oldCopy of the char at that index
// AND the mask with the oldCopy and add the new result into the mapPtr array
// take a new mask, with a 1 at the correct radix of the char (0 - 7)
// 0s everywhere else
// if the oldCopy AND the new mask = 0, a value was added, return true
// else no new value was added, return false
return false;
}
bool Bitmap::contains(int index) const
{
// Get a mask with a 0 at the correct radix of the char (0 - 7)
// 1s everywhere else
// if the oldCopy AND the new mask = 0, a value was added, return true
// else no new value was added, return false
return false;
}
int Bitmap::getSize() const
{
return size;
}
bool Bitmap::operator[](int index) const
{
// get the correct index of the mapPtr
// Use a mask to AND with the value at that index and return the result
return false;
}
bool Bitmap::setBit(int bitIndex)
{
// mask with a 1 at the appropriate bit
// OR with the correct index in the mapPtr
// return true if a change occoured, false otherwise
return false;
}
bool Bitmap::resetBit(int bitIndex)
{
// mask with a 0 at the appropriate bit
// AND with the correct index in the mapPtr
// return true if a change occoured, false otherwise
return false;
}
char Bitmap::getMask(int bitIndex)
{
// returns a mask with 1 at the appropriate location (0 - 7)
char mask = 1;
if (bitIndex <= 7)
return mask << bitIndex;
else return 0;
}
|
PHP
|
UTF-8
| 374
| 3.125
| 3
|
[] |
no_license
|
<?php
class usuario {
private $id, $nome, $email, $senha;
function __set($prop, $val) {
$this->$prop = $val;
}
function __get($prop) {
return $this->$prop;
}
function __construct($id, $nome, $email, $senha) {
$this->id = $id;
$this->nome = $nome;
$this->email= $email;
$this->senha = $senha;
}
}
?>
|
Python
|
UTF-8
| 1,663
| 4.03125
| 4
|
[] |
no_license
|
print("-- 슬라이싱 --")
nums = [0,1,2,3,4,5,6,7,8,9]
print(nums[2:5]) # 3번째 원소부터 5번째 원소까지
print(nums[:4]) # 첫번째 원소 부터 4번째 원소까지
print(nums[6:])
print(nums[1:7:2]) # 2번째 원소, 네번째 원소, 6번째 원소
print("-- 인덱스를 사용한 대입 --")
score = [ 88, 95, 70, 100, 99 ]
print(score[2])
score[2] = 55 # 3번째 원소를 55로 바꿈
print(score)
score[2] = [55, 66] # 3번째 원소가 서브리스트로 들어감.
print(score) # 3번째 요소만 두개의 요소의 값으로 구성된 리스트가 생김
print("-- 슬라이싱을 사용한 대입 --")
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums) # 리스트 만든 다음에 출력
nums[0:0] = [100] # [0], [0:1] : 첫번째 원소값을 100으로 바꿈, 그런데 [0:0] start = end 인경우 대체가 아닌 맨 앞에 껴놓겠다.
print(nums)
nums[2:5] = [20, 30, 40] # 3번째 원소부터 5번째원소[1,2,3] 자리에 20, 30, 40이 대신 들어감.
print(nums)
nums[6:8] = [90, 91, 92, 93, 94] # 7번째 원소부터 8번째 원소 자리에 빼서 90, 91, 92, 93, 94 끼워넣음
print(nums)
print("-- 슬라이싱을 사용한 제거 --")
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums)
nums[2:5] = [] # 3번째 원소부터 5번째 원소를 잘라냄
print(nums)
del nums[4] # 특정 요소를 잘라냄. 5번째 원소 잘라냄
print(nums)
print("-- 리스트 연산 --")
list1 = [1, 2, 3, 4, 5]
list2 = [10, 11]
listadd = list1 + list2 # 리스트끼리 결합하게 됨.
print(listadd)
listmulti = list2 * 3 # 리스트에 곱하기 3하면 3번 반복해서 리스트로 나옴.
print(listmulti)
|
C#
|
UTF-8
| 606
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
using System;
namespace FubuMVC.Core.Behaviors.Conditional
{
public class LambdaConditional : IConditional
{
private readonly Func<bool> _condition;
public LambdaConditional(Func<bool> condition)
{
_condition = condition;
}
public bool ShouldExecute()
{
return _condition();
}
}
public class LambdaConditional<T> : LambdaConditional
{
public LambdaConditional(T context, Func<T, bool> condition)
: base(() => condition(context))
{
}
}
}
|
Java
|
UTF-8
| 2,402
| 2.265625
| 2
|
[] |
no_license
|
package com.mfu.web.controller;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mfu.dao.record.LabTestResultDAO;
import com.mfu.entity.record.LabTestResult;
import com.mfu.web.model.WSResponse;
@Controller
public class LabTestController {
private static final Logger log = Logger
.getLogger(LabTestController.class.getName());
@RequestMapping(value = "/recordLabTestResultWS", method = RequestMethod.POST)
@ResponseBody
public String recordLabTestResult(@RequestBody LabTestResult v) {
LabTestResultDAO dao = new LabTestResultDAO();
try {
v.setUpdateDate(new Date());
dao.insertLabTestResult(v);
//HealthAnalysisController kc = new HealthAnalysisController();
//kc.classifySymptomCloudML(v);
return "1";
} catch (Exception e) {
e.printStackTrace();
log.warning(e.getMessage());
}finally{
dao.closeEntityManager();
}
return "-1";
}
@RequestMapping(value = "/getLatestLabTestWS", method = RequestMethod.GET)
@ResponseBody
public LabTestResult getLastRecord(HttpServletRequest request) {
LabTestResultDAO dao = new LabTestResultDAO();
try {
LabTestResult rec = dao.findLastLabTestResultByName(
request.getParameter("testName"),
request.getParameter("codeHN"));
return rec;
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
log.info("error occurs" + errors.toString());
}finally{
dao.closeEntityManager();
}
return null;
}
@RequestMapping(value = "/recordLabTestResultBatchWS", method = RequestMethod.POST)
@ResponseBody
public List<WSResponse> recordLabTestResultBatch(
@RequestBody LabTestResult[] vlist) {
List<WSResponse> resList = new ArrayList<WSResponse>();
String result;
for (LabTestResult v : vlist) {
result = this.recordLabTestResult(v);
resList.add(new WSResponse(v.getCodeHN(), Integer.parseInt(result)));
}
return resList;
}
}
|
PHP
|
UTF-8
| 1,293
| 2.6875
| 3
|
[] |
no_license
|
<?php
class ManagerTeam extends Team
{
public function __construct()
{
parent::__construct();
}
public function getNotification($idPlayer, $statusPlayer)
{
if ($idPlayer == false || $statusPlayer == false)
return 'Parâmetros session inexistente na função: ' . __FUNCTION__ . ' Linha: ' . __LINE__ . ' Arquivo: ' . __FILE__;
if ($idPlayer == '' || $statusPlayer == '')
return 'Parâmetros incorretos na função: ' . __FUNCTION__ . ' Linha: ' . __LINE__ . ' Arquivo: ' . __FILE__;
if ($statusPlayer != 1)
return array('without permission');
$arrTeam = $this->getTeamIdDb($idPlayer);
if (!is_array($arrTeam))
return 'Time inexistente na função: ' . __FUNCTION__ . ' Linha: ' . __LINE__ . ' Arquivo: ' . __FILE__;
try {
$stmt = Conexao::getInstance()->prepare('SELECT a.id, c.nome, a.dt_registro FROM team_player AS a
INNER JOIN user AS c on a.id_player = c.id
WHERE a.id_team = 1
AND a.access_status = 2
ORDER BY a.id DESC;');
$stmt->bindParam(':id_team', $arrTeam[0]['id']);
$stmt->execute();
$final_result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return (!empty($final_result)) ? $final_result : array('vazio');
} catch (Exception $e) {
return $e->getMessage();
}
}
}
|
Python
|
UTF-8
| 559
| 2.703125
| 3
|
[] |
no_license
|
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print 'waiting for connection'
tcpClickSock, addr = tcpSerSock.accept()
print '... connected form:', addr
while True:
data = tcpClickSock.recv(BUFSIZE)
print 'he say'
if not data:
break
tcpClickSock.send('[%s] %s' % (
ctime(),data
))
tcpClickSock.close()
tcpSerSock.close()
|
Markdown
|
UTF-8
| 6,550
| 2.796875
| 3
|
[] |
no_license
|
七七
由于那传音老人的连番指示,沈元通已经对他产生了亲切之感,不由运功呼道:“敢请老前辈显现法驾,以便晚辈叩见一下!”
那苍老的声音哈哈笑道:“时候到了,我们自会见面,何必急在今天。”
二人赶到江边,果见江边有三株立的撑天古树,沈元通神目扫处,数丈之外,便已见到那居中的树杈间,悬着一只掌大纸包。
沈元通身似电闪,伸手取下纸包,只见包面上老气横秋地写一行字道:“沈娃娃收拆。”纸包之内,只有一本四五页的小绢册,封面上题着“天籁之音”四字。
沈元通翻开蝉页,发现里面还夹着一只便条,上写寥寥数字:“三箫合壁,广布天音,镇魔卫道,廓乾朗坤。”
沈元通知道这张便笺是那传音老人所写,当下慎重的将之收起,然后又从头翻阅那本题为“天籁之音”的小册。
原来所谓“天籁之音”,只是一首极长的三箫合奏的乐曲。
沈元通对于音律之学,原有极深的素修,这时只见他的脸上,穆肃中犹掩不住一片惊喜之色,口中并哼哼唧唧地低声吟哦着。
铁心秀士曾弼对音律方面的造诣虽赶不上沈元通多多,却也非平常之辈可比,何况这种天籁之音,乃发于自然之律,纵是一条大莽牛,也必然受其感染影响,率性而动,不由自主。
唯因智慧之高低,其感受之程度有深浅之不同罢了。是以,铁心秀士曾弼仅耳闻沈元通的口诵,立即灵犀活跃,身子不由蹯之舞之起来。
沈元通一口气诵完全曲,心灵亦深受感应,许久许久之后,才满面祥和的叹道:“此种天籁之音,乃自碧紫三箫合奏的曲谱,如能三箫合璧同奏,数十里之内,天音遍布,戾气尽涤,此老不知是谁,真是惠我良多。”
铁心秀士曾弼,接口说出自己的感觉道:“此曲委实非凡,仅由元弟低诵出来,愚兄便不禁为之心畅神怡,烦恼全消。”
沈元通又道:“小弟的碧玉洞箫原也有一首本命之曲,深具潜默化之功,并能鼓音伤敌,但和这‘天籁之音’相较起来,就微不足道了。”
铁心秀士曾弼大为向往,道:“愚足久闻白、碧、紫三箫各有一首本命乐曲,却不知更有这厥合奏之谱,元弟能为愚兄一道其源由出处否?”
沈元通微带愧色地道:“小弟虽为碧玉洞箫现下的主人,却也未曾听说过有此三箫合奏的曲谱,此中详情,唯有将来向那位赠书的老前辈请教了。”
铁心秀士曾弼点点头,忽又道:“此刻晓风徐拂,江流悠悠,你我竟夕奔波,元弟何不趁此良辰佳境,横管一曲,让愚兄一聆碧玉洞箫之妙音,以饱耳福?”
沈元通初得仙谱,心情舒畅,闻言不禁心动,立即取出碧玉洞箫,迎唇吹奏起来。
起初,声音不大,只觉宫、商、角、徵、羽、和变宫、变徵七首,入耳有说不出来的清幽,渐吹声音渐高,顿又使人有一种奋激昂扬的意气,随着那箫声油然升起。
几经回荡转折,又渐渐低了下来,呜呜之声,使得铁心秀士曾弼心神黯然,俊目不由自主的注满了忧伤之泪。
箫声如此时高时低,时乐时哀,时喜时怒,时爱时恶,不断的转变逻换,铁心秀士曾弼的感情,随之起伏幻化,历尽诸般意境,忘却了人我,也忘却了整个世界。
忽然,箫声越来越低,愈来愈微,像一条无形的线,无尽无极。
晨风中,一切又恢复了原有的沉寂,江水下游之涯露出半轮红日,万道霞光,照射在铁心秀士曾弼的脸上。
但他却仍是如痴如醉,悠然神往如故。
沈元通收起碧玉洞箫,微微一笑道:“大哥,大哥,小弟现丑完毕了!”
铁心秀士曾弼由沉醉中惊醒过来,只觉脑际耳边,犹似有余音缭绕。
他将头摇晃了一下,看了沈元通一眼,忘情地道:“元弟……”
他元弟一字刚刚出口,沈元通忽然将手一摇,轻声道:“有人来了!”
铁心秀士曾弼敞声豪笑道:“元弟,如此仙乐妙音,如果有人听了而不闻声赶来,必是白痴无疑!”
铁心秀士曾弼话方说完,只觉白影一闪,前方丈外,已悄没声息地站着一人。
沈元通和铁心秀士曾弼抬头看去,心头齐是一怔。
只见来人一身白,竟是一位年约三十左右的绝色女子。
她脸似春花,柳眉微微上扬.脸上的神色冷如冰雪,显然不是一个随和之人。
这时她也正打量着沈元通和露铁秀士曾弼二人,也许由于他们二人一个长得文秀潇洒,一个长得英气逼人,看来都极可喜,她那寒冰似的脸色,始微微有了一点暖意,但出语磨却仍是目中无人地道:“碧玉洞箫的一点小小玩意见有什么了不得的,我是要来看看弄箫之人,可是沈家娃儿。”
她说着秀目落向沈元通的碧玉洞箫上,意思显然是要沈元通报名答话。
铁心秀士曾弼见她一派无礼的气势,大起反感,剑眉连剔,就要发作,却被沈元通用眼色止住。
就这稍稍一缓之间,那白衣女子已自不耐,鼻中轻“哼”一声,道:“你们不会说话?”
沈元通忙道:“晚辈姓沈,不知老前辈要找的可是晚辈?”
那白衣女子更仔细的看了沈元通几眼,又问道:“沈一之便是你租父?”从她如此口气中,可见她不是身份很高,便是有点自大之狂。
沈元通眉头一皱,仍是平和的道:“家祖已归隐了三十余年,不知老前辈如何……”
那白衣女子冷冷的道:“三十年算得了什么!老身未履尘凡已五十年了!”忽然语气一变,含有谴责意味地道:“我那英儿现在何处?”
沈元通闻问恍然大悟,闪电般忖道:“原来是她,玉箫仙子老前辈,五十年的归隐生活,竟仍未改变了她的古怪脾气。”他想着连忙躬身施礼道:“不知是卓老前辈驾到,请恕失礼之罪。”
玉箫仙子翠袖一挥,道:“罢了,我那英见不是和你在一起的么?”敢情她觉得沈元通看来顺眼,心中兴起情天补天补恨的念头,是以说话的语气已缓绥了许多。
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.