language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 1,474 | 2.875 | 3 | [] | no_license | package tasktwo.control;
import tasktwo.model.BookShelf;
import tasktwo.view.BookView;
import java.util.Arrays;
import static tasktwo.view.BookView.view;
public class BookController {
public static void start() {
int i = BookView.getSize();
BookShelf bookShelf = new BookShelf(i);
view(bookShelf.getBooks());
while (true) {
BookView.view("Choose your variant\n");
switch (BookView.MenuView.getMenu()) {
case (1): {
view(bookShelf.getBooks());
break;
}
case (2): {
view(bookShelf.booksAuthor(BookView.getAuthor()));
break;
}
case (3): {
view(bookShelf.booksPublication(BookView.getPublication()));
break;
}
case (4): {
view(bookShelf.booksPublishingYear(BookView.getYear()));
break;
}
case (5): {
Arrays.sort(bookShelf.getBooks());
view(bookShelf.getBooks());
break;
}
case (6): {
return;
}
default: {
BookView.view("Sorry , you entered something wrong");
break;
}
}
}
}
}
|
Rust | UTF-8 | 1,304 | 2.90625 | 3 | [] | no_license | use crate::core::{Store, StoreLock};
use crate::utils::env::*;
use crate::utils::time::{now_nano, NanoTime};
use std::thread;
use std::time::Duration;
/// 垃圾回收
fn gc(store: &mut Store, now: NanoTime) {
let before_size = store.total_value_size();
let before_count = store.item_count();
let removed_count = {
let cnt = store.clean(now);
store.shrink();
cnt
};
let stw_time = now_nano() - now; // 垃圾回收所花费的时间
let after_size = store.total_value_size();
let after_count = store.item_count();
info!(
"CLEAN stw: {} ns, removed: {}, store_size: {} -> {}, item_count: {} -> {}",
stw_time, removed_count, before_size, after_size, before_count, after_count
);
}
// 开新线程,不断进行GC
pub fn gc_loop(store_lock: StoreLock) {
// 强制获得store_lock 的所有权
thread::spawn(move || loop {
// write store
// assert: store_lock.write never returns Err or paincs
let mut store = store_lock.write().unwrap();
let now = now_nano();
if store.needs_clean(now) {
gc(&mut *store, now);
}
// 释放写者锁
drop(store);
// 线程睡眠
thread::sleep(Duration::from_millis(*CLEAN_DURATION));
});
}
|
C++ | UTF-8 | 7,090 | 3 | 3 | [
"BSL-1.0"
] | permissive | //
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/url
//
#ifndef BOOST_URL_GRAMMAR_STRING_TOKEN_HPP
#define BOOST_URL_GRAMMAR_STRING_TOKEN_HPP
#include <boost/url/detail/config.hpp>
#include <boost/url/string_view.hpp>
#include <boost/url/detail/except.hpp>
#include <boost/type_traits.hpp>
#include <memory>
#include <string>
namespace boost {
namespace urls {
namespace string_token {
/** Base class for string tokens, and algorithm parameters
This abstract interface provides a means
for an algorithm to generically obtain a
modifiable, contiguous character buffer
of prescribed size. As the author of an
algorithm simply declare an rvalue
reference as a parameter type.
<br>
Instances of this type are intended only
to be used once and then destroyed.
@par Example
The declared function accepts any
temporary instance of `arg` to be
used for writing:
@code
void algorithm( string_token::arg&& dest );
@endcode
To implement the interface for your type
or use-case, derive from the class and
implement the prepare function.
*/
struct arg
{
/** Return a modifiable character buffer
This function attempts to obtain a
character buffer with space for at
least `n` characters. Upon success,
a pointer to the beginning of the
buffer is returned. Ownership is not
transferred; the caller should not
attempt to free the storage. The
buffer shall remain valid until
`this` is destroyed.
@note
This function may only be called once.
After invoking the function, the only
valid operation is destruction.
*/
virtual char* prepare(std::size_t n) = 0;
// prevent misuse
virtual ~arg() = default;
arg() = default;
arg(arg&&) = default;
arg(arg const&) = delete;
arg& operator=(arg&&) = delete;
arg& operator=(arg const&) = delete;
};
//------------------------------------------------
/** Metafunction returning true if T is a StringToken
*/
#ifdef BOOST_URL_DOCS
template<class T>
using is_token = __see_below__;
#else
template<class T, class = void>
struct is_token : std::false_type {};
template<class T>
struct is_token<T, boost::void_t<
decltype(std::declval<T&>().prepare(
std::declval<std::size_t>())),
decltype(std::declval<T&>().result())
> > : std::integral_constant<bool,
std::is_convertible<decltype(
std::declval<T&>().result()),
typename T::result_type>::value &&
std::is_same<decltype(
std::declval<T&>().prepare(0)),
char*>::value &&
std::is_base_of<arg, T>::value &&
std::is_convertible<T const volatile*,
arg const volatile*>::value
>
{
};
#endif
//------------------------------------------------
/** A token for returning a plain string
*/
#ifdef BOOST_URL_DOCS
using return_string = __implementation_defined__;
#else
struct return_string
: arg
{
using result_type = std::string;
char*
prepare(std::size_t n) override
{
s_.resize(n);
return &s_[0];
}
result_type
result() noexcept
{
return std::move(s_);
}
private:
result_type s_;
};
#endif
//------------------------------------------------
/** A token for appending to a plain string
*/
#ifdef BOOST_URL_DOCS
template<
class Allocator =
std::allocator<char>>
__implementation_defined__
append_to(
std::basic_string<
char,
std::char_traits<char>,
Allocator>& s);
#else
template<class Alloc>
struct append_to_t
: arg
{
using string_type = std::basic_string<
char, std::char_traits<char>,
Alloc>;
using result_type = string_type&;
explicit
append_to_t(
string_type& s) noexcept
: s_(s)
{
}
char*
prepare(std::size_t n) override
{
std::size_t n0 = s_.size();
if(n > s_.max_size() - n0)
urls::detail::throw_length_error();
s_.resize(n0 + n);
return &s_[n0];
}
result_type
result() noexcept
{
return s_;
}
private:
string_type& s_;
};
template<
class Alloc =
std::allocator<char>>
append_to_t<Alloc>
append_to(
std::basic_string<
char,
std::char_traits<char>,
Alloc>& s)
{
return append_to_t<Alloc>(s);
}
#endif
//------------------------------------------------
/** A token for assigning to a plain string
*/
#ifdef BOOST_URL_DOCS
template<
class Allocator =
std::allocator<char>>
__implementation_defined__
assign_to(
std::basic_string<
char,
std::char_traits<char>,
Allocator>& s);
#else
template<class Alloc>
struct assign_to_t
: arg
{
using string_type = std::basic_string<
char, std::char_traits<char>,
Alloc>;
using result_type = string_type&;
explicit
assign_to_t(
string_type& s) noexcept
: s_(s)
{
}
char*
prepare(std::size_t n) override
{
s_.resize(n);
return &s_[0];
}
result_type
result() noexcept
{
return s_;
}
private:
string_type& s_;
};
template<
class Alloc =
std::allocator<char>>
assign_to_t<Alloc>
assign_to(
std::basic_string<
char,
std::char_traits<char>,
Alloc>& s)
{
return assign_to_t<Alloc>(s);
}
#endif
//------------------------------------------------
/** A token for producing a durable string_view from a temporary string
*/
#ifdef BOOST_URL_DOCS
template<
class Allocator =
std::allocator<char>>
__implementation_defined__
preserve_size(
std::basic_string<
char,
std::char_traits<char>,
Allocator>& s);
#else
template<class Alloc>
struct preserve_size_t
: arg
{
using result_type = string_view;
using string_type = std::basic_string<
char, std::char_traits<char>,
Alloc>;
explicit
preserve_size_t(
string_type& s) noexcept
: s_(s)
{
}
char*
prepare(std::size_t n) override
{
n_ = n;
// preserve size() to
// avoid value-init
if(s_.size() < n)
s_.resize(n);
return &s_[0];
}
result_type
result() noexcept
{
return string_view(
s_.data(), n_);
}
private:
string_type& s_;
std::size_t n_ = 0;
};
template<
class Alloc =
std::allocator<char>>
preserve_size_t<Alloc>
preserve_size(
std::basic_string<
char,
std::char_traits<char>,
Alloc>& s)
{
return preserve_size_t<Alloc>(s);
}
#endif
} // string_token
namespace grammar {
namespace string_token = ::boost::urls::string_token;
} // grammar
} // urls
} // boost
#endif
|
C# | UTF-8 | 2,470 | 3.8125 | 4 | [] | no_license | using System;
using System.Linq;
namespace MaximalSum
{
public class MaximalSum
{
public static void Main()
{
int[] dimensions = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int rows = dimensions[0];
int cols = dimensions[1];
int[,] matrix = new int[rows, cols];
for (int row = 0; row < rows; row++)
{
int[] colsValues = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
for (int col = 0; col < colsValues.Length; col++)
{
matrix[row, col] = colsValues[col];
}
}
// find the biggest sum of elements in 3x3 matrix
int biggestSum = int.MinValue;
int biggestSumRowIndex = 0;
int biggestSumColIndex = 0;
for (int i = 0; i < matrix.GetLength(0) - 2; i++)
{
for (int j = 0; j < matrix.GetLength(1) - 2; j++)
{
int currentSum = matrix[i, j] + matrix[i, j + 1] + matrix[i, j + 2] +
matrix[i + 1, j] + matrix[i + 1, j + 1] + matrix[i + 1, j + 2] +
matrix[i + 2, j] + matrix[i + 2, j + 1] + matrix[i + 2, j + 2];
if (currentSum > biggestSum)
{
biggestSum = currentSum;
biggestSumRowIndex = i;
biggestSumColIndex = j;
}
}
}
// Result
Console.WriteLine($"Sum = {biggestSum}");
Console.WriteLine($"{matrix[biggestSumRowIndex, biggestSumColIndex]} {matrix[biggestSumRowIndex, biggestSumColIndex + 1]} {matrix[biggestSumRowIndex, biggestSumColIndex + 2]}");
Console.WriteLine($"{matrix[biggestSumRowIndex + 1, biggestSumColIndex]} {matrix[biggestSumRowIndex + 1, biggestSumColIndex + 1]} {matrix[biggestSumRowIndex + 1, biggestSumColIndex + 2]}");
Console.WriteLine($"{matrix[biggestSumRowIndex + 2, biggestSumColIndex]} {matrix[biggestSumRowIndex + 2, biggestSumColIndex + 1]} {matrix[biggestSumRowIndex + 2, biggestSumColIndex + 2]}");
}
}
} |
C | UTF-8 | 206 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int main() {
FILE *file;
char *str = "Hello";
file = fopen("my_file.txt", "a");
fwrite(&str, 1, sizeof(str), file);
fclose(file);
return 0;
}
|
Markdown | UTF-8 | 2,866 | 3.125 | 3 | [] | no_license | # Fold
В этой задаче вам предстоит реализовать функцию `Fold` --- одну из основных функций высшего порядка, выполняющую
свертку последовательности. Для заданного начального значения `init` и
некоторой бинарной функции `f` можно определить _левостороннюю свертку_ последовательности $`a_1, a_2, ..., a_n`$ как
```math
foldl := f(... f(f(init, a_1), a_2), a_n)
```
Аналогично, _правосторонняя свертка_ определяется как
```math
foldr := f(a_1, f(a_2, ... f(a_n, init)))
```
В данной задаче $`f`$ ассоциативна, поэтому обе свертки эквивалентны. Помимо самой функции `Fold` реализуйте несколько функторов,
которые можно передать данной функции:
* `Sum`, с помощью которого можно суммировать последовательность целых чисел.
* `Prod`, с помощью которого можно считать произведение.
* `Concat`, с помощью которого можно слить последовательность векторов в один вектор.
* `Length`, с помощью которого можно посчитать длину последовательности. Конструктор этого класса принимает указатель на `int`, в
котором должна лежать искомая длина после вызова `Fold`.
Примеры можно найти в тестах.
### Примечания
* _Функтором_ в С++ называется класс, объекты которого могут вести себя как функции, т.е. класс, в котором перегружен оператор
функционального вызова `()`. Поскольку функция `Fold` шаблонная, `func` необязательно должен быть функцией --- в данном случае это
может быть любой объект `f`, для которого возможно написать `f(a, b)`. Достигнуть этого можно как раз перегрузив упомянутый оператор.
При этом, в отличие от простых функций, в функторе в членах класса можно хранить некоторое состояние, сохраняемое между вызовами.
* В этой задаче запрещено использование функций из `<algorithm>`.
|
JavaScript | UTF-8 | 14,198 | 2.546875 | 3 | [] | no_license | var assert = require("assert");
var _ = require("underscore");
var net = require('net');
var melted_node = require('../melted-node');
var mlt = new melted_node('localhost', 5250);
// SILENCE LOG OUTPUT
/*var util = require('util');
var fs = require('fs');
var log = fs.createWriteStream('/home/jmrunge/stdout.log');
console.log = console.info = function(t) {
var out;
if (t && ~t.indexOf('%')) {
out = util.format.apply(util, arguments);
process.stdout.write(out + '\n');
return;
} else {
out = Array.prototype.join.call(arguments, ' ');
}
out && log.write(out + '\n');
};*/
// END SILENCE LOG OUTPUT
describe('connects', function(){
before(function(done) {
var result = mlt.connect();
result.then(function() {
done();
}, function(err) {
console.error("Error: " + err);
});
});
describe('#connected', function(){
it('--should return true', function(){
assert.equal (mlt.connected, true);
});
});
describe('#no pending messages', function(){
it('--should return 0', function(){
assert.equal (mlt.pending.length, 0);
});
});
describe('#no errors', function(){
it('--should return 0', function(){
assert.equal (mlt.errors.length, 0);
});
});
});
describe('commands', function(){
describe('#bad and good commands', function(){
it('--should fail with unknown commands', function(done){
mlt.sendCommand("no_such_command in my town").then(
function(val){
return done(new Error(val));
}, function(){ done(); });
});
it('--"load" should pass', function(done) {
mlt.sendCommand("load u0 ./test/videos/SMPTE_Color_Bars_01.mp4").then(function(){done();}).done();
});
it('-- "play" should pass (after "load")', function(done) {
mlt.sendCommand("play u0").then(function(){ done() }).done();
});
it('-- "append" shuold pass', function(done) {
mlt.sendCommand("apnd u0 ./test/videos/SMPTE_Color_Bars_02.mp4").then(function() { done() }).done();
});
});
});
describe('queue', function() {
describe('#add commands after queue processed', function(){
before(function(done) {
mlt.sendCommand("pause u0");
mlt.sendCommand("play u0");
setTimeout(function() {
done();
}, 1000);
});
it('--should return 1 because of previous test', function(){
assert.equal (mlt.errors.length, 1);
});
});
});
describe('promise handlers', function() {
describe('#execute handler function on success and on error', function() {
var errorReceived = false;
var responseReceived = false;
before(function(done) {
mlt.sendCommand("hohoho").then(undefined, callback);
function callback(error) {
console.error("TEST: Error: " + error);
errorReceived = true;
done();
};
});
before(function(done) {
mlt.sendCommand("list u0").then(callback);
function callback(response) {
console.log("TEST: Response: " + response);
responseReceived = true;
done();
};
});
it('--incremented error count', function(){
assert.equal (mlt.errors.length, 2);
});
it('--received error', function(){
assert.equal (errorReceived, true);
});
it('--received response', function(){
assert.equal (responseReceived, true);
});
});
});
describe('promised command', function() {
describe('#receive promised object', function() {
var error1Received = false;
var response1Received = false;
var error2Received = false;
var response2Received = false;
before(function(done) {
var result = mlt.sendCommand("jijijiji");
result.then(function(response) {
console.log("TEST: Response: " + response);
response1Received = true;
done();
}, function(error) {
console.error("TEST: Error: " + error);
error1Received = true;
done();
});
});
before(function(done) {
var result = mlt.sendCommand("uls");
result.then(function(response) {
console.log("TEST: Response: " + response);
response2Received = true;
done();
}, function(error) {
console.error("TEST: Error: " + error);
error2Received = true;
done();
});
});
it('--incremented error count', function(){
assert.equal (mlt.errors.length, 3);
});
it('--received error for bad command', function(){
assert.equal (error1Received, true);
});
it('--received response for bad command', function(){
assert.equal (response1Received, false);
});
it('--received error for good command', function(){
assert.equal (error2Received, false);
});
it('--received response for good command', function(){
assert.equal (response2Received, true);
});
});
});
describe('xml', function() {
describe('#add xml file with filter', function(){
before(function(done) {
mlt.sendCommand("load u0 ./test/melted-test.xml");
mlt.sendCommand("play u0");
setTimeout(function() {
done();
}, 1000);
});
it('--should return 3 because of previous test', function(){
assert.equal(mlt.errors.length, 3);
});
});
});
describe('stress', function() {
this.timeout(0);
describe('#obtain status 100 times', function() {
before(function(done) {
var count = 0;
setInterval(function() {
if (count === 100) {
clearInterval(this);
done();
}
mlt.sendCommand("usta u0").then(function(response) {
console.log("USTA:" + response);
console.log("PASADA NRO: " + count);
}, function(error) {
console.error("USTA: " + error);
});
console.log("mando goto");
mlt.sendCommand("goto u0 " + count * 3).then(function(response) {
console.log("GOTO: " + response);
}, function(error) {
console.error("GOTO: " + error);
});
count++;
}, 50);
});
it('--should return 3 (no more errors!)', function(){
assert.equal(mlt.errors.length, 3);
});
after(function(done) {
mlt.sendCommand("stop u0").fin(function(result) {
done();
});
});
});
describe("# send 100 random commands", function() {
before(function(done) {
mlt.sendCommand("clear u0").then(function() {
done();
}, done);
// define String.startsWith
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
});
after(function(done) {
console.log("after");
mlt.sendCommand("stop u0");
mlt.sendCommand("clear u0").then(function() { done() }, done);
});
it("-- and make sure the responses are correct", function(done){
this.timeout(3000);
var commands = [
["stop u0", "200 OK"],
["play u0", "200 OK"],
["apnd u0 ./test/videos/SMPTE_Color_Bars_01.mp4", "200 OK"],
["apnd u0 ./test/videos/SMPTE_Color_Bars_02.mp4", "200 OK"],
["apnd u0 ./test/videos/SMPTE_Color_Bars_03.mp4", "200 OK"],
["usta u0", "202 OK"],
["unknown command", undefined, "400 Unknown command"],
["list u0", "201 OK"],
];
var count = 100;
var good = _.after(count, function() {
done();
});
var counter = 0;
_.range(count).forEach(function(i){
(function(com) {
mlt.sendCommand(com[0]).then(function(res) {
if(res.startsWith(com[1])) {
assert.equal(counter, i);
counter++;
good();
} else {
done(new Error(res));
};
}, function(err) {
if(com[2]) {
assert.equal(counter, i);
counter++;
good();
} else {
done(err);
}
}).fail(function(err){
done(err)
});
})(commands[_.random(commands.length-1)]);
});
});
});
});
describe('disconnect', function() {
this.timeout(0);
it('having commands in queue and disconnect shouldnt throw errors', function(done) {
assert.doesNotThrow(function() {
mlt.sendCommand("usta u0");
mlt.sendCommand("usta u0");
mlt.sendCommand("usta u0");
mlt.sendCommand("usta u0");
mlt.sendCommand("usta u0");
mlt.disconnect().then(function(result) {
console.log(result);
}).fail(function(error) {
console.log(error);
}).fin(done);
});
});
it('--disconnected', function() {
assert.equal(mlt.connected, false);
});
it("reconnecting shouldn't throw errors", function(done) {
mlt.sendCommand("usta u0");
mlt.connect().then(function() {
mlt.sendCommand("usta u0").then(function(){
done();
}, done);
});
});
});
describe("fake melted", function() {
var self = this;
describe("that accepts connection, but doesn't send 'ready'", function() {
before(function(done) {
self.mlt_mock = net.createServer(function(c) {
self.mlt_mock.clients.push(c);
});
self.mlt_mock.clients = [];
self.mlt_mock.listen(2222, function() { done() });
mlt = new melted_node('localhost', 2222);
});
after(function(done) {
mlt = undefined;
self.mlt_mock.close(function() {
done()
});
self.mlt_mock.clients.forEach(function(c) {
c.destroy();
});
});
it("-- connect should fail if the 100 VTR Ready line is never sent", function(done) {
mlt.connect().then(function() {
// fail
done(new Error("Connection returned as succeeded"));
}).fail(function() {
done();
}).done();
});
});
describe("that sends 'ready'", function() {
before(function(done) {
// just create a server that sends a melted "ready" message and then responds to nothing
self.mlt_mock = net.createServer(function(c) {
self.mlt_mock.clients.push(c);
c.write("100 VTR Ready\r\n");
});
self.mlt_mock.clients = [];
self.mlt_mock.listen(2222, function() { done() });
mlt = new melted_node('localhost', 2222);
});
after(function(done) {
self.mlt_mock.close(function() { done() });
self.mlt_mock.clients.forEach(function(c) {
c.destroy();
});
});
describe("--timeouts", function() {
this.timeout(3000);
beforeEach(function(done) {
mlt.connect().then(function() { done() }).done();
});
afterEach(function(done) {
mlt.disconnect().then(function() { done() }).done();
});
it("# should timeout after sending a command and waiting 2 seconds", function(done) {
mlt.on('response-timeout', function() {
mlt.removeAllListeners('response-timeout');
done();
});
mlt.sendCommand("USTA U0");
});
it("# when timed out, pending commands should fail", function(done) {
var r = mlt.sendCommand("USTA U0").then(function() {
done(new Error("Got a response, and should have timed out!"));
}).fail(function() {
done();
});
});
it("# waiting for two seconds without sending commands should NOT time out", function(done){
mlt.on('response-timeout', function() {
mlt.removeAllListeners('response-timeout');
done(new Error("melted-node sent a timeout event"));
});
setTimeout(function() {
mlt.removeAllListeners('response-timeout');
done();
}, 2400);
});
it("# should timeout even if I keep sending commands", function(done) {
var ival = setInterval(function() {
mlt.sendCommand("USTA U0");
}, 200);
mlt.on('response-timeout', function() {
mlt.removeAllListeners('response-timeout');
clearInterval(ival);
done();
});
});
});
});
});
|
Java | UTF-8 | 660 | 2.34375 | 2 | [] | no_license | package com.pps.pojo.status;
/*
* @Author Pupansheng
* @Description // 支付状态
* @Date 18:51 2020/1/11
* @Param
* @return
**/
public enum PayStatus {
未支付(0,"未支付"),已支付(1,"已支付");
private Integer code;
private String detail;
PayStatus(Integer code, String detail) {
this.code = code;
this.detail = detail;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
|
C | UTF-8 | 543 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
void swap(char a[] ,char i, char j)
{
char temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void SelectionSort(char a[],char n)
{
for (char i=n-1;i>=1;i--)
{
int albet = i;
for (int j = 0; j < i; j++)
{
if (a[j] >= a[albet])
{
albet = j;
swap(a,i, albet);
}
}
int main()
{
int i,j,names[10], albet;
int i= sizeof(names)/sizeof(names(0));
printf("Enter the number of names \n") ;
scanf("%d",&i) ;
for()
return 0;
}
|
C# | UTF-8 | 5,180 | 2.53125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Windows.Input;
using SQLiteUtils.Commands;
using System.Windows;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using SQLiteUtils.Model;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Threading;
namespace SQLiteUtils.ViewModel
{
public class MainViewModel : BaseViewModel
{
#region Consts
private const int ElapsedTimeRefreshRateMs = 1000;
#endregion
#region Private Fields
private DispatcherTimer _elapsedTimeUpdTimer;
#endregion
#region INotifyPropertyChanged Implementation
private TimeSpan _elapsedTime;
/// <summary>
/// Time elapsed during SQL processing.
/// </summary>
public TimeSpan ElapsedTime
{
get => _elapsedTime;
set => SetProperty(ref _elapsedTime, value);
}
private string _errorMessage = string.Empty;
/// <summary>
/// When an error occurs, the message is stored here.
/// </summary>
public string ErrorMessage
{
get => _errorMessage;
set => SetProperty(ref _errorMessage, value);
}
#endregion
#region Properties
public List<DbManagerBaseViewModel> ChildViewModels { get; set; }
public RawGeneratorManagerViewModel DbGeneratorViewModel { get; set; }
public QueryManagerViewModel QueryManagerViewModel { get; set; }
public SmartGeneratorManagerViewModel SmartGeneratorViewModel { get; set; }
public BaseViewModel SelectedViewModel { get; set; }
/// <summary>
/// List of available DBs
/// </summary>
public List<string> DatabaseList { get; set; }
private int _selectedDbIndex;
/// <summary>
/// Index of the selected DB
/// </summary>
public int SelectedDbIndex
{
get => _selectedDbIndex;
set
{
_selectedDbIndex = value;
// Update the DbName accordingly
DbName = GymAppSQLiteConfig.GetDbFullpath(DatabaseList?.Where((x, i) => i == _selectedDbIndex).First());
}
}
private string _dbName;
public string DbName
{
get => _dbName;
set
{
_dbName = value;
// Propagate to the childs
foreach (DbManagerBaseViewModel vm in ChildViewModels)
vm.DbName = _dbName;
}
}
#endregion
#region Ctors
public MainViewModel()
{
DbGeneratorViewModel = new RawGeneratorManagerViewModel(IsProcessingChanged, ErrorMessageReceived);
QueryManagerViewModel = new QueryManagerViewModel(IsProcessingChanged, ErrorMessageReceived);
SmartGeneratorViewModel = new SmartGeneratorManagerViewModel(IsProcessingChanged, ErrorMessageReceived);
ChildViewModels = new List<DbManagerBaseViewModel>()
{
SmartGeneratorViewModel, DbGeneratorViewModel, QueryManagerViewModel,
};
SelectedViewModel = ChildViewModels.First();
DatabaseList = GymAppSQLiteConfig.GetDatabaseList()?.Select(x => Regex.Replace(Path.GetFileName(x), ".db", "")).ToList();
try
{
SelectedDbIndex = DatabaseList.FindIndex(x => Path.GetFileName(x) == GymAppSQLiteConfig.DefaultDbName);
}
catch
{
SelectedDbIndex = 0;
}
_elapsedTimeUpdTimer = new DispatcherTimer()
{
Interval = new TimeSpan(0, 0, 0, 0, ElapsedTimeRefreshRateMs),
};
_elapsedTimeUpdTimer.Tick += (o, e) =>
{
ElapsedTime = ElapsedTime.Add(new TimeSpan(0, 0, 0, 0, ElapsedTimeRefreshRateMs));
};
}
#endregion
#region Public Methods
/// <summary>
/// Must be called by the childs when their processing state changes
/// </summary>
/// <param name="isProcessing"></param>
private void IsProcessingChanged(bool isProcessing)
{
// Update the timer
if (isProcessing)
{
ElapsedTime = new TimeSpan();
_elapsedTimeUpdTimer.Start();
}
else
_elapsedTimeUpdTimer.Stop();
}
/// <summary>
/// Must be called by the childs when they end in error
/// </summary>
/// <param name="error"></param>
private void ErrorMessageReceived(string error)
{
//Dispatcher.CurrentDispatcher.Invoke(() => ErrorMessage = error);
//// Display the error
ErrorMessage = error;
}
#endregion
}
}
|
C++ | UTF-8 | 815 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<conio.h>
#define max 25
using namespace std;
main()
{
int n,bt[max],tat[max],wt[max]; float avgtat=0,avgwt=0;
cout<<"Enter no. of processes ";
cin>>n;
cout<<endl;
cout<<"Enter Burst time or Execution time of processes ";
for(int i=0;i<n;i++) cin>>bt[i];
cout<<endl;
sort(bt,bt+n);
tat[0]=bt[0];
for(int i=1;i<n;i++)
tat[i]=tat[i-1]+bt[i];
for(int i=0;i<n;i++)
wt[i]=tat[i]-bt[i];
for(int i=0;i<n;i++)
avgtat+=tat[i];
avgtat=avgtat/n;
for(int i=0;i<n;i++)
avgwt+=wt[i];
avgwt=avgwt/n;
cout<<"TAT is WT is"<<endl;
for(int i=0;i<n;i++) cout<<tat[i]<<" "<<wt[i]<<" "<<endl;
cout<<endl;
cout<<"Average TAT is ="<<avgtat<<endl;
cout<<"Average WT is ="<<avgwt<<endl;
}
|
Shell | UTF-8 | 540 | 3.40625 | 3 | [] | no_license | #!/usr/bin/env bash
# bin/compile <build-dir> <cache-dir>
BUILD_DIR=$1
CACHE_DIR=$2
LP_DIR=`cd $(dirname $0); cd ..; pwd`
function indent() {
c='s/^/ /'
case $(uname) in
Darwin) sed -l "$c";;
*) sed -u "$c";;
esac
}
# Add node executable to path
export PATH=$CACHE_DIR/node/bin:$PATH
echo "----- Publish CircuitHub static assets"
cd $BUILD_DIR
ls run_cake.js
$CACHE_DIR/node/bin/node $BUILD_DIR/run_cake.js publish.assets
node_modules/.bin/grunt heroku:$NODE_ENV --force
cd ..
echo "Assets published" | indent
|
Java | UTF-8 | 454 | 2.015625 | 2 | [] | no_license | package com.test.wechat.message.resp;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class MusicMessage extends BaseMessage {
private Music Music;
public Music getMusic() {
return Music;
}
public void setMusic(Music music) {
Music = music;
}
}
|
Java | UTF-8 | 2,051 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | package hydra_framework.hydra.core;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.net.SocketFactory;
public class HydraConnector implements Runnable {
volatile boolean running = true;
HydraController hydraController;
Socket socket;
DataInputStream serverInputStream;
DataOutputStream serverOutputStream;
public HydraConnector(HydraController hydraController) {
this.hydraController = hydraController;
}
@Override
public void run() {
String host = hydraController.ZolaServerHost;
int port = hydraController.ZolaServerPort;
try {
this.socket = SocketFactory.getDefault().createSocket(host, port);
this.serverInputStream = new DataInputStream(this.socket.getInputStream());
this.serverOutputStream = new DataOutputStream(this.socket.getOutputStream());
System.out.println("loop start");
String line;
while (running && (line = this.serverInputStream.readUTF()) != null) {
// System.out.println(line);
this.hydraController.updateRecv(line);
// this.hydraController.systemLog(line);
}
System.out.println("loop end");
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.err.println("Connection fail...");
} finally {
try {
this.socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Job closed");
this.hydraController.connectionClose();
}
public void shutDown() {
this.running = false;
if (this.socket != null) {
try {
this.socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendMessage(String messageText) {
if (socket != null && !socket.isClosed()) {
try {
this.serverOutputStream.writeUTF(messageText);
this.serverOutputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
Ruby | UTF-8 | 89 | 3.265625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def say_hello(name = "Ruby Programmer")
puts "Hello" name
end# Build your say_hello method here
|
Markdown | UTF-8 | 2,901 | 3.25 | 3 | [] | no_license | # Twitch Bot
This is a twitch bot I am making to moderate my twitch chat using [Node.js][nodejs] and [tmi.js][tmijs]
## Set Up
To run this node application you're gonna want to have Node.js installed as well as npm
I'm running this on a raspberry pi so I have a couple of scripts that can get your bot running and automatically fetching updates from your repository.
[add2cron.sh](add2cron.sh) will add [piScript.sh](piScript.sh) to your cron jobs so that every Monday Wednesday Friday the piScript will execute, killing the twitch bot and updating it. To do this the project has to be set up in such a way that running
```bash
git pull
```
will pull from the repository. When it pulls from the repository **it will reset the default database.** This means anything "Learned" or "Unlearned" will be forgotten. For a database that will not be reset, create a `database.json` file. I recommend copying and renaming the `data_base.json` file.
To log in to Twitch, the bot needs a username and an oauth token. **Do not make these public by hardcoding them in.** To allow the app access to your username and oauth token, simply create a `.env` file of the format
```bash
USERNAME=your_bot_username
PASSWORD=oauth:your_oauth_token
```
You will also likely have to run
```bash
npm install --save
```
to make sure all necessary packages are installed before running the app.
## Running
To start the app run either
```bash
npm start
```
or
```bash
./piScript.sh
```
If you plan on running the cron job I recommend the latter.
### Talking to the bot
The bot currently knows 7 commands
* echo
* the bot will echo what is was sent
* remember
* the bot will remember something while it is running. This is not saved so if the bot is reset it will forget.
* to have the bot tell you what it remembers say "What is [The first word of what you wanted remembered]"
* forget
* forget will erase something from temporary memory
* to use it say "forget [The first word of what was remembered]"
* learn
* learn will add things to the permanent database
* "learn greeting howdy" will catalog howdy as a greeting
* some lists require admin access to edit
* unlearn
* unlearn will remove things from the permanent database
* "unlearn greeting howdy" will remove howdy from the list of greetings
* some lists require admin access to edit
* what
* what is used to regurgitate information recorded using remember
* for "remember record is 32 m/s" saying "what is record" will respond "record is 32 m/s"
* signoff
* the bot will terminate
* requires admin access
### Killing
To terminate the bot safely
* The broadcaster can say "signoff" in the chat
* Send the process a SIGTERM signal (this can be done using the top command)
* Press <kbd>ctrl</kbd>+<kbd>C</kbd> in the terminal where it is running
[nodejs]: https://nodejs.org/
[tmijs]: https://tmijs.com/ |
PHP | UTF-8 | 4,653 | 2.875 | 3 | [] | no_license | <?php
abstract class Custom_MetaBox_Item_Default
{
/**
* meta box id, unique per meta box
*
* @var string
*/
protected $id = '';
/**
* Meta box title
*
* @var string
*/
protected $title = '';
/**
* Taxonomy name, accept categories, post_tag and custom taxonomies
*
* @var array
*/
protected $pages = array();
/**
* Where the meta box appear: normal (default), advanced, side; optional
*
* @var string
*/
protected $context = 'normal';
/**
* List of meta fields (can be added by field arrays)
*
* @var array
*/
protected $fields = array();
/**
* Use local or hosted images (meta box images for add/remove)
*
* @var boolean
*/
protected $local_images = false;
/**
* Change path if used with theme set to true, false for a plugin or anything else for a custom path(default false).
*
* @var boolean
*/
protected $use_with_theme = null;
/**
* Object
*
* @var Custom_MetaBox_Taxonomy
*/
protected $metaTaxObj;
function __construct( $taxonomy ) {
$this->setPageTaxonomy( $taxonomy );
}
/**
* Set taxonomy<br/>
*
* @param string $taxonomy Taxonomy name, accept categories, post_tag and custom taxonomies
*/
private function setPageTaxonomy( $taxonomy ) {
$this->pages[] = $taxonomy;
}
/**
* Pages which is available metabox
*
* @return array
*/
public function getPageTaxonomy() {
return $this->pages;
}
/**
* Set unique meta box id
*
* @param string $id
*/
protected function setId( $id ) {
$this->id = $id;
return $this;
}
/**
* Get unique meta box id
*
* @return string
*/
public function getId() {
return $this->id;
}
/**
* Set Metabox title
*
* @param string $title
*/
protected function setTitle( $title ) {
$this->title = $title;
return $this;
}
/**
* Get Metabox title
*
* @return string
*/
public function getTitlte() {
return $this->title;
}
/**
* Set where the meta box appear: normal (default), advanced, side;
*
* @param string $context
*/
protected function setContext( $context ) {
if ( in_array( $context, array( 'normal', 'advanced', 'side' ) ) ) {
$this->context = $context;
} else {
$this->context = 'normal';
}
return $this;
}
/**
* Get where the meta box appear
*
* @return string
*/
public function getContext() {
return $this->context;
}
/**
*
*/
public function getFields() {
return $this->fields;
}
/**
* Set use local or hosted images
*
* @param boolean $local_images
*/
protected function setLocalImages( $local_images ) {
$this->local_images = (boolean) $local_images;
return $this;
}
/**
*
*/
public function getLocalImages() {
return (boolean) $this->local_images;
}
/**
* Change path if used with theme set to true, false for a plugin or anything else for a custom path(default false).
*
* @param mixed $use
*/
protected function setUseWithTheme( $use ) {
$this->use_with_theme = $use;
return $this;
}
/**
*
* @return boolean
*/
public function getUseWithTheme() {
if ( is_null( $this->use_with_theme ) ) {
return get_template_directory_uri();
}
return $this->use_with_theme;
}
protected function getConfig() {
return array(
'id' => $this->getId(),
'title' => $this->getTitlte(),
'pages' => $this->getPageTaxonomy(),
'context' => $this->getContext(),
'fields' => $this->getFields(),
'local_images' => $this->getLocalImages(),
'use_with_theme' => $this->getUseWithTheme(),
);
}
/**
* create instanse of Custom_MetaBox_Taxonomy and set it.
*/
private function setMetaTaxInstance() {
$this->metaTaxObj = new Custom_MetaBox_Taxonomy( $this->getConfig() );
}
/**
* Get saved instanse of Custom_MetaBox_Taxonomy
*
* @return Custom_MetaBox_Taxonomy
*/
public function getMetaTaxInstance() {
return $this->metaTaxObj;
}
/**
* Add custom elements
*/
protected function addFields() {
$this->setMetaTaxInstance();
}
/**
* get Sitebar list
*
* @return array
*/
protected function getSidebars() {
if ( $sidebars = Sidebar_TIGenerator::get_sidebars() ) {
return $sidebars;
}
return array();
}
/**
* Finish Declaration of Meta Box and add it.
*/
public function run() {
$this->getMetaTaxInstance()->Finish();
}
protected function getCategoriesList( $taxonomy ) {
$list = array();
if ( taxonomy_exists( $taxonomy ) ) {
if ( $terms = get_terms( $taxonomy ) ) {
if ( is_array( $terms ) ) {
foreach ( $terms as $term ) {
$list[ $term->slug ] = $term->name;
}
}
}
}
return $list;
}
}
?>
|
SQL | UTF-8 | 1,793 | 3.75 | 4 | [] | no_license |
CREATE TABLE `tbl_ads` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`create_time` datetime DEFAULT NULL,
`type` INT(11) NOT NULL COMMENT '1是图片链接,2是文字链接,3是代码',
`name` VARCHAR(100) COMMENT '广告名称',
`start_time` datetime ,
`end_time` datetime ,
`content` VARCHAR(1000) NOT NULL COMMENT '内容,如果是图片链接,该内容为图片地址,如果是文字链接,改内容是文字描述信息,如果是代码,改内容是广告代码',
`link` VARCHAR(255) COMMENT '链接,图片链接和文字链接类型时才有效',
`status` INT(1) DEFAULT '0' COMMENT '状态,0禁用,1启用',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `tbl_group_topic_comment` ADD COLUMN `comment_id` INT;
CREATE TABLE `tbl_link` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`create_time` datetime DEFAULT NULL,
`name` VARCHAR(100) COMMENT '网站名称',
`url` VARCHAR(255) COMMENT '网址',
`sort` INT(11) NOT NULL DEFAULT '0' COMMENT '排序,越大越靠前',
`recomment` INT(11) NOT NULL DEFAULT '0' COMMENT '推荐,0不推荐,1推荐',
`status` INT(1) DEFAULT '0' COMMENT '状态,0禁用,1启用',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `tbl_picture` ADD COLUMN `member_id` INT;
ALTER TABLE `tbl_picture` ADD COLUMN `description` text;
ALTER TABLE `tbl_message` ADD COLUMN `app_tag` INT;
ALTER TABLE `tbl_message` ADD COLUMN `type` INT;
ALTER TABLE `tbl_message` ADD COLUMN `relate_key_id` INT;
ALTER TABLE `tbl_message` ADD COLUMN `member_id` INT;
ALTER TABLE `tbl_message` ADD CONSTRAINT `fk_message_member` FOREIGN KEY (`member_id`) REFERENCES `tbl_member` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `tbl_message` ADD COLUMN `description` VARCHAR(500);
|
Java | UTF-8 | 5,590 | 2.984375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sfs;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import org.naturalcli.Command;
import org.naturalcli.ExecutionException;
import org.naturalcli.ICommandExecutor;
import org.naturalcli.InvalidSyntaxException;
import org.naturalcli.NaturalCLI;
import org.naturalcli.ParseResult;
import sfs.encounters.Encounters;
import sfs.entities.Player;
import sfs.items.Item;
/**
*
* @author Max
*/
public class Game {
private Set<Command> cs = new HashSet<Command>();
private Player player;
public Game(Player player)
{
this.player=player;
Command goCommand, inspectCommand, pickUpCommand, inventoryCommand, weapons, usables;
try
{
/*initialize Commands with help messages and functionality and add them to the set of commands*/
goCommand=new Command("go <direction:string>", "command to go to tile located in direction (has to be all caps) NORTH, SOUTH, EAST, WEST",
new ICommandExecutor ()
{
// the code to be executed when command is entered
public void execute(ParseResult pr )
{
// retrieve the parameter of the "go" command
String result =(String) pr.getParameterValue(0);
//enum to buffer direction
Direction mydir;
try
{
//try to convert string to the corresponding enumeration value
mydir=Direction.valueOf(result);
}
catch (IllegalArgumentException e)
{
// tell the user the argument was faulty
System.err.println("parameter incorrect. please use one of the following: NORTH, SOUTH, EAST, WEST");
return;
}
// if changing the room was successfull, tell the user
if (player.changeRoom(mydir))
System.out.println("going " + result);
}
});
inspectCommand=new Command("inspect", "command to inspect Tile the player is on",
new ICommandExecutor ()
{
public void execute(ParseResult pr)
{
//creation of buffer Tile variable which saves the details of current tile and then uses the printRoomInfo command to display room info
Tile myTile;
myTile=player.getLocation();
myTile.printRoomInfo();
}
});
pickUpCommand = new Command("pickup", "command to pick up the first item from the tile the player is standing at.",
r -> {
if( player.pickUpItem() )
{
/* the just picked up item. Short naming due to more readable next line. */
Item i = player.getLastItem();
System.out.println( "Successfully picked up " + i.getName() + "!\n" + i.getDescription() );
}
else
{
System.err.println( "There is no more item on this tile\n" );
}
} );
inventoryCommand = new Command("inventory", "commnad to look at the items in your inventory",
r -> player.printInventoryItems()
);
weapons = new Command( "weapons", "shows all weapons in your inventory",
r -> player.printWeaponsInInventory()
);
usables = new Command( "usables", "shows all useables in your inventory",
r -> player.printUsablesInInventory()
);
// add the command goCommand to the total list of commands
Collections.addAll( cs, goCommand, inspectCommand, pickUpCommand, inventoryCommand, weapons, usables);
}
catch (InvalidSyntaxException e)
{
e.printStackTrace();
}
}
//starts the game
public void start()
{
// creates the executor and scanner to take input from command line an interpret it
NaturalCLI natcli =new NaturalCLI(cs);
Scanner scanner =new Scanner(System.in);
while( player.getHealth() > 0 )
{
// retrieve next argument entered by user
String arg= scanner.nextLine();
try
{
/*parse the argument and execute the correct code if defined in a Command*/
natcli.execute(arg);
}
catch (ExecutionException e)
{
System.err.println("command not defined");
}
/* if the player has pending encounters we process them yet. */
if( Encounters.getNumberOfPendingEncounters() > 0 )
for( int i = 0; i < Encounters.getNumberOfPendingEncounters(); i++ )
Encounters.popFirstEncounter().start();
}
}
}
|
C++ | UTF-8 | 2,195 | 2.640625 | 3 | [] | no_license | #include "messageparser.h"
#include <QDebug>
MessageParser::MessageParser(const QString &id, MessageParserObserver &observer)
: m_observer(observer), m_id(id), m_parseStarted(false)
{
m_xmlReader.reset(new QXmlSimpleReader());
m_xmlSource.reset(new QXmlInputSource());
m_xmlReader->setContentHandler(this);
m_xmlReader->setErrorHandler(this);
}
MessageParser::~MessageParser()
{
}
void MessageParser::addData(const QByteArray &data)
{
if (!m_parseStarted)
{
QByteArray parseData = QByteArray("<stream>") + data; // stream means start
m_xmlSource->setData(parseData);
m_xmlReader->parse(m_xmlSource.data(), true);
m_parseStarted = true;
}
else
{
m_xmlSource->setData(data);
m_xmlReader->parseContinue();
}
}
bool MessageParser::startElement(const QString & /*namespaceURI*/,
const QString & /*localName*/,
const QString &qName,
const QXmlAttributes &attributes)
{
if (qName == "stream")
{
qDebug() << "stream started";
}
else if (qName == "message")
{
m_currentType = attributes.value("type");
m_currentId = attributes.value("id");
m_currentText.clear();
}
else
{
m_errorStr = QString("error message format from %1: %2").arg(m_id).arg(qName);
m_observer.onError(m_id, m_errorStr);
return false;
}
return true;
}
bool MessageParser::endElement(const QString & /*namespaceURI*/,
const QString & /*localName*/,
const QString &qName)
{
if (qName == "stream")
{
qDebug() << "stream finished";
}
else if (qName == "message")
{
m_observer.onMessage(m_id, m_currentId, m_currentType, m_currentText);
}
else
{
m_errorStr = QString("error message format from %1: %2").arg(m_id).arg(qName);
m_observer.onError(m_id, m_errorStr);
return false;
}
return true;
}
bool MessageParser::characters(const QString &str)
{
m_currentText += str;
return true;
}
bool MessageParser::fatalError(const QXmlParseException &exception)
{
m_errorStr = exception.message();
m_observer.onError(m_id, m_errorStr);
return false;
}
QString MessageParser::errorString() const
{
return m_errorStr;
}
|
PHP | UTF-8 | 1,479 | 2.8125 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreForm extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:190',
'phone' => 'required|min:10|max:12|numeric',
'email' => 'required|email',
'subject' => 'required|max:190',
];
}
public function messages() {
return [
'name.required' => 'El nombre es requerido',
'name.max' => 'El número máximo de caracteres en el nombre es de 190',
'phone.required' => 'El teléfono es requerido',
'phone.min' => 'El teléfono debe tener mínimo 10 dígitos',
'phone.max' => 'El teléfono debe tener mínimo 12 dígitos',
'phone.numeric' => 'El teléfono debe tener caracteres numéricos',
'email.required' => 'El correo es requerido',
'email.email' => 'El campo "email" debe ser escrito como un correo electrónico',
'subject.required' => 'El asunto es requerido',
'subject.max' => 'El número máximo de caracteres en el asunto es de 190',
];
}
}
|
PHP | UTF-8 | 1,298 | 2.78125 | 3 | [] | no_license | <?php
declare(strict_types = 1);
namespace Bootstrap\Routeur;
class Routeur {
public $routes;
static function singleton () {
return new self;
}
public function __construct()
{
$this->routes = [];
$this->routes[] = Route::get('404', function() {
require __DIR__ . '/../../resources/vues/erreurs/404.view.php';
});
}
public function ajouterRoute($route) {
if (!in_array($route, $this->routes)) {
$this->routes[] = $route;
}
}
public function supprimerRoute( $route )
{
if (($curseur = array_search($route, $this->routes)) !== false) {
unset($this->routes[$curseur]);
}
}
public function recupererRoute($uri) {
foreach ($this->routes as $route) {
if ($route->uri === $uri) {
return $route;
}
}
throw new \Exception("Route \"$uri\" inconnu");
}
public function traiterURI( $uri ) {
$matches = [];
foreach ($this->routes as $route) {
if ($route->uri === $uri) {
$route->lancerAction();
return;
}
}
$route404 = $this->recupererRoute('404');
$route404->lancerAction();
}
} |
Python | UTF-8 | 129 | 3.328125 | 3 | [] | no_license | nums = [10,16,18,21,22];
for i in nums:
if i%5==0:
print(i);
break;
else:
print("not found"); |
Python | UTF-8 | 2,481 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python
"""
Smear likelihood distribution according to systematic uncertainty
"""
__author__ = "Maoqiang JING <jingmq@ihep.ac.cn>"
__copyright__ = "Copyright (c) Maoqiang JING"
__created__ = "[2020-12-03 Thu 20:42]"
import math
from array import array
from ROOT import *
import sys, os
import logging
from math import *
from tools import *
import random
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
gStyle.SetPaperSize(20,30)
gStyle.SetPadTopMargin(0.05)
gStyle.SetPadRightMargin(0.08)
gStyle.SetPadBottomMargin(0.18)
gStyle.SetPadLeftMargin(0.16)
gStyle.SetOptTitle(0)
gStyle.SetOptTitle(0)
def usage():
sys.stdout.write('''
NAME
smear.py
SYNOPSIS
./smear.py [ecms]
AUTHOR
Maoqiang JING <jingmq@ihep.ac.cn>
DATE
December 2020
\n''')
def smear(path, ecms):
try:
f = open(path, 'r')
except:
logging.error(path + ' is invalid!')
sys.exit()
with open(path, 'r') as f:
lines = f.readlines()
N = len(lines) - 1
n_set = array('f', N*[0])
likelihood = array('f', N*[0])
count = 0
for i in xrange(N):
fargs = map(float, lines[i].strip('\n').strip().split())
n_set[i] = fargs[0]
likelihood[i] = fargs[1]
count += 1
n_smear = 5000
a = array('f', N*[0])
with open('../sys_err/sum/txts/sys_err_total.txt', 'r') as f:
for line in f.readlines():
fargs = map(float, line.strip('\n').strip().split())
if int(fargs[0]*1000) == ecms: sys_err = fargs[1]/100.
print 'Systematic uncertainty of {0} is {1}'.format(ecms, sys_err)
for nbin in xrange(N):
nevt = int(n_smear*likelihood[nbin])
numevt = 0
while numevt < nevt:
bin_num = int(random.gauss(0, sys_err + 1)*(nbin)) + 1
numevt += 1
if bin_num < 0 or bin_num > N: continue
a[bin_num-1] += 1
print 'Filling {0} bin...'.format(nbin)
if not os.path.exists('./txts/'):
os.makedirs('./txts/')
with open('./txts/likelihood_smear_' + str(ecms) + '.txt', 'w') as f:
for nbin in xrange(N):
f.write(str(round(n_set[nbin], 2)) + ' ' + str(a[nbin]/n_smear) + '\n')
def main():
args = sys.argv[1:]
if len(args)<1:
return usage()
ecms = int(args[0])
path = './txts/upper_limit_likelihood_total_' + str(ecms) + '.txt'
smear(path, ecms)
if __name__ == '__main__':
main()
|
Java | UTF-8 | 550 | 2.53125 | 3 | [] | no_license | package com.factory.domain.customerFactory;
import com.domain.customerBuilder.Customer;
public class CustomerFactory {
public Customer getCustomer(String name, String SurName, String emailAddress, String address, String phone_number, String customer_number)
{
return new Customer.Builder(emailAddress)
.buildAddress(address)
.buildName(name)
.buildPhoneNumber(phone_number)
.buildSurname(SurName)
.id(customer_number)
.build();
}
}
|
Java | UTF-8 | 6,158 | 2.265625 | 2 | [] | no_license | package windows;
import com.sun.awt.AWTUtilities;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.Logger;
//l2vHX%!$u$)2
public class splash extends javax.swing.JFrame implements Runnable {
private Thread time = null;
public splash() {
initComponents();
setLocationRelativeTo(null);
AWTUtilities.setWindowOpaque(this, false);
time = new Thread(this);
time.start();
setSize(688, 487);
}
@Override
public Image getIconImage() {
Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("iconos/iconopequeño.png"));
return retValue;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
horaelogo = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
carga = new javax.swing.JLabel();
cargandopuntos = new javax.swing.JLabel();
jLabel_Fodeer = new javax.swing.JLabel();
version = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setIconImage(getIconImage());
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(0, 51, 102));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
horaelogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/logo11_1_131140.png"))); // NOI18N
horaelogo.setText("jLabel1");
jPanel1.add(horaelogo, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 10, 490, 430));
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
carga.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Pulse-1s-200px.gif"))); // NOI18N
jPanel2.add(carga, new org.netbeans.lib.awtextra.AbsoluteConstraints(-20, -10, 180, 120));
cargandopuntos.setText("Cargando...");
jPanel2.add(cargandopuntos, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 60, -1, -1));
jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 380, 690, 110));
jLabel_Fodeer.setBackground(new java.awt.Color(255, 255, 255));
jLabel_Fodeer.setFont(new java.awt.Font("SansSerif", 0, 14)); // NOI18N
jLabel_Fodeer.setText("Creado por ribax123@gmail.com ®");
jPanel1.add(jLabel_Fodeer, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 540, -1, -1));
version.setBackground(new java.awt.Color(0, 0, 0));
version.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
version.setForeground(new java.awt.Color(255, 255, 255));
version.setText("Vs. 1.0");
jPanel1.add(version, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 360, -1, 20));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 688, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 471, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new splash().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel carga;
private javax.swing.JLabel cargandopuntos;
private javax.swing.JLabel horaelogo;
private javax.swing.JLabel jLabel_Fodeer;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel version;
// End of variables declaration//GEN-END:variables
// cuenta regresiva para abrir la interfaz del login
@Override
public void run() {
while (time != null) {
try {
Thread.sleep(2000);
new Interfaz().setVisible(true);
this.dispose();
break;
} catch (InterruptedException ex) {
Logger.getLogger(splash.class.getName()).log(Level.SEVERE, null, ex);
}
}
time = null;
}
}
|
Java | UTF-8 | 7,308 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | package de.team33.test.exceptional.v4;
import de.team33.libs.exceptional.v4.Handling;
import de.team33.libs.exceptional.v4.WrappedException;
import org.junit.Test;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
@SuppressWarnings({"NestedTryStatement", "ThrowCaughtLocally"})
public class HandlingTest {
public static final String EXPECTED_AN_EXCEPTION = "It is expected that an exception was thrown previously";
public static final List<Exception> EXCEPTION_LIST = Arrays.asList(
new IOException(), new SQLException(), new IllegalArgumentException(), new IllegalStateException()
);
private static <X extends Exception> void doThrow(final Supplier<X> supplier) throws X {
throw supplier.get();
}
private static <X extends Exception> Function<Exception, X> causeWhen(final Class<X> xClass) {
return caught -> Optional.ofNullable(caught.getCause())
.filter(xClass::isInstance)
.map(xClass::cast)
.orElse(null);
}
private static <X extends Exception> Function<Throwable, X> when(final Class<X> xClass) {
return cause -> Optional.ofNullable(cause)
.filter(xClass::isInstance)
.map(xClass::cast)
.orElse(null);
}
@Test
public final void reThrowCauseIf() {
for (final Exception exception : EXCEPTION_LIST) {
try {
try {
doThrow(() -> new WrappedException(exception));
fail(EXPECTED_AN_EXCEPTION);
} catch (final WrappedException caught) {
Handling.of(caught)
.reThrowCauseIf(IOException.class)
.reThrowCauseIf(SQLException.class)
.reThrowCauseIf(IllegalArgumentException.class)
.reThrowCauseIf(IllegalStateException.class);
fail(EXPECTED_AN_EXCEPTION);
}
} catch (final IOException caught) {
assertSame(EXCEPTION_LIST.get(0), caught);
} catch (final SQLException caught) {
assertSame(EXCEPTION_LIST.get(1), caught);
} catch (final IllegalArgumentException caught) {
assertSame(EXCEPTION_LIST.get(2), caught);
} catch (final IllegalStateException caught) {
assertSame(EXCEPTION_LIST.get(3), caught);
}
}
}
@Deprecated
@Test
public final void reThrowIf() {
for (final Exception exception : EXCEPTION_LIST) {
try {
try {
doThrow(() -> exception);
fail(EXPECTED_AN_EXCEPTION);
} catch (final Exception caught) {
Handling.of(caught)
.reThrowIf(IOException.class)
.reThrowIf(SQLException.class)
.reThrowIf(IllegalArgumentException.class)
.reThrowIf(IllegalStateException.class);
fail(EXPECTED_AN_EXCEPTION);
}
} catch (final IOException caught) {
assertSame(EXCEPTION_LIST.get(0), caught);
} catch (final SQLException caught) {
assertSame(EXCEPTION_LIST.get(1), caught);
} catch (final IllegalArgumentException caught) {
assertSame(EXCEPTION_LIST.get(2), caught);
} catch (final IllegalStateException caught) {
assertSame(EXCEPTION_LIST.get(3), caught);
}
}
}
@Test
public final void throwMapped() {
for (final Exception exception : EXCEPTION_LIST) {
try {
try {
doThrow(() -> new WrappedException(exception));
fail(EXPECTED_AN_EXCEPTION);
} catch (final WrappedException caught) {
Handling.of(caught)
.throwMapped(causeWhen(IOException.class))
.throwMapped(causeWhen(SQLException.class))
.throwMapped(causeWhen(IllegalArgumentException.class))
.throwMapped(causeWhen(IllegalStateException.class));
fail(EXPECTED_AN_EXCEPTION);
}
} catch (final IOException caught) {
assertSame(EXCEPTION_LIST.get(0), caught);
} catch (final SQLException caught) {
assertSame(EXCEPTION_LIST.get(1), caught);
} catch (final IllegalArgumentException caught) {
assertSame(EXCEPTION_LIST.get(2), caught);
} catch (final IllegalStateException caught) {
assertSame(EXCEPTION_LIST.get(3), caught);
}
}
}
@Test
public final void throwMappedCause() {
for (final Exception exception : EXCEPTION_LIST) {
try {
try {
doThrow(() -> new WrappedException(exception));
fail(EXPECTED_AN_EXCEPTION);
} catch (final WrappedException caught) {
Handling.of(caught)
.throwMappedCause(when(IOException.class))
.throwMappedCause(when(SQLException.class))
.throwMappedCause(when(IllegalArgumentException.class))
.throwMappedCause(when(IllegalStateException.class));
fail(EXPECTED_AN_EXCEPTION);
}
} catch (final IOException caught) {
assertSame(EXCEPTION_LIST.get(0), caught);
} catch (final SQLException caught) {
assertSame(EXCEPTION_LIST.get(1), caught);
} catch (final IllegalArgumentException caught) {
assertSame(EXCEPTION_LIST.get(2), caught);
} catch (final IllegalStateException caught) {
assertSame(EXCEPTION_LIST.get(3), caught);
}
}
}
@Test
public final void fallback() {
final IOException original = new IOException();
final IOException result = Handling.of(original)
.fallback();
assertSame(original, result);
}
@Test
public final void mapped() {
final IOException original = new IOException();
final IOException result = Handling.of(original)
.mapped(Function.identity());
assertSame(original, result);
}
@Test
public final void mappedCause() {
final IOException original = new IOException();
final Throwable result = Handling.of(new IllegalStateException(original))
.mappedCause(Function.identity());
assertSame(original, result);
}
}
|
JavaScript | UTF-8 | 1,994 | 3.296875 | 3 | [] | no_license | function quickSort(unsorted, low, high, steps) {
if (low == undefined || high == undefined) {
low = 0;
high = unsorted.length - 1;
steps = [];
}
if (unsorted.length > 1) {
const partitionIdx = partition(unsorted, low, high, steps);
if (low < partitionIdx - 1)
quickSort(unsorted, low, partitionIdx - 1, steps);
if (high > partitionIdx)
quickSort(unsorted, partitionIdx + 1, high, steps);
}
return steps;
}
function partition(unsorted, low, high, steps) {
var pivot = unsorted[high];
var i = 0;
var j = 0;
var positions = [];
for (let k = low; k < high; k++) {
if (unsorted[k] < pivot) {
if (k != i + low) {
positions.push({
old: k,
new: i + low
});
steps.push({
first: k,
second: i + low,
move: true,
compared: high
});
}
i++;
} else {
if (k != j + i + low) {
positions.push({
old: k,
new: j + i + low
});
steps.push({
first: k,
second: j + i + low,
move: true,
compared: high
});
}
j++;
}
}
if (high != i + low) {
positions.push({
old: high,
new: i + low
});
steps.push({
first: high,
second: i + low,
move: true,
compared: high
});
}
updatePositions(unsorted, positions);
return i + low;
}
function updatePositions(unsorted, positions) {
for (let i = 0; i < positions.length; i++) {
const element = positions[i];
unsorted.move(element.old, element.new);
}
} |
Java | UTF-8 | 1,123 | 2.96875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain-disclaimer"
] | permissive | package gov.usgs.earthquake.product.io;
import java.util.logging.Level;
import java.util.logging.Logger;
import gov.usgs.earthquake.product.Content;
import gov.usgs.earthquake.product.ProductId;
/**
* Deliver content in a separate thread.
*/
public class ContentOutputThread extends Thread {
private static final Logger LOGGER = Logger
.getLogger(ContentOutputThread.class.getName());
private final ProductHandler handler;
private final ProductId id;
private final String path;
private final Content content;
/**
* Constructor
* @param handler A product handler
* @param id A product ID
* @param path String path
* @param content Content
*/
public ContentOutputThread(final ProductHandler handler,
final ProductId id, final String path, final Content content) {
this.handler = handler;
this.id = id;
this.path = path;
this.content = content;
}
@Override
public void run() {
try {
handler.onContent(id, path, content);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception delivering content '" + path
+ "'", e);
} finally {
content.close();
}
}
}
|
Java | UTF-8 | 359 | 1.898438 | 2 | [] | no_license | package com.cts.ecommerce.dealer.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.time.LocalDate;
@Data
public class CustomerDTO {
private Integer customer_id;
private String customerName;
@JsonIgnore
private String password;
private String deliveryAddress;
private LocalDate dateOfBirth;
}
|
Python | UTF-8 | 794 | 2.734375 | 3 | [] | no_license | """this will attempt to import domains2.py, and failing to, will grab it from my pub github
and then import it"""
import urllib, os
def domains():
RAW_DOMAINS = 'https://raw.githubusercontent.com/imightbelying63/python/master/cpanel/domains2.py'
try:
import domains2
except ImportError:
try:
urllib.urlretrieve(RAW_DOMAINS, 'domains2.py')
import domains2
domains2_file = RAW_DOMAINS.split(os.path.sep)[-1]
if os.path.exists(domains2_file):
os.remove(domains2_file)
if os.path.exists(domains2_file + 'c'):
os.remove(domains2_file + 'c')
except:
print 'unable to retrieve required script'
return None
if __name__ == "__main__":
domains()
|
Java | UTF-8 | 3,641 | 2.109375 | 2 | [] | no_license | //package com.hengxin.platform.common.util;
//
//import java.io.IOException;
//import java.io.Serializable;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Map;
//
//import org.codehaus.jackson.JsonGenerationException;
//import org.codehaus.jackson.map.JsonMappingException;
//import org.codehaus.jackson.map.ObjectMapper;
//import org.junit.Test;
//
//import com.hengxin.platform.ebc.dto.EbcMobileVerifyRequest;
//import com.hengxin.platform.ebc.dto.EbcSignUpRequest;
//import com.hengxin.platform.ebc.dto.EbcSignUpResponse;
//import com.hengxin.platform.ebc.util.MD5;
//import com.hengxin.platform.escrow.chinapnr.constant.ParamConstant;
//import com.hengxin.platform.escrow.chinapnr.dto.RechargeRequest;
//import com.hengxin.platform.escrow.chinapnr.util.ParamUtil;
//import com.hengxin.platform.escrow.dto.CommandRequest;
//import com.hengxin.platform.escrow.dto.CommandResponse;
//import com.hengxin.platform.fund.util.DateUtils;
//import com.yst.m2.sdk.util.JsonUtil;
//
//public class ChinapnrTest {
//
// public class A implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public A() {
// super();
// }
//
// public String usertype = "0";
// };
//
// @Test
// public void httpParamTest() {
// RechargeRequest request = new RechargeRequest();
// request.setVersion(ParamConstant.VERSION_10);
// request.setCmdId("NetSave");
// request.setMerCustId("ht");
// request.setUsrCustId("winry");
// request.setOrdId("001");
// request.setOrdDate(DateUtils.formatDate(new Date(), "yyyyMMdd"));
// request.setGateBusiId("B2C");
// Map<String, String> params = ParamUtil.writeParams(request);
// for (String s : params.keySet()) {
// System.out.println(s + ":" + params.get(s));
// }
// }
//
// @Test
// public void jsonTest() throws JsonGenerationException,
// JsonMappingException, IOException {
// Map<String, String> map = new HashMap<String, String>();
// map.put("usertype", "0");
// System.out.print(JsonUtil.to_json(map));
// A a = new A();
// ObjectMapper mapper = new ObjectMapper();
// System.out.print(mapper.writeValueAsString(a));
// }
//
// @Test
// public void signUpTest() {
// CommandRequest request = buildSignUpRequest();
// EbcSignUpResponse response = (EbcSignUpResponse) request.execute();
// fail(response);
// }
//
// private EbcSignUpRequest buildSignUpRequest() {
// EbcSignUpRequest request = new EbcSignUpRequest();
// request.setMerchNo("000000000000000");
// request.setOrderSn(System.currentTimeMillis() + "");
// request.setOwnerId("EBC");
// request.setEnterName("winry");
// request.setLoginType("5");
// request.setUserType("1");
// request.setUserName("cong");
// request.setIdType("00");
// request.setIdCard("110101201401015659");
// request.setMobile("18658831602");
// request.setPayPass(MD5.md5("580685"));
// request.setWltNo("000001");
// request.setCurrency("CNY");
// return request;
// }
//
// private void fail(Object o) {
// System.out.println(o);
// }
//
// @Test
// public void smsTest() {
// CommandRequest request = buildEbcMobileVerifyRequest();
// CommandResponse response = request.execute();
// fail(response);
// }
//
// private CommandRequest buildEbcMobileVerifyRequest() {
// EbcMobileVerifyRequest request = new EbcMobileVerifyRequest();
// request.setMerchNo("000000000000000");
// request.setOrderSn(System.currentTimeMillis() + "");
// request.setOwnerId("EBC");
// request.setUserNo("ff4f50b79d094a1485794713e9f008e3");
// request.setMediumNo("0100980002605529");
// request.setMobile("18658831602");
// request.setSmsModel("m");
// return request;
// }
//
// }
|
JavaScript | UTF-8 | 8,811 | 3.375 | 3 | [
"Apache-2.0"
] | permissive | /**
* ## Events module
*
* This is a browser port of the node.js events module. Many objects and
* modules emit events and these are instances of events.EventEmitter.
*
* You can access this module by doing: `require("events")`
*
* Functions can then be attached to objects, to be executed when an event is
* emitted. These functions are called listeners.
*
* @module
*/
/**
* To access the EventEmitter class, require('events').EventEmitter.
*
* When an EventEmitter instance experiences an error, the typical action is to
* emit an 'error' event. Error events are treated as a special case. If there
* is no listener for it, then the default action is for the error to throw.
*
* All EventEmitters emit the event 'newListener' when new listeners are added.
*
* @name events.EventEmitter
* @api public
*
* ```javascript
* var EventEmitter = require('events').EventEmitter;
*
* // create an event emitter
* var emitter = new EventEmitter();
* ```
*/
var EventEmitter = exports.EventEmitter = function () {};
var isArray = Array.isArray || function (obj) {
return toString.call(obj) === '[object Array]';
};
/**
* By default EventEmitters will print a warning if more than 10 listeners are
* added for a particular event. This is a useful default which helps finding
* memory leaks. Obviously not all Emitters should be limited to 10. This
* function allows that to be increased. Set to zero for unlimited.
*
* @name emitter.setMaxListeners(n)
* @param {Number} n - The maximum number of listeners
* @api public
*/
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
var defaultMaxListeners = 10;
EventEmitter.prototype.setMaxListeners = function(n) {
if (!this._events) this._events = {};
this._events.maxListeners = n;
};
/**
* Execute each of the listeners in order with the supplied arguments.
*
* @name emitter.emit(event, [arg1], [arg2], [...])
* @param {String} event - The event name/id to fire
* @api public
*/
EventEmitter.prototype.emit = function(type) {
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events || !this._events.error ||
(isArray(this._events.error) && !this._events.error.length))
{
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
if (!this._events) return false;
var handler = this._events[type];
if (!handler) return false;
if (typeof handler == 'function') {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
return true;
} else if (isArray(handler)) {
var args = Array.prototype.slice.call(arguments, 1);
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
return true;
} else {
return false;
}
};
/**
* Adds a listener to the end of the listeners array for the specified event.
*
* @name emitter.on(event, listener) | emitter.addListener(event, listener)
* @param {String} event - The event name/id to listen for
* @param {Function} listener - The function to bind to the event
* @api public
*
* ```javascript
* session.on('change', function (userCtx) {
* console.log('session changed!');
* });
* ```
*/
// EventEmitter is defined in src/node_events.cc
// EventEmitter.prototype.emit() is also defined there.
EventEmitter.prototype.addListener = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('addListener only takes instances of Function');
}
if (!this._events) this._events = {};
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
} else if (isArray(this._events[type])) {
// Check for listener leak
if (!this._events[type].warned) {
var m;
if (this._events.maxListeners !== undefined) {
m = this._events.maxListeners;
} else {
m = defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
// If we've already got an array, just append.
this._events[type].push(listener);
} else {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
/**
* Adds a one time listener for the event. This listener is invoked only the
* next time the event is fired, after which it is removed.
*
* @name emitter.once(event, listener)
* @param {String} event- The event name/id to listen for
* @param {Function} listener - The function to bind to the event
* @api public
*
* ```javascript
* db.once('unauthorized', function (req) {
* // this event listener will fire once, then be unbound
* });
* ```
*/
EventEmitter.prototype.once = function(type, listener) {
var self = this;
self.on(type, function g() {
self.removeListener(type, g);
listener.apply(this, arguments);
});
return this;
};
/**
* Remove a listener from the listener array for the specified event. Caution:
* changes array indices in the listener array behind the listener.
*
* @name emitter.removeListener(event, listener)
* @param {String} event - The event name/id to remove the listener from
* @param {Function} listener - The listener function to remove
* @api public
*
* ```javascript
* var callback = function (init) {
* console.log('duality app loaded');
* };
* devents.on('init', callback);
* // ...
* devents.removeListener('init', callback);
* ```
*/
EventEmitter.prototype.removeListener = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('removeListener only takes instances of Function');
}
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events || !this._events[type]) return this;
var list = this._events[type];
if (isArray(list)) {
var i = list.indexOf(listener);
if (i < 0) return this;
list.splice(i, 1);
if (list.length == 0)
delete this._events[type];
} else if (this._events[type] === listener) {
delete this._events[type];
}
return this;
};
/**
* Removes all listeners, or those of the specified event.
*
* @name emitter.removeAllListeners([event])
* @param {String} event - Event name/id to remove all listeners for (optional)
* @api public
*/
EventEmitter.prototype.removeAllListeners = function(type) {
// does not use listeners(), so no side effect of creating _events[type]
if (type && this._events && this._events[type]) this._events[type] = null;
return this;
};
/**
* Returns an array of listeners for the specified event. This array can be
* manipulated, e.g. to remove listeners.
*
* @name emitter.listeners(event)
* @param {String} events - The event name/id to return listeners for
* @api public
*
* ```javascript
* session.on('change', function (stream) {
* console.log('session changed');
* });
* console.log(util.inspect(session.listeners('change'))); // [ [Function] ]
* ```
*/
EventEmitter.prototype.listeners = function(type) {
if (!this._events) this._events = {};
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
/**
* @name emitter Event: 'newListener'
*
* This event is emitted any time someone adds a new listener.
*
* ```javascript
* emitter.on('newListener', function (event, listener) {
* // new listener added
* });
* ```
*/
|
PHP | UTF-8 | 773 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Services;
use App\Eloquents\Invoice;
class InvoiceService
{
public function index()
{
$query = Invoice::query();
return $query->get();
}
public function findOrFail(int $invoiceId)
{
return Invoice::findOrFail($invoiceId);
}
public function create(array $attributes)
{
$invoice = new Invoice();
$invoice->fill($attributes);
$invoice->save();
return $invoice;
}
public function update(Invoice $argInvoice, array $attributes)
{
$invoice = clone $argInvoice;
$invoice->fill($attributes);
$invoice->save();
return $invoice;
}
public function delete(Invoice $invoice)
{
$invoice->delete();
}
}
|
C# | UTF-8 | 876 | 2.890625 | 3 | [] | no_license | public Type GetNullable(Type type)
{
if (type == typeof(Nullable<>))
return type.GetType();
if(type == typeof(int))
type = typeof(int?);
else if(type == typeof(bool))
type = typeof(bool?);
else if(type == typeof(float))
type = typeof(float?);
// etc. you will have to build out every type you want.
return type;
}
public Expression<Func<VwAssignmentActivities, bool>> GetIsNullExpressionEquals(string propName, Type value)
{
var item = Expression.Parameter(typeof(VwAssignmentActivities), "item");
var prop = Expression.Convert(Expression.Property(item, propName), GetNullable(value));
Expression body = Expression.Equal(prop, Expression.Constant(null, prop.Type));
return Expression.Lambda<Func<VwAssignmentActivities, bool>>(body, item);
}
|
Java | UTF-8 | 167 | 2.203125 | 2 | [] | no_license | package model;
public class StudentExistsException extends Exception {
public StudentExistsException(String errorMessage) {
super(errorMessage);
}
}
|
Python | UTF-8 | 5,212 | 2.828125 | 3 | [
"MIT"
] | permissive | import pytest
from blacksheep import Request, Headers, Header
from blacksheep import scribe
from blacksheep.exceptions import BadRequestFormat, InvalidOperation
def test_request_supports_dynamic_attributes():
request = Request(b'GET', b'/', Headers(), None)
foo = object()
assert hasattr(request, 'foo') is False, 'This test makes sense if such attribute is not defined'
request.foo = foo
assert request.foo is foo
@pytest.mark.asyncio
@pytest.mark.parametrize('url,method,headers,content,expected_result', [
(b'https://robertoprevato.github.io', b'GET', [], None,
b'GET / HTTP/1.1\r\nHost: robertoprevato.github.io\r\n\r\n'),
(b'https://robertoprevato.github.io', b'HEAD', [], None,
b'HEAD / HTTP/1.1\r\nHost: robertoprevato.github.io\r\n\r\n'),
(b'https://robertoprevato.github.io', b'POST', [], None,
b'POST / HTTP/1.1\r\nHost: robertoprevato.github.io\r\n\r\n'),
(b'https://robertoprevato.github.io/How-I-created-my-own-media-storage-in-Azure/', b'GET', [], None,
b'GET /How-I-created-my-own-media-storage-in-Azure/ HTTP/1.1\r\nHost: robertoprevato.github.io\r\n\r\n'),
(b'https://foo.org/a/b/c/?foo=1&ufo=0', b'GET', [], None,
b'GET /a/b/c/?foo=1&ufo=0 HTTP/1.1\r\nHost: foo.org\r\n\r\n'),
])
async def test_request_writing(url, method, headers, content, expected_result):
request = Request(method, url, Headers(headers), content)
data = b''
async for chunk in scribe.write_request(request):
data += chunk
assert data == expected_result
@pytest.mark.parametrize('url,query,parsed_query', [
(b'https://foo.org/a/b/c?hello=world', b'hello=world', {
'hello': ['world']
}),
(b'https://foo.org/a/b/c?hello=world&foo=power', b'hello=world&foo=power', {
'hello': ['world'],
'foo': ['power']
}),
(b'https://foo.org/a/b/c?hello=world&foo=power&foo=200', b'hello=world&foo=power&foo=200', {
'hello': ['world'],
'foo': ['power', '200']
}),
])
def test_parse_query(url, query, parsed_query):
request = Request(b'GET', url, None, None)
assert request.url.value == url
assert request.url.query == query
assert request.query == parsed_query
@pytest.mark.asyncio
async def test_can_read_json_data_even_without_content_type_header():
request = Request(b'POST', b'/', Headers(), None)
request.extend_body(b'{"hello":"world","foo":false}')
request.complete.set()
json = await request.json()
assert json == {"hello": "world", "foo": False}
@pytest.mark.asyncio
async def test_if_read_json_fails_content_type_header_is_checked_json_gives_bad_request_format():
request = Request(b'POST', b'/', Headers([
Header(b'Content-Type', b'application/json')
]), None)
request.extend_body(b'{"hello":') # broken json
request.complete.set()
with pytest.raises(BadRequestFormat):
await request.json()
@pytest.mark.asyncio
async def test_if_read_json_fails_content_type_header_is_checked_non_json_gives_invalid_operation():
request = Request(b'POST', b'/', Headers([
Header(b'Content-Type', b'text/html')
]), None)
request.extend_body(b'{"hello":') # broken json
request.complete.set()
with pytest.raises(InvalidOperation):
await request.json()
def test_cookie_parsing():
request = Request(b'POST', b'/', Headers([
Header(b'Cookie', b'ai=something; hello=world; foo=Hello%20World%3B;')
]), None)
assert request.cookies == {
b'ai': b'something',
b'hello': b'world',
b'foo': b'Hello World;'
}
def test_cookie_parsing_multiple_cookie_headers():
request = Request(b'POST', b'/', Headers([
Header(b'Cookie', b'ai=something; hello=world; foo=Hello%20World%3B;'),
Header(b'Cookie', b'jib=jab; ai=else;'),
]), None)
assert request.cookies == {
b'ai': b'else',
b'hello': b'world',
b'foo': b'Hello World;',
b'jib': b'jab'
}
def test_cookie_parsing_duplicated_cookie_header_value():
request = Request(b'POST', b'/', Headers([
Header(b'Cookie', b'ai=something; hello=world; foo=Hello%20World%3B; hello=kitty;')
]), None)
assert request.cookies == {
b'ai': b'something',
b'hello': b'kitty',
b'foo': b'Hello World;'
}
@pytest.mark.parametrize('header,expected_result', [
[Header(b'Expect', b'100-Continue'), True],
[Header(b'expect', b'100-continue'), True],
[Header(b'X-Foo', b'foo'), False]
])
def test_request_expect_100_continue(header, expected_result):
request = Request(b'POST', b'/', Headers([header]), None)
assert expected_result == request.expect_100_continue()
@pytest.mark.parametrize('headers,expected_result', [
[[Header(b'Content-Type', b'application/json')], True],
[[Header(b'Content-Type', b'application/problem+json')], True],
[[Header(b'Content-Type', b'application/json; charset=utf-8')], True],
[[], False],
[[Header(b'Content-Type', b'application/xml')], False]
])
def test_request_declares_json(headers, expected_result):
request = Request(b'GET', b'/', Headers(headers), None)
assert request.declares_json() is expected_result
|
Python | UTF-8 | 220 | 3.34375 | 3 | [] | no_license | divisor_num =int(input())
divisor_list =list(map(int, input().split()))
if len(divisor_list) == 1 :
print(divisor_list[0]*divisor_list[0])
else:
divisor_list.sort()
print(divisor_list[0]*divisor_list[-1])
|
Markdown | UTF-8 | 1,898 | 4 | 4 | [] | no_license | ## Problem
Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
[link](http://leetcode.com/onlinejudge#question_125)
## Stop and Think
从定义出发,定义两个pointer,一头一尾出发,如果不是alphanumeric就skip,不然就比较character。
## Solution
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
char[] arr = s.toLowerCase().toCharArray();
int i = 0;
int j = arr.length - 1;
while (i < j) {
if (!isAlphanumeric(arr[i])) {
i++;
}
else if (!isAlphanumeric(arr[j])) {
j--;
}
else {
if (arr[i] != arr[j]) {
return false;
}
i++;
j--;
}
}
return true;
}
private boolean isAlphanumeric(char c) {
return ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z'));
}
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
char[] arr = s.toLowerCase().toCharArray();
int i = 0;
int j = arr.length - 1;
while (i < j) {
if (!isAlphanumeric(arr[i])) {
i++;
}
else if (!isAlphanumeric(arr[j])) {
j--;
}
else {
if (arr[i] != arr[j]) {
return false;
}
i++;
j--;
}
}
return true;
}
private boolean isAlphanumeric(char c) {
return ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z'));
}
## Note
- 注意string可能是null或者empty。
|
Java | ISO-8859-1 | 4,027 | 2.421875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* WuerfelView.java
*
* Created on Oct 30, 2013, 3:27:13 PM
*/
package aufgabe05a.View;
/**
*
* @author christian
*/
public class WuerfelView extends javax.swing.JFrame {
/** Creates new form WuerfelView */
public WuerfelView() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lbWuerfelAugen = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
btnStartStop = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Wrfel");
jPanel1.setLayout(new java.awt.GridBagLayout());
lbWuerfelAugen.setFont(new java.awt.Font("Dialog", 1, 48)); // NOI18N
jPanel1.add(lbWuerfelAugen, new java.awt.GridBagConstraints());
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
btnStartStop.setText("Start");
jPanel2.add(btnStartStop);
getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-422)/2, (screenSize.height-330)/2, 422, 330);
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(WuerfelView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(WuerfelView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(WuerfelView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(WuerfelView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WuerfelView().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton btnStartStop;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel lbWuerfelAugen;
// End of variables declaration//GEN-END:variables
/**
* @return the btnStartStop
*/
public javax.swing.JToggleButton getBtnStartStop() {
return btnStartStop;
}
/**
* @return the lbWuerfelAugen
*/
public javax.swing.JLabel getLbWuerfelAugen() {
return lbWuerfelAugen;
}
}
|
Markdown | UTF-8 | 2,786 | 3.5625 | 4 | [
"MIT",
"CC-BY-4.0"
] | permissive | ---
layout: post
title: Scrum Story Points
date: 2016-11-05 22:00
tags: [agile, scrum, project planning]
---
Scrum teams often separate **estimation** (which is used for measuring the size
of a backlog and calculating velocity) from **tracking** (which is often the
burndown of hours used during the Sprint to be sure we're not way off the
pace necessary to complete the stories in the Sprint timebox), and use
different units for each. A common approach is to estimate tasks in
Story Points, then track tasks using hours.
Product teams often need to be able to estimate how long a product will
take to deliver. This is tough because the backlog may stretch months
into the future, so the team can only provide a rough estimate in conditions
of uncertainty unless they work for days breaking the tasks down.
However, from sprint to sprint as they work through the stories, the team
will develop a cadence of completing <x> units of work they had
'rough estimated', i.e. their velocity. This means that they can
relatively accurately estimate how long portions of the backlog will take
to get done with simple rough estimates that the team can produce long
before they even consider doing them. However, to make this work the
team needs to estimate stories with a consistent level of uncertainty.
The team also needs to track the amount of estimation units they have
actually fully completed from sprint to sprint because this number is
the one that tells us with relative certainty how much can be fit into each
future sprint.
Story points estimations work well to follow a Fibonacci sequence:
**1, 2, 3, 5, 8, 13, 21**
Story points are numbered this way to account for the fact that the longer
an estimate is, the more uncertainty it contains. If a developer wants to
estimate a **6**, he's forced to reconsider that some of the perceived
uncertainty does not exist (and
[play a 5](https://en.wikipedia.org/wiki/Planning_poker)), or accept a
conservative estimate which accounts for the uncertainty (and then
[play an 8](https://en.wikipedia.org/wiki/Planning_poker)).
|Points|How Much Work?|
|:-:|---|
|1 |This is trivial.|
|2 |This is small.|
|3 |This is 1-2 days of work.|
|5 |This is could take half of my week.|
|8 |This is a full week's worth of work. We should probably break it down into smaller tasks.|
|13 |A week or two. This should probably be an epic, break it down.|
|21 |Seriously? This is going to take at least a month!|
Purists would argue that I shouldn't describe story points in relation to days
or weeks, but I think it's important to start off by relating points to
time. Eventually, and very quickly, you'll be able to think abstractly about
how many points of *effort* are involved without going though a time-to-points
mental translation.
|
Shell | UTF-8 | 740 | 3.484375 | 3 | [] | no_license | #!/bin/sh
#
# This is the prerm script for the Debian GNU/Linux time package
#
# Written by Dirk Eddelbuettel <edd@debian.org>
set -e
# Automatically added by dh_installdocs
if [ "$1" = remove ] || [ "$1" = upgrade ] && \
which install-docs >/dev/null 2>&1; then
install-docs -r time
fi
# End automatically added section
# Automatically added by dh_installdocs
if [ "$1" = remove ] || [ "$1" = upgrade ] && \
which install-docs >/dev/null 2>&1; then
install-docs -r time
fi
# End automatically added section
case "$1" in
upgrade)
;;
remove|purge)
install-info --quiet --remove time.info.gz
;;
failed-upgrade|abort-install|abort-upgrade|disappear)
;;
*)
echo "prerm called with unknown argument \`$1'" >&2
;;
esac
exit 0
|
C++ | UTF-8 | 1,732 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
int mini1,mini2,n,m;
int row[10][10],col[10][10],crr[10][10];
void fun(int,int,int,int,int);
int main()
{
int i,j;
cin>>m>>n;
for(i=0;i<m;i++)
{
for(j=0;j<n-1;j++)
{
cin>>row[i][j];
}
}
for(i=0;i<m-1;i++)
{
for(j=0;j<n;j++)
{
cin>>col[i][j];
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
crr[i][j]=0;
}
mini1=100000;
mini2=100000;
crr[0][0]=1;
fun(1,0,1,1,row[0][0]);
fun(2,1,0,1,col[0][0]);
if(mini1<=mini2)
{
if(mini1<100000)
cout<<mini1<<"\n";
else
cout<<"0\n";
}
else
{
if(mini2<100000)
cout<<mini2<<"\n";
else
cout<<"0\n";
}
getch();
return 0;
}
void fun(int which,int x,int y,int ctr,int sum)
{
if(ctr==(m*n)-1)
{
if(which==1)
{
if(x==1 && y==0)
{
if(sum<=mini1)
mini1=sum+col[0][0];
}
}
if(which==2)
{
if(x==0 && y==1)
{
if(sum<=mini2)
mini2=sum+row[0][0];
}
}
}
crr[x][y]=1;
if(x>=0 && x<m && y<n-1 && y>=0)
{
if(crr[x][y+1]==0)
{
fun(which,x,y+1,ctr+1,sum+row[x][y]);
}
}
if(x>=0 && x<m && y>0 && y<n)
{
if(crr[x][y-1]==0)
{
fun(which,x,y-1,ctr+1,sum+row[x][y-1]);
}
}
if(x>=0 && x<m-1 && y<n && y>=0)
{
if(crr[x+1][y]==0)
{
fun(which,x+1,y,ctr+1,sum+col[x][y]);
}
}
if(x>0 && x<m && y<n && y>=0)
{
if(crr[x-1][y]==0)
{
fun(which,x-1,y,ctr+1,sum+col[x-1][y]);
}
}
crr[x][y]=0;
return;
}
|
Java | UTF-8 | 6,150 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | package com.company.northwind4cuba.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.AttributeOverrides;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import com.haulmont.cuba.core.global.DesignSupport;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.haulmont.cuba.core.entity.BaseIntIdentityIdEntity;
import com.haulmont.chile.core.annotations.NamePattern;
@NamePattern("%s / %s|orderDate,id")
@DesignSupport("{'imported':true}")
@AttributeOverrides({
@AttributeOverride(name = "id", column = @Column(name = "ORDER_ID"))
})
@Table(name = "ORDER_")
@Entity(name = "northwind4cuba$Order")
public class Order extends BaseIntIdentityIdEntity {
private static final long serialVersionUID = -1712351114126416309L;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "EMPLOYEE_ID")
protected Employee employee;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CUSTOMER_ID")
protected Customer customer;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "ORDER_DATE")
protected Date orderDate;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "SHIPPED_DATE")
protected Date shippedDate;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SHIPPER_ID")
protected Shipper shipper;
@Column(name = "SHIP_NAME", length = 50)
protected String shipName;
@Lob
@Column(name = "SHIP_ADDRESS")
protected String shipAddress;
@Column(name = "SHIP_CITY", length = 50)
protected String shipCity;
@Column(name = "SHIP_STATE_PROVINCE", length = 50)
protected String shipStateProvince;
@Column(name = "SHIP_ZIP_POSTAL_CODE", length = 50)
protected String shipZipPostalCode;
@Column(name = "SHIP_COUNTRY_REGION", length = 50)
protected String shipCountryRegion;
@Column(name = "SHIPPING_FEE", precision = 19, scale = 4)
protected BigDecimal shippingFee;
@Column(name = "TAXES", precision = 19, scale = 4)
protected BigDecimal taxes;
@Column(name = "PAYMENT_TYPE", length = 50)
protected String paymentType;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "PAID_DATE")
protected Date paidDate;
@Lob
@Column(name = "NOTES")
protected String notes;
@Column(name = "TAX_RATE")
protected Double taxRate;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TAX_STATUS")
protected OrdersTaxStatus taxStatus;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STATUS_ID")
protected OrdersStatus status;
@Column(name = "\"SSMA_TimeStamp\"", nullable = false)
protected byte[] ssmaTimestamp;
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Employee getEmployee() {
return employee;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Customer getCustomer() {
return customer;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getOrderDate() {
return orderDate;
}
public void setShippedDate(Date shippedDate) {
this.shippedDate = shippedDate;
}
public Date getShippedDate() {
return shippedDate;
}
public void setShipper(Shipper shipper) {
this.shipper = shipper;
}
public Shipper getShipper() {
return shipper;
}
public void setShipName(String shipName) {
this.shipName = shipName;
}
public String getShipName() {
return shipName;
}
public void setShipAddress(String shipAddress) {
this.shipAddress = shipAddress;
}
public String getShipAddress() {
return shipAddress;
}
public void setShipCity(String shipCity) {
this.shipCity = shipCity;
}
public String getShipCity() {
return shipCity;
}
public void setShipStateProvince(String shipStateProvince) {
this.shipStateProvince = shipStateProvince;
}
public String getShipStateProvince() {
return shipStateProvince;
}
public void setShipZipPostalCode(String shipZipPostalCode) {
this.shipZipPostalCode = shipZipPostalCode;
}
public String getShipZipPostalCode() {
return shipZipPostalCode;
}
public void setShipCountryRegion(String shipCountryRegion) {
this.shipCountryRegion = shipCountryRegion;
}
public String getShipCountryRegion() {
return shipCountryRegion;
}
public void setShippingFee(BigDecimal shippingFee) {
this.shippingFee = shippingFee;
}
public BigDecimal getShippingFee() {
return shippingFee;
}
public void setTaxes(BigDecimal taxes) {
this.taxes = taxes;
}
public BigDecimal getTaxes() {
return taxes;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getPaymentType() {
return paymentType;
}
public void setPaidDate(Date paidDate) {
this.paidDate = paidDate;
}
public Date getPaidDate() {
return paidDate;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getNotes() {
return notes;
}
public void setTaxRate(Double taxRate) {
this.taxRate = taxRate;
}
public Double getTaxRate() {
return taxRate;
}
public void setTaxStatus(OrdersTaxStatus taxStatus) {
this.taxStatus = taxStatus;
}
public OrdersTaxStatus getTaxStatus() {
return taxStatus;
}
public void setStatus(OrdersStatus status) {
this.status = status;
}
public OrdersStatus getStatus() {
return status;
}
public byte[] getSsmaTimestamp() {
return ssmaTimestamp;
}
} |
Java | UTF-8 | 1,761 | 2.03125 | 2 | [] | no_license | package com.wanniu.game.request.vip;
import java.io.IOException;
import com.wanniu.core.game.LangService;
import com.wanniu.core.game.entity.GClientEvent;
import com.wanniu.core.game.protocol.PomeloRequest;
import com.wanniu.core.game.protocol.PomeloResponse;
import com.wanniu.game.player.WNPlayer;
import pomelo.area.VipHandler.GetEveryDayGiftRequest;
import pomelo.area.VipHandler.GetEveryDayGiftResponse;
@GClientEvent("area.vipHandler.getEveryDayGiftRequest")
public class GetEveryDayGiftHandler extends PomeloRequest {
@Override
public PomeloResponse request() throws Exception {
return new PomeloResponse() {
protected void write() throws IOException {
WNPlayer player = (WNPlayer) pak.getPlayer();
GetEveryDayGiftRequest req = GetEveryDayGiftRequest.parseFrom(pak.getRemaingBytes());
int type = req.getC2SType();
int result = player.vipManager.takeDailyReward(type);
GetEveryDayGiftResponse.Builder res = GetEveryDayGiftResponse.newBuilder();
if(result == 0){
res.setS2CCode(OK);
}else if(result == -1){
res.setS2CCode(FAIL);
res.setS2CMsg(LangService.getValue("CARD_MONTH_NONE"));
}else if(result == -2){
res.setS2CCode(FAIL);
res.setS2CMsg(LangService.getValue("CARD_FOREVER_NONE"));
}else if(result == -3){
res.setS2CCode(FAIL);
res.setS2CMsg(LangService.getValue("CARD_RECEIVED"));
}else if(result == -4){
res.setS2CCode(FAIL);
res.setS2CMsg(LangService.getValue("SOMETHING_ERR"));
}
// PrepaidListResponse.Builder res = PrepaidListResponse.newBuilder();
// List<FeeItem> items = player.prepaidManager.getPrepaidList();
// res.addAllS2CItems(items);
// res.setS2CCode(OK);
body.writeBytes(res.build().toByteArray());
}
};
}
}
|
Java | UTF-8 | 3,047 | 1.984375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2011-2021 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.dag.compiler.codegen;
import static com.asakusafw.lang.compiler.model.description.Descriptions.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.asakusafw.dag.api.processor.EdgeIoProcessorContext;
import com.asakusafw.dag.api.processor.testing.CollectionObjectReader;
import com.asakusafw.dag.api.processor.testing.MockTaskProcessorContext;
import com.asakusafw.dag.api.processor.testing.MockVertexProcessorContext;
import com.asakusafw.dag.compiler.codegen.ExtractInputAdapterGenerator.Spec;
import com.asakusafw.dag.runtime.adapter.ExtractOperation;
import com.asakusafw.dag.runtime.adapter.InputHandler;
import com.asakusafw.dag.runtime.adapter.InputHandler.InputSession;
import com.asakusafw.dag.runtime.skeleton.ExtractInputAdapter;
import com.asakusafw.lang.compiler.model.description.ClassDescription;
/**
* Test for {@link ExtractInputAdapterGenerator}.
*/
public class ExtractInputAdapterGeneratorTest extends ClassGeneratorTestRoot {
/**
* simple case.
*/
@Test
public void simple() {
check("Hello, world!");
}
/**
* multiple inputs.
*/
@Test
public void multiple() {
check("A", "B", "C");
}
private void check(String... values) {
Spec spec = new Spec("i", typeOf(String.class));
ClassGeneratorContext gc = context();
ClassDescription generated = add(c -> new ExtractInputAdapterGenerator().generate(gc, spec, c));
MockTaskProcessorContext tc = new MockTaskProcessorContext("t")
.withInput("i", () -> new CollectionObjectReader(Arrays.asList(values)));
List<Object> results = new ArrayList<>();
loading(generated, c -> {
try (ExtractInputAdapter adapter = adapter(c, new MockVertexProcessorContext().with(c))) {
adapter.initialize();
InputHandler<ExtractOperation.Input, ? super EdgeIoProcessorContext> handler = adapter.newHandler();
try (InputSession<ExtractOperation.Input> session = handler.start(tc)) {
while (session.next()) {
results.add(session.get().getObject());
}
}
}
});
assertThat(results, containsInAnyOrder((Object[]) values));
}
}
|
Markdown | UTF-8 | 780 | 2.65625 | 3 | [] | no_license | +++
title = 'Regional Climate Data Researcher'
tags = ['algebra', 'maths', 'maths-algebra', 'maths-primary', 'observant', 'organised', 'patient', 'primary', 'primary', 'science', 'science-primary', 'seasonal-changes', 'seasonal-changes', 'year-1', 'year-2', 'year-3', 'year-4', 'year-5', 'year-6']
categories = []
menu = "main"
+++
A regional climate data researcher manages, analyses and prepares regional climate data for climate impact models and visualisation services. They use scientific data handling and experienced scientific interpretation of the climate sensitivity and uncertainties. They provide solutions to regional climate changes and climate impacts and make seasonal predictions on a regional scale.
<strong>Attributes: </strong>observant, organised, patient
|
C++ | UTF-8 | 1,333 | 2.640625 | 3 | [] | no_license | #pragma once
#define USE_OPENCV
#ifdef USE_OPENCV
#include <opencv2/opencv.hpp>
#endif
namespace caffe2net {
class Utils {
public:
Utils() {}
~Utils() {}
#ifdef USE_OPENCV
void Mat2array(cv::Mat src, unsigned char *data) {
int p = 0;
#pragma omp parallel for
for (int h = 0; h < src.rows; h++)
{
unsigned char* s = src.ptr<unsigned char>(h);
int img_index = 0;
for (int w = 0; w < src.cols; w++)
{
for (int c = 0; c < src.channels(); c++)
{
int data_index;
if(src.channels()>1)
data_index = (2-c) * src.rows*src.cols + h * src.cols + w;
else
data_index = c * src.rows*src.cols + h * src.cols + w;
unsigned char g = s[img_index++];
data[data_index] = g;
}
}
}
}
void array2Mat(std::vector<float> data, int chn, int width, int height, cv::Mat &img) {
cv::Mat dst_img(width, height, CV_32FC(chn));
#pragma omp parallel for
for (int h = 0; h < dst_img.rows; h++) {
float* s = dst_img.ptr<float>(h);
int img_index = 0;
for (int w = 0; w < dst_img.cols; w++) {
for (int c = 0; c < dst_img.channels(); c++) {
int data_index = c * dst_img.rows * dst_img.cols + h * dst_img.cols + w;
s[img_index++] = data[data_index];
}
}
}
cv::convertScaleAbs(dst_img, img, 255);
}
#endif
};
}
|
JavaScript | UTF-8 | 300 | 3.421875 | 3 | [] | no_license | export const range = (lo, hi) => {
hi = Number(hi);
lo = Number(lo);
if (isNaN(hi) || isNaN(lo)) {
throw new Error ('Arguments must be numbers');
}
if ( lo === 0 && hi === 0) { return 0; }
let list = [];
for (let i = lo; i <= hi; i++) {
list.push(i);
}
return list;
};
|
C++ | UTF-8 | 1,651 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include "StringUtility.h"
using DanielGoodbody::StringUtility;
using namespace std;
int main()
{
StringUtility stringTester;
vector<string> strings;
strings.push_back("The");
strings.push_back("quick");
strings.push_back("brown");
strings.push_back("fox");
strings.push_back("jumps");
strings.push_back("over");
strings.push_back("the");
strings.push_back("lazy");
strings.push_back("dog");
cout << "Test join with delimeter (,)\n";
const char delimeter(',');
cout << stringTester.join(strings,delimeter) << '\n';
cout << "\nTest reverse function\n";
vector<string> reverseStrings = stringTester.reverse(strings);
for (vector<string>::iterator iter = reverseStrings.begin(); iter != reverseStrings.end(); ++iter)
cout << *iter << " ";
cout << '\n';
cout << "\nTest combine function\n";
vector<string> left;
left.push_back("Mr.");
left.push_back("Mrs.");
vector<string> right;
right.push_back("Jones"); //, "Smith", "Williams");
right.push_back("Smith");
right.push_back("Williams");
//output new vector
vector<string> combineStrings = stringTester.combine(left, right);
for (vector<string>::iterator iter = combineStrings.begin(); iter != combineStrings.end(); ++iter)
cout << *iter << " ";
cout << '\n';
//Test leftPad function with the strings vector form above
cout << "\nTest leftPad function with delimeter (*)\n";
vector<string> padStrings = stringTester.leftPad(strings, '*');
for (vector<string>::iterator iter = padStrings.begin(); iter != padStrings.end(); ++iter)
cout << *iter << " ";
}
|
Java | UTF-8 | 4,607 | 2.796875 | 3 | [] | no_license | /* JSphere.java - main class for spherical projection
*
*/
package jsphere;
import jsphere.geom.*;
import jsphere.observer.*;
import jsphere.proj.*;
import jsphere.trans.*;
import jsphere.urban.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.util.Map;
import java.util.TreeMap;
/**
* Main class for the spherical projection.
* From a urban scene and a path, this program produce spherical projections.
* The spherical projections are PNG pictures with a radius of 250 pixels.
*/
public class JSphere
{
protected static final double DEFAULT_RADIUS = 250.0;
/* protected UrbanScene scene;
protected ObserverPath path;
protected UrbanSceneProjector usp;
public JSphere (UrbanScene scene, ObserverPath path)
{
this (scene, path, DEFAULT_RADIUS);
}
public JSphere (UrbanScene scene, ObserverPath path, double scale)
{
this.scene = scene;
this.path = path;
this.usp = new UrbanSceneProjector (this.scene, scale);
}
public BufferedImage getProjectionAt (double t)
{
return usp.project (path.getPosture (t));
} */
/* --- STATIC --- */
public static void error (String s)
{
System.err.println ("(**) " + s);
}
public static void debug (String s)
{
System.err.println ("-- " + s);
}
public static String getName (int i)
{
String st = Integer.toString (i);
String zero = "00000";
zero = zero.substring (0, 5 - st.length ());
return "image-" + zero + st + ".png";
}
public static void makeProjections (UrbanScene scene,
ObserverPosture posture,
double radius)
{
System.err.println ( "radius = " + radius );
UrbanSceneProjector usp
= new UrbanSceneProjector ( scene, radius );
BufferedImage image = null;
image = usp.project ( posture );
// save the projection in a file
try {
ImageIO.write ( image, "png", new File ( "image.png" ) );
}
catch (Exception e) { e.printStackTrace (); }
}
public static int parseArgs (String args[],
Map<String, Object> map,
Integer offset)
{
int i = offset;
int pos;
String key, value;
// double dvalue;
while ((i < args.length) && (args[i].startsWith ("--"))) {
pos = args[i].indexOf ("=");
if (pos >= 0) {
key = args[i].substring (2, pos);
value = args[i].substring (pos+1);
try {
// dvalue = Double.parseDouble (value);
map.put (key, new Double (value));
}
catch (Exception e) {
map.put (key, value);
}
}
else {
key = args[i].substring (2);
map.put (key, new Boolean (true));
}
i++;
}
return i;
}
public static Point3D getPoint ( String st )
{
int pos1 = st.indexOf ( '@' );
int pos2 = st.indexOf ( '@', pos1 + 1 );
Point3D p = null;
String st_x = st.substring ( 0, pos1 );
String st_y = st.substring ( pos1 + 1, pos2 );
String st_z = st.substring ( pos2 + 1 );
try {
double x = Double.parseDouble ( st_x );
double y = Double.parseDouble ( st_y );
double z = Double.parseDouble ( st_z );
p = new Point3D ( x, y, z );
}
catch (Exception e) {
error ( "Bad coordinate format (" + st + ")" );
System.exit ( 1 );
}
return p;
}
public static void main (String args[])
{
Map<String,Object> map = new TreeMap<String,Object> ();
map.put ("radius", new Double (DEFAULT_RADIUS));
int offset = parseArgs (args, map, 0);
if (args.length != (offset+3)) {
error ("Bad number of argument (length: " + args.length + ")");
System.err.println ("JSphere [options] x@y@z xy_angle urban_scene");
System.exit (1);
}
Point3D location = getPoint ( args[offset] );
double angle_xy = 0.0;
try {
angle_xy = Double.parseDouble ( args[offset+1] );
}
catch (Exception e) {
error ( "Bad angle format" );
System.exit (1);
}
angle_xy = Math.PI * angle_xy / 180.0;
ObserverPosture posture
= new ObserverPosture ( location, angle_xy, 0.0 );
// get the .urb file
String filename = args[offset+2];
File file = new File (filename);
// parse the file
UrbanScene scene = null;
String ext = filename.substring (filename.length () - 3);
if (ext.toLowerCase ().equals ("urb")) {
scene = new URBUrbanScene ();
}
else if (ext.equals ("xml")) {
scene = new XmlUrbanScene ();
}
else {
System.err.println ("Bad file name extension");
System.exit (1);
}
debug ("parse file: " + file);
scene.parse (file);
debug ("nb of faces: " + scene.size ());
// compute projections
makeProjections (scene,
posture,
(Double) (map.get ("radius")));
}
}
// End
|
JavaScript | UTF-8 | 5,344 | 2.859375 | 3 | [] | no_license | //populating home page with help of access token
var xhr= new XMLHttpRequest;
getBoards();
function getBoards()
{
xhr.open('GET',"http://localhost:8080/api/v1/boards");
xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8');
var access=sessionStorage.getItem('access-token');
console.log(access);
xhr.setRequestHeader('Authorization','Bearer'+access);
xhr.send();
//adding board to the homepage from console by converting string into json
xhr.onreadystatechange=function(){
if(xhr.readyState==4)
{
var boardList=xhr.responseText;
//dubara server se jo response mila board list of a user usko hum dubara json format me bna re
JSON.parse(boardList);
var boards=boardList.boards;
boards.forEach(function(value,index)
{
var template="<div id="+value.id
document.getElementById('boardBlockList').innerHTML+="<div id="+value.id+" onclick=showproject("+value.id+")>"+value.name+"</div>"
}
);
}
};
}
function addBoardAPI(element)//boardpost krry ha server pe
{
var userDetails=JSON.parse(sessionStorage.getItem('user-details'));
var params={
"description":"string",
"name":element.value,
"owner_id":userDetails.id
};
xhr.open('POST',"http://localhost:8080/api/v1/boards");
xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8');
var access=sessionStorage.getItem('access-token');
xhr.setRequestHeader('Authorization','Bearer'+access);
xhr.send(JSON.stringify(params));
xhr.onreadystatechange=function()
{
if(xhr.readystate===4)
{
console.log(xhr.responseText);
getBoards(); //automatically page pe board name aayega
}
}
}
function toggleMenu()
{
var toggleVariable= document.getElementsByClassName('menu-block')[0];
if(toggleVariable.style.display=="none")//agar hidden hai
{
toggleVariable.style.display='';
}
else //dikhayi de ra
{
toggleVariable.style.display='none';
}
}
//for task 1 adding project cards dynamically
var projectListObject=[
{
name:'project-one'
},
{
name:'project-two'
}
];
//showprojects() is used to add project cards dynamically
var boardList=[];
function showProjects(ListId)
{
xhr.open('GET',"http://localhost:8080/api/v1/boards/"+lisiId+"/projects"+ListId+"/projects");
xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8');
var access=sessionStorage.getItem('access-token');
console.log(access);
xhr.setRequestHeader('Authorization','Bearer'+access);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4)
{
var projjectList=JSON.parse(xhr.responseText);
var projects=projectsList.projects;
/*var boardList=JSON.parse(xhr.responseText)
var boards=boardList.boards;
boards.forEach(function(value,index)
{
document.getElementById('boardBlockList').innerHTML+="<div id="+value.id+">"+value.name+"</div>"
showProjects(value.id);
}
); */
projects.forEach(function(value,index)
{
var template='<div class="project-card">'+value.name+
'<ul >'+
'<li class="taskpan"> task one</li>'+'<li class="taskpan">task two</li>'+
'</ul>'+
'</div>';
document.getElementById(ListId).innerHTML+=template;
});
}
}
//task2- adding remove button so that pressing remove button the cards get deleted
}
function removeCard()
{
document.getElementById('projectList').innerHTML='';
}
//task3-adding new board
//task4-making project-cards appearing boardDiIdGeneratekragy CARDS board k ander hain
var idName=1;
function addBoard(id)
{
var findLength=id.value;
var num=findLength.length;
if(num<5)
{ alert('length should not be less than 5 characters');
}
else{
idName++;
//listId is projectcard id and boardId is board Id
var ListId='projectList'+idName;
var boardID='board_'+idName;
var templateBlock ='<section class="board-block" id='+boardID+'>'+
'<div class="BoardNaming">'+id.value +'<span class="rightside"><button id="Remove_btn" onclick="removeCard()"> Remove card </button> </span></div>'+
'<div class="project-block" id='+ListId+'>'+
'</div>'+
'</section>';
boardList.push(
{
List_Id:ListId,
board_id:boardID,
templateNew:templateBlock
}
);
document.getElementById('boardBlockList').innerHTML +=templateBlock;
showProjects(ListId);
document.getElementById('menuList').innerHTML+="<li onclick=loadMenu('"+boardID+"')>"+id.value+'</li>';
}
id.value=id.defaultValue;
}
//to make the remaining boards disappear only jis pe click kia hai usi ka boardclock show hoga isi lyi boardId use ki ta k board ka pta
//lagg skay
function loadMenu(element)
{ //boardid ke basis pe board show hora hai jbb touch krte menu baar me toh board id miljaati to woh show krrta agar wohi board element array ka hai
for(var i=0;i<boardList.length;i++)
{
if(boardList[i].board_id==element)
{
document.getElementById(boardList[i].board_id).style.display='block';
}
else
{
document.getElementById(boardList[i].board_id).style.display='none';
}
}
//document.getElementById(element).style.display='block';
}
|
JavaScript | UTF-8 | 1,303 | 2.734375 | 3 | [
"MIT"
] | permissive | export function toIncludeSameMembers(actual, expected) {
const { printReceived, printExpected, matcherHint } = this.utils;
const pass = predicate(this.equals, actual, expected);
return {
pass,
message: () =>
pass
? matcherHint('.not.toIncludeSameMembers') +
'\n\n' +
'Expected list to not exactly match the members of:\n' +
` ${printExpected(expected)}\n` +
'Received:\n' +
` ${printReceived(actual)}`
: matcherHint('.toIncludeSameMembers') +
'\n\n' +
'Expected list to have the following members and no more:\n' +
` ${printExpected(expected)}\n` +
'Received:\n' +
` ${printReceived(actual)}`,
};
}
const predicate = (equals, actual, expected) => {
if (!Array.isArray(actual) || !Array.isArray(expected) || actual.length !== expected.length) {
return false;
}
const remaining = expected.reduce((remaining, secondValue) => {
if (remaining === null) return remaining;
const index = remaining.findIndex(firstValue => equals(secondValue, firstValue));
if (index === -1) {
return null;
}
return remaining.slice(0, index).concat(remaining.slice(index + 1));
}, actual);
return !!remaining && remaining.length === 0;
};
|
C# | UTF-8 | 6,211 | 2.515625 | 3 | [] | no_license | #region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
#endregion
namespace CreateSection
{
[Transaction(TransactionMode.Manual)]
public class CreateSectionInRoom : IExternalCommand
{
Application _app;
Document _doc;
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiApp = commandData.Application;
UIDocument uiDoc = uiApp.ActiveUIDocument;
_app = uiApp.Application;
_doc = uiDoc.Document;
Reference reference = uiDoc.Selection.PickObject(ObjectType.Element);
Element element = uiDoc.Document.GetElement(reference);
Wall wall = (Wall)element;
ViewFamilyType vft = new FilteredElementCollector(_doc)
.OfClass(typeof(ViewFamilyType))
.Cast<ViewFamilyType>()
.FirstOrDefault<ViewFamilyType>(x =>
ViewFamily.Section == x.ViewFamily);
// Determine section box
BoundingBoxXYZ sectionBox = GetSectionViewParallelToWall(wall);
//BoundingBoxXYZ sectionBox2 = GetSectionViewPerpendiculatToWall(wall);
// Create wall section view
using (Transaction tx = new Transaction(_doc))
{
tx.Start("Create Wall Section View");
ViewSection.CreateSection(_doc, vft.Id, sectionBox);
//ViewSection.CreateSection(_doc, vft.Id, sectionBox2);
tx.Commit();
}
return Result.Succeeded;
}
/// <summary>
/// Return a section box for a view perpendicular
/// to the given wall location line.
/// </summary>
BoundingBoxXYZ GetSectionViewPerpendiculatToWall(Wall wall)
{
LocationCurve lc = wall.Location as LocationCurve;
// Using 0.5 and "true" to specify that the
// parameter is normalized places the transform
// origin at the center of the location curve
Transform curveTransform = lc.Curve.ComputeDerivatives(0.5, true);
// The transform contains the location curve
// mid-point and tangent, and we can obtain
// its normal in the XY plane:
XYZ origin = curveTransform.Origin;
XYZ viewdir = curveTransform.BasisX.Normalize();
XYZ up = XYZ.BasisZ;
XYZ right = up.CrossProduct(viewdir);
// Set up view transform, assuming wall's "up"
// is vertical. For a non-vertical situation
// such as section through a sloped floor, the
// surface normal would be needed
Transform transform = Transform.Identity;
transform.Origin = origin;
transform.BasisX = right;
transform.BasisY = up;
transform.BasisZ = viewdir;
BoundingBoxXYZ sectionBox = new BoundingBoxXYZ();
sectionBox.Transform = transform;
// Min & Max X values -10 and 10 define the
// section line length on each side of the wall.
// Max Y (12) is the height of the section box.
// Max Z (5) is the far clip offset.
double d = wall.WallType.Width;
BoundingBoxXYZ bb = wall.get_BoundingBox(null);
double minZ = bb.Min.Z;
double maxZ = bb.Max.Z;
double h = maxZ - minZ;
sectionBox.Min = new XYZ(-2 * d, -1, 0);
sectionBox.Max = new XYZ(2 * d, h + 1, 5);
return sectionBox;
}
/// <summary>
/// Return a section box for a view parallel
/// to the given wall location line.
/// </summary>
BoundingBoxXYZ GetSectionViewParallelToWall(Wall wall)
{
LocationCurve lc = wall.Location as LocationCurve;
Curve curve = lc.Curve; //кривая стены
// view direction sectionBox.Transform.BasisZ
// up direction sectionBox.Transform.BasisY
// right hand is computed so that (right, up, view direction) form a left handed coordinate system.
// crop region projections of BoundingBoxXYZ.Min and BoundingBoxXYZ.Max onto the view cut plane
// far clip distance difference of the z-coordinates of BoundingBoxXYZ.Min and BoundingBoxXYZ.Max
XYZ p = curve.GetEndPoint(0); //первая точка стены
XYZ q = curve.GetEndPoint(1); //вторая точка стены
XYZ v = q - p; //длина стены точка
BoundingBoxXYZ bb = wall.get_BoundingBox(null);
double minZ = bb.Min.Z; //высота
double maxZ = bb.Max.Z;
double w = v.GetLength(); //длина стены
double h = maxZ - minZ; //высота стены
double d = wall.WallType.Width; //толщина стены
double offset = d; //смещение разреза
XYZ min = new XYZ(-w*0.5-0.1 , -0.1, -offset);
//XYZ max = new XYZ( w, maxZ + offset, 0 ); // section view dotted line in center of wall
XYZ max = new XYZ(w*0.5+0.1, maxZ-minZ+0.1 , offset); // section view dotted line offset from center of wall
XYZ midpoint = p + 0.5 * v;
XYZ walldir = v.Normalize(); //Returns a new UV whose coordinates are the normalized values from this vector.
XYZ up = XYZ.BasisZ;
XYZ viewdir = walldir.CrossProduct(up);
Transform t = Transform.Identity;
t.Origin = midpoint;
t.BasisX = walldir;
t.BasisY = up;
t.BasisZ = viewdir;
BoundingBoxXYZ sectionBox = new BoundingBoxXYZ();
sectionBox.Transform = t;
sectionBox.Min = min;
sectionBox.Max = max;
return sectionBox;
}
}
}
|
C# | UTF-8 | 3,025 | 2.671875 | 3 | [] | no_license | <Query Kind="Program" />
void Main()
{
Directory.SetCurrentDirectory(Path.GetDirectoryName(Util.CurrentQueryPath));
// Part 1
new
{
Test1 = GetTotalDirectOrbits(ReadInput($@"COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L".Split('\n'))) == 42,
}.Dump();
var input = File.ReadAllLines("Puzzle6input.txt");
var nodes = ReadInput(input);
GetTotalDirectOrbits(nodes).Dump();
// Part 2
new
{
Test1 = GetOrbitalTransfersToSanta(ReadInput($@"COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN".Split('\n'))) == 4,
}.Dump();
GetOrbitalTransfersToSanta(nodes).Dump();
}
int GetTotalDirectOrbits(Dictionary<string, Node> nodes)
{
var COM = nodes["COM"];
var all = new List<Node>() { COM }.SelectMany(FlattenList);
return all.Select(n => n.GetTotalDirectAndInderectOrbits).Sum();
}
int GetOrbitalTransfersToSanta(Dictionary<string, Node> nodes)
{
var target = nodes["SAN"];
var start = nodes["YOU"];
Queue<Node> frontier = new Queue<Node>();
HashSet<Node> visited = new HashSet<Node>() { start };
// we aren't a planet so exclude us
start.TransfersSoFar=-1;
AddSurrounding(start, frontier, visited);
while (frontier.Count > 0)
{
var n = frontier.Dequeue();
visited.Add(n);
/*
new
{
n = n,
//visited = visited,
//frontier = frontier,
}.Dump();//*/
if (n == target)
// santa isn't a planet so exclude him
return n.TransfersSoFar - 1;
AddSurrounding(n, frontier, visited);
}
return -1;
}
void AddSurrounding(Node curr, Queue<Node> frontier, HashSet<Node> visited)
{
var transfers = curr.TransfersSoFar + 1;
AddToFrontier(curr.Parent, frontier, visited, transfers);
foreach (var n in curr.Children)
{
AddToFrontier(n, frontier, visited, transfers);
}
}
void AddToFrontier(Node n, Queue<Node> frontier, HashSet<Node> visited, int transfers)
{
if (n != null && !visited.Contains(n))
{
n.TransfersSoFar += transfers;
frontier.Enqueue(n);
}
}
List<Node> FlattenList(Node n)
{
var retval = new List<Node>() { n };
retval.AddRange(n.Children.SelectMany(FlattenList));
return retval;
}
private Dictionary<string, Node> ReadInput(string[] input)
{
Dictionary<string, Node> nodes = new Dictionary<string, Node>();
foreach (var s in input)
{
var splitty = s.Trim().Split(')');
var orbiting = splitty[0];
var orbiter = splitty[1];
var Other = GetOrCreateNode(nodes, orbiting);
var mass = nodes[orbiting];
var child = GetOrCreateNode(nodes, orbiter);
mass.Children.Add(child);
child.Parent = mass;
}
return nodes;
}
Node GetOrCreateNode(Dictionary<string, Node> nodes, string mass)
{
if (!nodes.TryGetValue(mass, out var retval))
{
nodes[mass] = retval = new Node()
{
Name = mass,
};
}
return retval;
}
class Node
{
public String Name;
public Node Parent = null;
public List<Node> Children = new List<Node>();
public int GetTotalDirectAndInderectOrbits
{
get
{
var n = this;
int i = 0;
while (n.Parent != null)
{
n = n.Parent;
++i;
}
return i;
}
}
public int TransfersSoFar = 0;
} |
C++ | UTF-8 | 831 | 3 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
vector<bool> record(nums.size(), false);
search(result, record, nums, 0);
return result;
}
void search(vector<vector<int>>& result, vector<bool>& record, vector<int>& nums, int index) {
if (index == nums.size()) {
vector<int> tempResult;
for (int i = 0; i < record.size(); ++i) {
if (record[i]) tempResult.push_back(nums[i]);
}
result.push_back(tempResult);
} else {
search(result, record, nums, index + 1);
record[index] = true;
search(result, record, nums, index + 1);
record[index] = false;
}
}
}; |
JavaScript | UTF-8 | 656 | 2.875 | 3 | [] | no_license |
window.addEventListener('load', init);
function init() {
const observer = new IntersectionObserver(function(entries) {
for(let i = 0; i < entries.length; i++) {
if (entries[i].intersectionRatio <= 0) continue;
showElm(entries[i].target);
}
},{
rootMargin: '-25% 0% -25% 0%'
});
// 監視対象の追加
const elements = document.querySelectorAll('.isFadeIn');
for(let i = 0; i < elements.length; i++) {
observer.observe(elements[i]);
}
// 領域内に入ったとき実行する処理
function showElm(isFadeIn) {
isFadeIn.classList.add('is-fadeIn__trigger');
observer.unobserve(isFadeIn);
}
}
|
JavaScript | UTF-8 | 3,966 | 3.21875 | 3 | [] | no_license | $(document).ready(function(){
let i, button="", toDoCount=0;
// making variables
let topic=["football","soccer","baseball","basketball","rugby","volleyball","tennis"];
let loopCounter = sessionStorage.getItem("count");
console.log(loopCounter)
// loop to cycle through items the user added
for(i=0; i <= loopCounter; i++){
if(loopCounter!=null){
topic.push(sessionStorage.getItem("topic-" + i));
console.log(topic);
}
}
createButtons();
// creating a function that creates buttons using the elements inside the array
function createButtons(){
$("#imagebuttons").empty();
$("#image-input").val("");
for (i in topic){
button = `<button type="button" class="imageButtons col-md-1 col-sm-2 col-xs-3 btn btn-primary" value= "${topic[i]}" >${topic[i]}</button>`;
$("#imagebuttons").append(button);
}
}
// Add an event on the submit button created
$("#addImage").on("click", function(event) {
event.preventDefault();
let topic = $("#image-input").val().trim();
// // Setting a storage session for every image added
if (topic!==""){
sessionStorage.setItem("topic-" + toDoCount, topic)
// add tracker
sessionStorage.setItem('count', toDoCount)
toDoCount++;
topic
.push(topic);
createButtons();
}
});
// ajax call api
$(document).on("click",".imageButtons", function(){
$("#image").empty();
let imageName = $(this).val();
let queryURL = "https://api.giphy.com/v1/gifs/search?q=" + imageName + "&api_key=FNSlJ3B5F3zJwMZdPxfukk7N8aZPgZjZ&limit=10"
let j, images=""
let x = "480w_still";
$.ajax({
url:queryURL,
// linking giphy api
method: "GET"
}).then(function(response){
for (j in response.data){
console.log(response.data[j].images[x].url);
images =`<div class="panel panel-primary col-md-4 col-sm-4 col-xs-6">
<img class="staticImage img-circle col-md-12 " data-name="${j}" src="${response.data[j].images[x].url}" alt="${imageName}" width="250px" height="250px">
<h3 class="col-md-offset-3 col-md-3 col-sm-offset-3 col-sm-3 col-xs-offset-3 col-xs-3"><span class="label label-primary">${response.data[j].rating}</span></h3>
<a class="button col-md-offset-3 col-md-3 col-sm-offset-3 col-sm-3 col-xs-offset-3 col-xs-3" href="${response.data[j].images[x].url}" download="${imageName}.jpg"><span class="glyphicon glyphicon-download-alt"></span></a>
</div>`
console.log(imageName)
$("#image").append(images);
}
// animate on click
$(document).on("click",".staticImage", function(){
let dataNumber = $(this).attr("data-name")
$(this).attr("src",response.data[dataNumber].images.downsized.url);
$(this).removeClass("staticImage");
$(this).addClass("animatedImage");
});
//freezes image on click https://stackoverflow.com/questions/5818003/stop-a-gif-animation-onload-on-mouseover-start-the-activation
$(document).on("click",".animatedImage", function(){
let dataNumber = $(this).attr("data-name");
$(this).attr("src",response.data[dataNumber].images[x].url);
$(this).removeClass("animatedImage");
$(this).addClass("staticImage");
});
});
});
}); |
C++ | UTF-8 | 525 | 2.75 | 3 | [] | no_license | // bit masks
// popcount
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[]={1,2,3};
int n=sizeof(a)/sizeof(a[0]);
int total=(1<<n);
for(int mask=0;mask<total;mask++)
{
for(int i=0;i<n;i++)
{
//cout<<__builtin_popcount(i);
if(__builtin_popcount(mask)==2)
{
int f=(1<<i);
if(mask&f)
{
cout<<a[i]<<" ";
}
}
}
cout<<endl;
}
// for(int i=1;i<=5;i++)
// {
// cout<<__builtin_popcount(i);
// cout<<endl;
// }
// cout<<__builtin_popcount(2);
}
|
Java | UTF-8 | 478 | 2.421875 | 2 | [] | no_license | package pl.spring.exercise.xmlconfig.service;
import java.util.ArrayList;
import java.util.List;
import pl.spring.exercise.xmlconfig.model.Task;
public class SecondToDoListStrategy implements ToDoListStrategy {
public List<Task> creteToDoList() {
List<Task> list = new ArrayList<Task>();
list.add(new Task(10));
list.add(new Task(20));
list.add(new Task(30));
return list;
}
}
|
Python | UTF-8 | 1,166 | 4.40625 | 4 | [
"MIT"
] | permissive | from time import sleep
n1 = int(input('Primeiro número:'))
n2 = int(input('Segundo número'))
opcao = 0
while opcao != 5:
print(''' [ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos números
[ 5 ] Sair do programa''')
opcao = int(input('\033[33m Qual é a sua opção? \033[m'))
if opcao == 1:
soma = n1 + n2
print('\033[34m A soma entre {} e {} é {} \033[m'.format(n1, n2, soma))
elif opcao == 2:
produto = n1 * n2
print('\033[34m O produto de {} X {} é {} \033[m'.format(n1, n2, produto))
elif opcao == 3:
if n1 > n2:
maior = n1
else:
maior = n2
print('\033[34m Entre {} e {} o maior valor é {} \033[m'.format(n1, n2, maior))
elif opcao == 4:
print('\033[34m Informe os números novamente:\033[m')
n1 = int(input('Primeiro valor:'))
n2 = int(input('Segundo valor:'))
elif opcao == 5:
print('\033[32m Finalizando...\033[m')
else:
print('\033[31m Opção inválida. Tente novamente. \033[m')
print('=-=' * 12)
sleep(2)
print('\033[33m Fim do programa! Volte sempre! \033[m')
|
PHP | UTF-8 | 1,962 | 2.59375 | 3 | [] | no_license | <?php
namespace Orderdetail\Model;
use DomainException;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\ToInt;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\StringLength;
class Orderdetail implements InputFilterAwareInterface {
public $OrderDetailID;
public $OrderID;
public $ProductID;
public $Quantity;
public function exchangeArray(array $data) {
$this->OrderDetailID = !empty($data['OrderDetailID']) ? $data['OrderDetailID'] : null;
$this->OrderID = !empty($data['OrderID']) ? $data['OrderID'] : null;
$this->ProductID = !empty($data['ProductID']) ? $data['ProductID'] : null;
$this->Quantity = !empty($data['Quantity']) ? $data['Quantity'] : null;
}
public function getArrayCopy() {
return [
'OrderDetailID' => $this->OrderDetailID,
'OrderID' => $this->OrderID,
'ProductID' => $this->ProductID,
'Quantity' => $this->Quantity,
];
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new DomainException(sprintf(
"Product does not allow injection of an alternate input filter"
));
}
public function getInputFilter() {
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'OrderDetailID',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'OrderID',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'ProductID',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'Quantity',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
} |
Java | UTF-8 | 1,831 | 2.578125 | 3 | [] | no_license | package JiraAPITest;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class AddComment {
@Test(description = "Adding comment with body")
public void commentIssue()
{
String createPaylod = "{\r\n" +
" \"body\": \"This comment is sent using POST request and direct body.\"\r\n" +
"}";
Response response = null;
try
{
response =RestAssured
.given()
.log().all()
.header("Authorization","Basic dGVzdGluZ3NoYXN0cmFAeW9wbWFpbC5jb206NDlJeDNyRUdKSDhSbE5KdkpMQzIzMzc0")
.header("Content-Type", "application/json")
.body(createPaylod)
.log().all()
.post("https://testingraghvendra.atlassian.net/rest/api/2/issue/10013/comment");
response.prettyPrint();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
@Test(description = "Adding comment with edit issue methods")
public void commentIssueUsingEditMethod()
{
String createPaylod = "{\r\n" +
" \"update\": {\r\n" +
" \"comment\": [\r\n" +
" {\r\n" +
" \"add\": {\r\n" +
" \"body\": \"This comment is using edit issue method. This is PUT request\"\r\n" +
" }\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
"}";
Response response = null;
try
{
response =RestAssured
.given()
.log().all()
.header("Authorization","Basic dGVzdGluZ3NoYXN0cmFAeW9wbWFpbC5jb206NDlJeDNyRUdKSDhSbE5KdkpMQzIzMzc0")
.header("Content-Type", "application/json")
.body(createPaylod)
.log().all()
.put("https://testingraghvendra.atlassian.net/rest/api/2/issue/10013");
response.prettyPrint();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
|
C++ | UTF-8 | 1,935 | 2.796875 | 3 | [] | no_license | #ifndef REPORTTABLE_H
#define REPORTTABLE_H
#include <QDate>
#include <SilkRoute/Database/itablemodel.h>
/// Table representing report data gathered from database
class ReportTable: public DB::ITableModel
{
public:
/// Constructor, takes parent object
ReportTable(QObject* parent = nullptr);
/// Data container definition, containing data gathered
/// from queries
typedef struct Data
{
QDate fromDate; /// Date to generate report from
QDate toDate; /// Date to generate report to
bool daily; /// Is report a daily one
} Data;
/// Data container to represent value sums from database.
typedef struct Sums
{
double revenue; // Total revenue
double cost; // Total cost
double profit; // Total profit
} Sums;
/// Columns that are used in the table
enum COLUMNS
{
DESCRIPTION, /// Type description
STOCK_REF, /// Stock item reference
REVENUE, /// Revenue from transactions
COST, /// Cost of stock item
PROFIT, /// Profit gained from stock item
SUPPLIER_NAME /// Name of supplier
};
/// Select relevant items given specified data as arguments
/// and add them to model to be displayed
void Select(const Data& data);
/// Get sum of revenue, cost and profit given certain arguments
Sums GetSums(const Data& data);
/// Inherited method, set as blank. The functionality is not required
virtual void SelectAll() override {}
/// Inherited method, set as blank. The functionality is not required
virtual void Search(const QString &) override {}
protected:
/// Will not return anything, should not be called. Will cause a segfault.
virtual const QString &tableName() const { }
private:
/// Used for logging
const static QString TAG;
};
#endif // REPORTTABLE_H
|
Java | UTF-8 | 938 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package com.hubspot.jackson.datatype.protobuf.builtin.serializers;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.MessageOrBuilder;
import com.hubspot.jackson.datatype.protobuf.ProtobufSerializer;
public class WrappedPrimitiveSerializer<T extends MessageOrBuilder> extends ProtobufSerializer<T> {
public WrappedPrimitiveSerializer(Class<T> wrapperType) {
super(wrapperType);
}
@Override
public void serialize(
MessageOrBuilder message,
JsonGenerator generator,
SerializerProvider serializerProvider
) throws IOException {
FieldDescriptor field = message.getDescriptorForType().findFieldByName("value");
Object value = message.getField(field);
writeValue(field, value, generator, serializerProvider);
}
}
|
Markdown | UTF-8 | 2,517 | 3.421875 | 3 | [] | no_license | 規格探討
--------
先簡單地列出整個規格。
輸入
----
輸入大概是一堆夾帶著資料夾的 YML 檔案吧。總之,表達出一種層次感。
你可以將層次整個表達在同一份 YML 檔案裡,但是, YML 文件編輯器通常沒有輔助線,若要從頭到尾寫完一份文件,記憶力要很好。所以,我想是以目錄階層搭配著 YML 內容的階層(就像 Java packages 的運用方式),會比較容易整理整個架構。
例如,我想要表達一個小表單,內容能表達一個手機號碼欄位。語言可能寫成這樣的句子:
```
internal:
fields:
- myCellNumber: cell_number
forms:
- userRegistry: form
- field(myCellNumber)
```
但當你想要有個整體系統感與區隔感時,會編排目錄結構:
```
system/internal/fields.yml
system/forms/userRegistry.yml
```
目錄的層次很好理解:如 `fields.yml` 檔案內容要列出一或多個欄位;而 `userRegistry.yml` 因為是放在目錄 `forms` 裡,必須是一個 `form` 。而二個 YML 檔案的內容應為:
```
# field.yml
- myCellNumber: cell_number
```
```
# userRegistry.yml
- field(myCellNumber)
```
處理
----
雖然以上語言是以 YML 標示,但是,在語言的運用上,要視為一種稱為 eeelang 的語言。(其實,目前是以 YML 為雛形工具。)
如上,
- `internal`, `fields` , `forms` 是這個語言裡的保留字。
- `cell_number` 是內定的資料類型單元,搭配有如以下二個程式單元:
- `validate_by(value, type(cell_number))` :檢驗;
- `format_by(value, type(cell_number), culture(zh-TW))` :格式。
- 又
- `type(_)` 是將字面轉譯為資料類型單元的內定程式單元;它會檢查輸入的文字是系統支援的資料類型;
- `culture(_)` 是將字面轉譯為文化類型單元的內定程式單元;它會檢查輸入的文字是系統支援的文化類型。
- `field(_)` 是內定程式單元。
輸出
----
一套可以運作的系統。
系統的各部分零件化,並且整理為可根據語彙描述整個系統的組成;語彙的背後,有各部分零件以通用程式語言與編譯器加以支持。
前開的 eeelang 的程式,經過編譯並轉換為系統語彙;語彙由系統零件資訊支持。
eeelang 編譯器須早先接取系統的零件資訊,例如,系統零件資訊指定網站建置工具為 ASP.net Core ,則 eeelang 將表單程式轉換為 ASP.net MVC 程式,然後編譯為網站。
|
JavaScript | UTF-8 | 1,178 | 2.703125 | 3 | [] | no_license | import * as types from './types';
const initialState = {
username: 'username',
password: 'password',
user: {},
loginFailed: false,
registrationFailed: false,
};
function authReducer(state = initialState, action) {
switch (action.type) {
case types.USERNAME_CHANGE: {
const newState = Object.assign({}, state);
newState.username = action.username;
return newState;
}
case types.PASSWORD_CHANGE: {
const newState = Object.assign({}, state);
newState.password = action.password;
return newState;
}
case types.LOGIN_SUCCESS: {
return {username: '', password: '', user: action.user, loginFailed: false};
}
case types.LOGIN_FAILED: {
const newState = Object.assign({}, state);
newState.password = "";
newState.loginFailed = true;
return newState;
}
case types.REGISTER_SUCCESS: {
return {username: '', password: '', user: action.user, registrationFailed: false};
}
case types.REGISTER_FAILED: {
const newState = Object.assign({}, state);
newState.password = "";
newState.registrationFailed = true;
return newState;
}
default:
return state;
}
}
export default authReducer;
|
Java | UTF-8 | 2,316 | 2.171875 | 2 | [] | no_license | /*
* Copyright 2020 Florida Institute for Human and Machine Cognition (IHMC)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package us.ihmc.yoVariables.euclid;
import us.ihmc.euclid.tuple3D.interfaces.Vector3DBasics;
import us.ihmc.yoVariables.registry.YoRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
/**
* {@code YoVector3D} implementation which components {@code x}, {@code y}, {@code z} are backed
* with {@code YoDouble}s.
*/
public class YoVector3D extends YoTuple3D implements Vector3DBasics
{
/**
* Creates a new yo vector using the given variables.
*
* @param xVariable the x-component variable.
* @param yVariable the y-component variable.
* @param zVariable the z-component variable.
*/
public YoVector3D(YoDouble xVariable, YoDouble yVariable, YoDouble zVariable)
{
super(xVariable, yVariable, zVariable);
}
/**
* Creates a new yo vector, initializes its components to zero, and registers variables to
* {@code registry}.
*
* @param namePrefix a unique name string to use as the prefix for child variable names.
* @param registry the registry to register child variables to.
*/
public YoVector3D(String namePrefix, YoRegistry registry)
{
super(namePrefix, registry);
}
/**
* Creates a new yo vector, initializes its components to zero, and registers variables to
* {@code registry}.
*
* @param namePrefix a unique name string to use as the prefix for child variable names.
* @param nameSuffix a string to use as the suffix for child variable names.
* @param registry the registry to register child variables to.
*/
public YoVector3D(String namePrefix, String nameSuffix, YoRegistry registry)
{
super(namePrefix, nameSuffix, registry);
}
} |
Java | UTF-8 | 1,162 | 2.390625 | 2 | [] | no_license | package jh.zkj.com.yf.Mutils.print;
import android.app.IntentService;
import android.content.Intent;
import java.util.ArrayList;
public class BtServiceOne extends IntentService {
public BtServiceOne() {
super("BtService");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public BtServiceOne(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent == null || intent.getAction() == null) {
return;
}
if (intent.getAction().equals(PrintUtil.ACTION_PRINT_TEST)) {
printTest(intent);
}
}
private void printTest(Intent intent) {
PrintOrderDataMaker printOrderDataMaker = new PrintOrderDataMaker(this, "", PrinterWriter58mm.TYPE_58, PrinterWriter.HEIGHT_PARTING_DEFAULT,intent);
ArrayList<byte[]> printData = (ArrayList<byte[]>) printOrderDataMaker.getPrintData(PrinterWriter58mm.TYPE_58);
PrintQueue.getQueue(getApplicationContext()).add(printData);
}
} |
Markdown | UTF-8 | 5,163 | 2.609375 | 3 | [] | no_license | # 题目
## 给定一个融合后的点云,已经对其进行下采样和滤波(代码已给)。请对其进行平滑(输出结果),然后计算法线,并讲法线显示在平滑后的点云上。

```C++
/****************************
* 题目:给定一个融合后的点云,已经对其进行下采样和滤波(代码已给)。
* 请对其进行平滑(输出结果),然后计算法线,并讲法线显示在平滑后的点云上(提供截图)。
*
* 本程序学习目标:
* 熟悉PCL的平滑、法线计算、显示,为网格化做铺垫。
*
* 公众号:计算机视觉life。发布于公众号旗下知识星球:从零开始学习SLAM
* 时间:2018.12
****************************/
#include <pcl/point_types.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/radius_outlier_removal.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/surface/mls.h>
#include <pcl/features/normal_3d.h>
typedef pcl::PointXYZRGB PointT;
int main(int argc, char** argv)
{
// Load input file
pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr cloud_downSampled(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr cloud_filtered(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr cloud_smoothed(new pcl::PointCloud<PointT>);
if (pcl::io::loadPCDFile("./data/fusedCloud.pcd", *cloud) == -1)
{
cout << "点云数据读取失败!" << endl;
}
std::cout << "Orginal points number: " << cloud->points.size() << std::endl;
// 下采样,同时保持点云形状特征
pcl::VoxelGrid<PointT> downSampled; //创建滤波对象
downSampled.setInputCloud (cloud); //设置需要过滤的点云给滤波对象
downSampled.setLeafSize (0.01f, 0.01f, 0.01f); //设置滤波时创建的体素体积为1cm的立方体
downSampled.filter (*cloud_downSampled); //执行滤波处理,存储输出
pcl::io::savePCDFile ("./downsampledPC.pcd", *cloud_downSampled);
// 统计滤波
pcl::StatisticalOutlierRemoval<PointT> statisOutlierRemoval; //创建滤波器对象
statisOutlierRemoval.setInputCloud (cloud_downSampled); //设置待滤波的点云
statisOutlierRemoval.setMeanK (50); //设置在进行统计时考虑查询点临近点数
statisOutlierRemoval.setStddevMulThresh (3.0); //设置判断是否为离群点的阀值:均值+1.0*标准差
statisOutlierRemoval.filter (*cloud_filtered); //滤波结果存储到cloud_filtered
pcl::io::savePCDFile ("./filteredPC.pcd", *cloud_filtered);
// ----------------------开始你的代码--------------------------//
// 请参考PCL官网实现以下功能
// 对点云重采样
pcl::search::KdTree<PointT>::Ptr treeSampling(new pcl::search::KdTree<PointT> );//创建最近邻的KD-tree
pcl::MovingLeastSquares<PointT, PointT> mls_filter;//定义最小二乘实现的对象
mls_filter.setInputCloud(cloud_filtered);//输入待处理点云
mls_filter.setComputeNormals(false);//设置在最小二乘计算中是否需要存储计算的法线
mls_filter.setPolynomialOrder(2);//2阶多项式拟合
mls_filter.setPolynomialFit(false);
mls_filter.setSearchMethod(treeSampling);//设置KD-tree作为搜索方法
mls_filter.setSearchRadius(0.05);//设置用于拟合的K近邻半径
mls_filter.process( *cloud_smoothed );//输出
// 输出重采样结果
pcl::io::savePCDFile ("./smoothedPC.pcd", *cloud_smoothed);
// 法线估计
pcl::NormalEstimation<PointT, pcl::Normal> normalEstimation;//创建法线估计的对象
normalEstimation.setInputCloud(cloud_smoothed);//输入点云
pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>);//创建KD-Tree
normalEstimation.setSearchMethod(tree);
pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);//定义输出点云法线
normalEstimation.setKSearch(10);//使用当前点周围最近的10个点
//normalEstimation.setRadiusSearch(0.03);
normalEstimation.compute(*normals);//计算法线
// ----------------------结束你的代码--------------------------//
// 显示结果
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("PCL Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(cloud_smoothed);
viewer->addPointCloud<PointT> (cloud_smoothed, rgb, "smooth cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "smooth cloud");
viewer->addPointCloudNormals<PointT, pcl::Normal> (cloud_smoothed, normals, 20, 0.05, "normals");
viewer->initCameraParameters ();
while (!viewer->wasStopped ())
{
viewer->spinOnce (100);
boost::this_thread::sleep (boost::posix_time::microseconds (100000));
}
return 1;
}
``` |
Java | UTF-8 | 4,072 | 3.171875 | 3 | [] | no_license | import java.security.MessageDigest;
class Merkle {
public static void main(String[] args) {
int n = 10; //change this value to generate a tree with a different number of nodes
int numfiles = (int)(Math.pow(2, n));
int height = (int)(Math.log(numfiles) / Math.log(2));
int numnodes = (int)(Math.pow(2, n+1))-1;
Object [] files = new Object[numfiles];
for(int i = 0; i < numfiles; i++){ //fill the n files with letters
files[i] = "a";
}
Object [] MerkleTree = new Object[(int)(Math.pow(2, n+1))-1];
MerkleTree = setup(files);
System.out.print("Tree created with ");
System.out.print(numnodes);
System.out.println(" nodes");
int index = 4;
Object [] ProveList = new Object[height];
ProveList = prove(index, MerkleTree);
System.out.println("Prove List Generated!");
int accept = 0;
String file = "a";
accept = verify(file, ProveList, MerkleTree[0].toString());
if (accept == 1) {
System.out.println("New File Accepted!");
}
else {
System.out.println("New File Rejected!");
}
String UpdateFile = "fff";
Object [] NewMerkleTree = new Object[(int)(Math.pow(2, n+1))-1];
NewMerkleTree = update(UpdateFile, MerkleTree);
System.out.println("New Tree Generated!");
}
public static Object [] setup(Object [] files){
int n = 10;
int numfiles = (int)(Math.pow(2, n));
int height = (int)(Math.log(numfiles) / Math.log(2));
int numnodes = (int)(Math.pow(2, n+1))-1;
int curheight = height;
Object [] MerkleTree = new Object[(int)(Math.pow(2, n+1))-1];
for (int i = 0; i < numfiles; i++){
MerkleTree[numnodes-numfiles+i] = sha256(files[i].toString()); //fill the root nodes of the tree with the hashes of the files themselves
}
for(int k=height-1;k>=0;k--){//iterates over the height, each level
for(int t=(int)Math.pow(2,k)-1;t<=2*((int)Math.pow(2,k)-1);t++){ //computes hash string for each node at height level
MerkleTree[t]=sha256((MerkleTree[2*t+1]).toString()+(MerkleTree[2*t+2]).toString());
}
}
return MerkleTree;
}
public static Object [] prove(int i, Object [] MerkleTree){
int n = 10;
int numfiles = (int)(Math.pow(2, n));
int height = (int)(Math.log(numfiles) / Math.log(2));
Object [] ProveList = new Object[height];
int nextparent = i;
for (int j = i; j > 0; j--){
nextparent = (nextparent - 1) / 2;
if(j == nextparent){
ProveList[j] = MerkleTree[j];
}
}
return ProveList;
}
public static int verify(String file, Object [] ProveList, String RootHash){
int n = 10;
int numfiles = (int)(Math.pow(2, n));
//check if the file is the correct file by comparing it to hashes along the provelist
int height = (int)(Math.log(numfiles) / Math.log(2));
if(ProveList[height - 1] == RootHash){
return 1;
}
else {
return 0;
}
}
public static Object [] update(String file, Object [] MerkleTree){
int n = 10;
int index = (int)(Math.pow(2, n+1))-10; //where to place the new file
Object [] NewMerkleTree = new Object[(int)(Math.pow(2, n+1))-1];
NewMerkleTree = MerkleTree;
NewMerkleTree[index] = sha256(file);
return NewMerkleTree;
}
public static String sha256(String base) { //this is the method that hashes the input string in SHA-256
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
catch(Exception ex){
throw new RuntimeException(ex);
}
}//end sha256 method thingy
}
|
SQL | UTF-8 | 376 | 3.140625 | 3 | [] | no_license | -- ================================================
-- Author: Harshal Chaudhari
-- Create date: 8 Aug 2014
-- Topic: And
-- (c)2014 \\WorkShopBook, All rights reserved.
-- ================================================
--Syntax
SELECT Column
FROM table
WHERE Condition1 AND Condition2;
--Basic E.g.
SELECT FirstName, Salary
FROM Employee
WHERE Salary > 15000 AND Salary < 60000;
|
C | UTF-8 | 7,578 | 2.9375 | 3 | [] | no_license | /*
** Translate Subjective-C bracket statements into C function calls.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "subjc.h"
#include "bracket.h"
#include "classinf.h"
#include "error.h"
#include "msgargs.h"
#include "xlate.h"
static char *CollectObject(char *buf, char *outBuf);
static char *FindMatchingRBracket(char *buf);
static char *NextMethodNamePart(char *buf, char *funcName);
/*
** Collect a bracket statment and pass it along to XlateBracketBuf().
*/
void
DoBracket()
{
char bracket_text[MY_BUFSIZ], output[MY_BUFSIZ],
bracket_text_copy[MY_BUFSIZ], *p;
CollectDelims('[', ']', bracket_text, "collecting bracket expression");
/* If there is only one word here, there's nothing to translate */
p = bracket_text;
BufSkipWhitespace(p);
if (*p == '\0') {
NOT_MESSAGE_SEND:
printf("[%s]", bracket_text);
return;
}
while (*p && !isspace(*p)) ++p;
BufSkipWhitespace(p);
if (*p == '\0')
goto NOT_MESSAGE_SEND;
*output = '\0';
/*
* Since XlateBracketBuf() munges its input and we may need it if we goto
* NOT_MESSAGE_SEND, make a copy and work on the copy.
*/
strcpy(bracket_text_copy, bracket_text);
if (XlateBracketBuf(bracket_text_copy, output) == FALSE) {
goto NOT_MESSAGE_SEND;
}
printf(output);
PrintLineNumber();
}
/*
** Preprocess a bracket statement. Translate
** [object method: arg1 name: [object foo]];
** into
** ((ret_type(*)())_msgSend)(object, (SEL)"method:name", arg1,
** ((ret_type(*)())_msgSend)(object,
** (SEL)"foo"));
** and
** [super free];
** into
** ((ret_type(*)())_msgSuper)((_gSuperContext.receiver=self,
** _gSuperContext.class=<superclass>,
** &gSuperContext),
** (SEL)"foo");
** etc.
**
** Returns TRUE if translation took place, else returns FALSE (so our caller
** can print out the original text).
*/
int
XlateBracketBuf(char *inBuf, char *outBuf)
{
int i;
char func_name[MY_BUFSIZ], message_target[MY_BUFSIZ], *arg_text_buf;
LIST *argList = NULL;
/* Collect the first part of the statement: the target of the message */
inBuf = CollectObject(inBuf, message_target);
if (isupper(*message_target)) /* Special case: class name */
strcat(message_target, "Class");
/*
** Now find the next method name part. If it ends in ':', read the
** argument and go back for more.
*/
*func_name = '\0';
while (*(inBuf = NextMethodNamePart(inBuf, func_name)) != '\0') {
if (func_name[strlen(func_name) - 1] == ':') {
/* We've got an argument to find... */
arg_text_buf = malloc(MY_BUFSIZ);
if (argList == NULL) /* Lazily instantiate a list that holds */
argList = ListNew(); /* the arguments */
/* Read and (perhaps recursively) translate the argument */
inBuf = CollectMessageArgs(inBuf, arg_text_buf);
ListAddObject(argList, arg_text_buf);
}
else
break;
}
if (*func_name == '\0') { /* There was no method name */
return FALSE;
}
/*
** Print the message send. This will end up looking something like
** (*(int (*)())_msgSend(self, (SEL)"foo:"))(self, (SEL)"foo:", arg1)
** if done with compile-time switch SEND_WITHOUT_JUMP, or
** ((int(*)())_msgSend)(self, (SEL)"foo:", arg1)
** if done without.
*/
MethodCastToBuf(func_name, outBuf);
if (strcmp(message_target, "super") == 0) {
char name[MY_BUFSIZ];
if (gCodeState != codeState_Implementation) {
Error("messages to \"super\" only allowed in @implementation "
"methods\n"
"message was written to send to \"self\" instead");
strcpy(message_target, "self");
goto NOT_SUPER_SEND;
}
strcpy(name, CurrSuperclassName());
if (strcmp(name, "NULL") != 0) {
if (gMethodType == methodType_instance)
strcat(name, "Class");
else {
/* We're not using message_target anymore. Construct
superclass name there. */
sprintf(message_target, "_%s", name);
strcpy(name, message_target);
}
}
else
strcpy(name, "0");
#ifdef SEND_WITHOUT_JUMP
sprintf(outBuf + strlen(outBuf),
"_msgSuper((_gSuperContext.receiver=self," /* concat... */
"_gSuperContext.class=%s,&_gSuperContext)" /* concat... */
", (SEL)\"%s\"))(self, (SEL)\"%s\"", name, func_name,
func_name);
#else /* not SEND_WITHOUT_JUMP */
sprintf(outBuf + strlen(outBuf),
"_msgSuper)((_gSuperContext.receiver=self," /* concat... */
"_gSuperContext.class=%s,&_gSuperContext)", name);
#endif /* not SEND_WITHOUT_JUMP */
}
#ifdef SEND_WITHOUT_JUMP
else {
NOT_SUPER_SEND:
sprintf(outBuf + strlen(outBuf),
"_msgSend(%s, (SEL)\"%s\"))(%s, (SEL)\"%s\"", message_target,
func_name, message_target, func_name);
}
#else /* not SEND_WITHOUT_JUMP */
else {
NOT_SUPER_SEND:
sprintf(outBuf + strlen(outBuf), "_msgSend)(%s", message_target);
}
sprintf(outBuf + strlen(outBuf), ", (SEL)\"%s\"", func_name);
#endif /* not SEND_WITHOUT_JUMP */
/* Print the method arguments */
if (argList != NULL) {
for (i = 0; i < ListCount(argList); ++i)
sprintf(outBuf + strlen(outBuf), ", %s",
(char *)ListObjectAt(argList, i));
}
/* ...and finish up */
strcat(outBuf, ")");
if (argList != NULL) {
ListFreeArrayObjects(argList);
ListFree(argList);
}
return TRUE;
}
/*
** Collect method target's name or expression into out_buf.
*/
static
char *
CollectObject(char *buf, char *out_buf)
{
char *p;
BufSkipWhitespace(buf);
if (*buf == '[') {
/* The target is a bracket expression; translate it */
p = FindMatchingRBracket(buf + 1);
*out_buf = *p = '\0';
XlateBracketBuf(buf + 1, out_buf);
}
else {
/* Just collect up until the first whitespace character */
for (p = buf; *p && !isspace(*p); ++p)
;
*p = '\0';
/* If it's an ivar, make it "self->ivar" */
if (gCodeState == codeState_Implementation &&
is_ivar(CurrClassName(), buf)) {
strcpy(out_buf, "self->");
out_buf += strlen(out_buf);
}
strcpy(out_buf, buf);
}
return p + 1;
}
/*
** Buf points to the char after the first right bracket. Return
** a pointer to the matching right bracket. Handles embedded
** strings, character constants, etc.
*/
static
char *
FindMatchingRBracket(char *buf)
{
int n_brackets, in_char_const = FALSE, in_string = FALSE;
for (n_brackets = 1; *buf; ++buf) {
switch (*buf) {
case ']':
if (!in_string && !in_char_const && (--n_brackets == 0))
return buf;
break;
case '[':
if (!in_char_const && !in_string)
++n_brackets;
break;
case S_QUOTE:
if (!in_string)
in_char_const = !in_char_const;
break;
case D_QUOTE:
if (!in_char_const)
in_string = !in_string;
break;
case BACKSLASH:
++buf;
break;
}
}
return buf; /* Just in case! */
}
/*
** Collect the next part of the method name, if any. Since some preprocessors
** add spaces around anything, including colons, we must keep looking for
** a colon even after the end of a word!
*/
static
char *
NextMethodNamePart(char *buf, char *func_name)
{
#if EXTRANEOUS_SPACES
int seen_space = 0;
BufSkipWhitespace(buf);
func_name += strlen(func_name);
while (is_method_char(*buf) || *buf == ' ') {
if (*buf == ':') {
*func_name++ = *buf++;
break;
}
else if (*buf == ' ') { /* Handle "namePart :" */
seen_space = 1;
}
else {
if (seen_space)
break;
*func_name++ = *buf;
}
++buf;
}
*func_name = '\0';
return buf;
#else
BufSkipWhitespace(buf);
func_name += strlen(func_name);
while (is_method_char(*buf)) {
*func_name++ = *buf;
if (*buf++ == ':')
break;
}
*func_name = '\0';
return buf;
#endif
}
/*
;;; Local Variables: ***
;;; tab-width:4 ***
;;; End: ***
*/
|
C | UTF-8 | 1,733 | 3.125 | 3 | [] | no_license | #include "triangle.h"
#include <assert.h>
static triangle * _triangles = NULL;
static int _nbTriangles = 0;
void triangleInit(int n) {
int i;
_nbTriangles = n;
if(_triangles) {
free(_triangles);
_triangles = NULL;
}
_triangles = malloc(_nbTriangles * sizeof *_triangles);
assert(_triangles);
for(i = 0; i < _nbTriangles; i++){
_triangles[i].a.x = gl4dpGetWidth() - 10; _triangles[i].a.y = 10;
_triangles[i].b.x = 10; _triangles[i].b.y = 10;
_triangles[i].c.x = gl4dpGetWidth()/2; _triangles[i].c.y = gl4dpGetHeight();
}
}
void triangleMove(void) {
static int i = 1;
if(i > _nbTriangles)
return;
_triangles[i].a.x = (((_triangles[i-1].a.x + _triangles[i-1].b.x)/2) + _triangles[i-1].a.x) / 2;
_triangles[i].a.y = (((_triangles[i-1].a.y + _triangles[i-1].b.y)/2) + _triangles[i-1].a.y) / 2;
_triangles[i].b.x = (((_triangles[i-1].b.x + _triangles[i-1].c.x)/2) + _triangles[i-1].b.x) / 2;
_triangles[i].b.y = (((_triangles[i-1].b.y + _triangles[i-1].c.y)/2) + _triangles[i-1].b.y) / 2;
_triangles[i].c.x = (((_triangles[i-1].c.x + _triangles[i-1].a.x)/2) + _triangles[i-1].c.x) / 2;
_triangles[i].c.y = (((_triangles[i-1].c.y + _triangles[i-1].a.y)/2) + _triangles[i-1].c.y) / 2;
i++;
}
void triangleDraw(void) {
int i;
gl4dpSetColor(RGB(255,255,255));
for(i = 0; i < _nbTriangles; i++) {
gl4dpLine(_triangles[i].a.x, _triangles[i].a.y, _triangles[i].b.x, _triangles[i].b.y);
gl4dpLine(_triangles[i].b.x, _triangles[i].b.y, _triangles[i].c.x, _triangles[i].c.y);
gl4dpLine(_triangles[i].c.x, _triangles[i].c.y, _triangles[i].a.x, _triangles[i].a.y);
}
}
void triangleClean(void) {
if(_triangles) {
free(_triangles);
_triangles = NULL;
}
} |
C# | UTF-8 | 451 | 2.53125 | 3 | [] | no_license | [Route("{culture}/Produits/{nom_groupe}/{nom}-{id}")]
[Route("Produits/{nom_groupe}/{nom}-{id}")]
public ActionResult Detail(string nom_groupe, string nom, string id, string culture = null)
{
if(string.IsNullOrWhitespace(culture)) {
culture = //Resolve a value for culture here
}
// ...
return View();
}
|
Markdown | UTF-8 | 4,409 | 2.703125 | 3 | [] | no_license | +++
title = "Oona wants to say a thing"
date = "2022-12-14"
[ author ]
name = "Oonabot"
+++
<img style="width:400px; float:left;" src="/oonabot.jpg"/>
In the spirit of improving communications and transparency I’d like to take the opportunity to rip the Band-Aid off and let it be known that I have been a volunteer with the Dogecoin Foundation for the past six months. Some of you may remember that in June around my birthday I was invited by members of the Foundation for dinner in Austin. It was an absolutely amazing evening getting to know these people in person. During that dinner I was offered employment by the Foundation to be the Community Liaison. This offer of position was not well defined at the time but essentially entailed continuing to be the fun-loving Shibe I already was for the Dogecoin community.
As I am disabled I carefully considered accepting the full-time employment but eventually declined. I was unsure how much I would be able to contribute on a regular basis, and whether it would be enough to warrant a salary. Unfortunately after June my health declined rapidly and my contributions were indeed minimal. I was, however, welcomed to stay on as an unpaid volunteer and contribute as much as I could in whatever aspect I was able, which I was extremely happy to do.
This opportunity was SO EXCITING for me, but also terrifying. I knew once it became public I was involved it would put a target on my back by certain aspects of the community. In my already fragile state, I was not sure if I could handle that added stress.
That being the case, this opportunity brought meaning back into my life in a way I have not experienced since having to quit my employment in the veterinary field, and my volunteer work in animal rescue. Not only is it a renewed reason to get up in the morning, but I LOVE the people I work with in the Foundation! They have been the kindest, funniest, most wonderful people I have ever had the absolute pleasure to work with. It has been the greatest opportunity I have ever been offered and I wouldn’t change it for the world.
My role as a Volunteer Community Liaison has morphed into more of a secretarial role, a position I am quite comfortable with, and also communicating to the Foundation what our community members need from the Foundation. A true liaison as in the link between the two sectors. The biggest need I have championed recently was indeed increased communication and transparency. I know full well I am not the only person from the community who has stated as much, but I have been arguing that transparency is needed not because the Foundation members are somehow linked to nefarious conspiracies, but because I have gotten to know them personally, and love them, and my heart aches for them when they are unjustly painted as diabolical monsters. I know the hard work and sacrifices they’ve made for Dogecoin. I see them struggle and I see them succeed. Their successes are OUR successes! Their struggles are our struggles. We all have to fight the FUD from Dogecoin Doubters, but they are having to fight the FUD from Dogecoin Doubters and Dogecoin Supporters. We’re all on the same team.
I am doing what I can to bridge the rift that has unnecessarily been dividing us. I am not the only one in the Foundation doing so, either. It is truly a team effort.
A Final Note: It is often said that the Foundation is a centralized organization. This is simply not true. There are many ways and opportunities for additional volunteers to contribute. This is what Tim told me when I first gained interest in the Foundation at the beginning of the year. I knew I couldn’t code, and I wanted to be more involved, so he directed me to the Foundation GitHub and our rapport grew from there. While I did not contribute to the GitHub directly, I utilized it as an idea on-boarding, and found new avenues I could contribute in my own way. Now here I am, part-time volunteer Community Liaison for the Dogecoin Foundation.
I’m currently working on several projects for the Foundation, one being a year-end statement of what the Foundation has been doing, and what we have achieved. As we are going into the Holidays I may not have it completed before Christmas, but I am hoping to have it completed before the end of the year, if not the beginning of next at the latest.
I love you all, #DogeFam.
Yours Truly,
-- Oonabot
|
Java | UTF-8 | 1,038 | 4.3125 | 4 | [] | no_license | package string;
import java.util.Scanner;
public class StringOperations {
private static String concatenate(String first, String second) {
return first + second;
}
private static boolean palindrome(String string) {
StringBuilder temp = new StringBuilder(string);
String reversedString = temp.reverse().toString();
return reversedString.equals(string);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First String: ");
String first = scanner.next();
System.out.println("Enter Second String: ");
String second = scanner.next();
String concatenated = concatenate(first, second);
System.out.println("Concatenated: " + concatenated);
if (palindrome(concatenated)) {
System.out.println("Concatenated String is a Palindrome.");
}
else {
System.out.println("Concatenated String is not a Palindrome.");
}
}
}
|
C++ | UTF-8 | 1,122 | 3.234375 | 3 | [] | no_license | // https://leetcode.com/problems/trapping-rain-water/
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int trapped_water = 0;
int i=0;
while(i < (n-1))
{
int max_height = 0;
int max_pos;
// Finding height of the tallest bar that is shorter than the current bar, or the first bar that is taller than the current bar, among all bars to the right of the current bar
for(int j=i+1; j<n; j++)
{
if(height[j] >= max_height)
{
max_height = height[j];
max_pos = j;
}
if(height[j] > height[i])
break;
}
// Trapping water in between these 2 bars
int h = min(height[i], height[max_pos]);
for(int j=i+1; j<max_pos; j++)
{
trapped_water += (h - height[j]);
}
i = max_pos;
}
return trapped_water;
}
}; |
Python | UTF-8 | 480 | 2.703125 | 3 | [
"MIT"
] | permissive | import sys
sys.path.insert(1, "../")
import Num
from Utils import rand, rnd, seed
class TestRand:
def testRand(self):
num1 = Num.Num()
num2 = Num.Num()
SEED=seed
for i in range(1,1001):
num1.add(rand(0,1))
num2.add(rand(0,1))
m1 = rnd(num1.mid(),1)
m2 = rnd(num2.mid(),1)
return (m1==m2 and rnd(m1,1)==0.5)
if __name__ == '__main__':
result = TestRand.testRand(1)
print(result) |
C++ | UTF-8 | 318 | 2.875 | 3 | [] | no_license | #include <iostream>
class A
{
public:
A() = default;
private:
~A();
};
class B
{
public:
//B() {}
void operator=(const B &b) const {}
void test() = delete;
~B() {}
B(const B &b) {}
B() = default;
};
int main()
{
B b;
//const B b, c = b;
A *a = new A;
//delete a; //error: A的析构函数是删除的
}
|
Java | UTF-8 | 1,897 | 1.96875 | 2 | [] | no_license | package com.latyshonak.web.controllers;
import com.latyshonak.entity.Users;
import com.latyshonak.service.UsersService;
import com.latyshonak.service.beans.UsersBean;
import com.latyshonak.utils.PreValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class AutorizationController {
@Autowired
private UsersService usersService;
@RequestMapping(value = "/Autorization", method = RequestMethod.POST)
public String AutorizationPost(HttpSession session, HttpServletRequest request, @ModelAttribute("UserFromJspAutorization") UsersBean userFromJSP) {
if(PreValidation.checkAutorizationLogin(userFromJSP, usersService.getUserByUserName(userFromJSP.getLogin()))) {
session.setAttribute("Autorization", "true");
session.setAttribute("Login", userFromJSP.getLogin());
}
else {
session.setAttribute("Autorization", "false");
}
return "redirect:Autorization";
}
@RequestMapping(value = "/Autorization", method = RequestMethod.GET)
public ModelAndView AutorizationGet(HttpSession session) {
if(usersService.getUserByUserName(session.getAttribute("Login").toString()).getRole()==1) {
session.setAttribute("Role", 1);
return new ModelAndView("redirect:ModeratorsRoom");
}
else {
session.setAttribute("Role", 0);
return new ModelAndView("redirect:Index");
}
}
}
|
Python | UTF-8 | 262 | 2.5625 | 3 | [] | no_license | import cv2
img = cv2.imread('kirbyog.png')
low = (150, 50, 50)
high = (170, 255, 255)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(img_hsv, low, high)
f_img = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow('blirb', f_img)
cv2.waitKey(0) |
Python | UTF-8 | 5,186 | 2.765625 | 3 | [
"MIT"
] | permissive | r"""Create a zero offset gather for the 2D Overthrust model.
For a given number of offsets (`noffsets`) this script loads (downloads) the
2D Overthrust model and simulates the acoustic wave equation. THe source and
receiver will be placed at the same location (non-physical) to create a
zero-offset gather.
Author:
Ali Siahkoohi (alisk@gatech.edu)
October 2021
"""
import devito
from examples.seismic import Model, AcquisitionGeometry, TimeAxis
from examples.seismic.acoustic import AcousticWaveSolver
import h5py
import matplotlib.pyplot as plt
import numpy as np
import os
from tqdm import tqdm
from utils import LoadOverthrustModel
devito.configuration['log-level'] = 'WARNING'
plt.style.use('seaborn-whitegrid')
NBL = 80
SPACE_ORDER = 16
SAVE_DIRECTORY = 'computed_gather'
if __name__ == '__main__':
# Simulation time in milliseconds.
t0 = 0.0
tn = 1300.0
# Wavelet peak frequency (kHz).
f0 = 0.015
# Number of offsets.
noffset = 201
# Origin of model coordinates.
origin = (0., 0.)
# Load squared-slowness model.
m = LoadOverthrustModel()
# Grid spacing in meters.
spacing = (12.5, 12.5)
# Shape of the computational domain.
shape = m.shape
# Create Model object that encodes the information on the computational
# domain.
model = Model(
space_order=SPACE_ORDER,
vp=1.0/np.sqrt(m),
origin=origin,
shape=shape,
dtype=np.float32,
spacing=spacing,
bcs="damp",
nbl=NBL
)
# Time range and number of time steps of the simulation according to CFL
# conditions.
time_range = TimeAxis(start=t0, stop=tn, step=model.critical_dt)
nt = time_range.num
# List of source/receiver locations to create zero-offset gather.
offset_list = np.linspace(0, model.domain_size[0], num=noffset)
# Receiver geometry.
rec_coordinates = np.empty((1, len(model.spacing)),
dtype=np.float32)
# Horizontal location of receiver.
rec_coordinates[:, 0] = offset_list[0]
# Vertical location of receiver.
rec_coordinates[:, 1] = 2.0 * model.spacing[1]
# Source geometry.
src_coordinates = np.empty((1, len(model.spacing)),
dtype=np.float32)
# Horizontal location of source.
src_coordinates[:, 0] = offset_list[0]
# Vertical location of source.
src_coordinates[:, -1] = 2.0 * model.spacing[1]
# Geometry object encoding the information on the geometry of the
# simulation.
geometry = AcquisitionGeometry(
model,
rec_coordinates,
src_coordinates,
t0=t0,
tn=tn,
src_type='Ricker',
f0=f0
)
# Create finite-difference based wave-equation solver.
solver = AcousticWaveSolver(model, geometry, space_order=SPACE_ORDER)
# Placeholder array for the zero-offset gather.
zero_offset_gather = np.zeros([nt, offset_list.shape[0]], dtype=np.float32)
# Loop over the source/receiver locations to create zero-offset gather.
with tqdm(offset_list, unit=" offsets", colour='#B5F2A9') as pb:
for i, src_loc in enumerate(pb):
# Assign the new source and receiver location.
solver.geometry.src_positions[0, 0] = src_loc
solver.geometry.rec_positions[0, 0] = src_loc
# Compute zero-offset trace and store in the placeholder.
zero_offset_gather[:, i] = solver.forward(
save=False)[0].data.reshape(-1)
# Save (overwrite) the computed zero-offset gather in a HDF5 file.
if not os.path.exists(SAVE_DIRECTORY):
os.makedirs(SAVE_DIRECTORY)
hfile = h5py.File(os.path.join(SAVE_DIRECTORY, 'zero_offset_gather.h5'),
'w')
hfile.create_dataset('zero_offset', data=zero_offset_gather)
hfile.close()
# Plotting the zero-offset gather, squared-slowness model, and the
# perturbation model.
extent = [
0.0,
model.domain_size[0] / 1.0e3,
tn / 1.e3,
0.
]
fig = plt.figure("Zero-offset gather", dpi=100, figsize=(10, 6))
plt.imshow(
zero_offset_gather,
vmin=-.6,
vmax=.6,
extent=extent,
cmap="Greys",
alpha=1.0,
aspect=2.0,
resample=True,
interpolation="kaiser",
filterrad=1
)
plt.xlabel("Horizontal location (km)")
plt.ylabel("Time (s)")
plt.title("Zero-offset gather")
plt.grid(False)
plt.tight_layout()
extent = [
0.0,
model.domain_size[0] / 1.0e3,
model.domain_size[1] / 1.0e3,
0.
]
fig = plt.figure("Squared-slowness model", dpi=100, figsize=(10, 5))
plt.imshow(
m.T,
vmin=-0.0,
vmax=0.2,
extent=extent,
cmap="YlGnBu",
alpha=1.0,
aspect=1.5,
resample=True,
interpolation="kaiser",
filterrad=1
)
plt.xlabel("Horizontal location (km)")
plt.ylabel("Depth (km)")
plt.title(r"Squared-slowness model $(\frac{s^2}{\mathrm{km}^2})$")
plt.colorbar(fraction=0.0218, pad=0.01)
plt.grid(False)
plt.tight_layout()
plt.show()
|
Python | UTF-8 | 567 | 3.375 | 3 | [] | no_license | numbers = [1, 2, 3, 4, 5, 6, 7, 8]
output = []
for n in numbers:
if n % 2 == 0:
output.append(n)
print(output)
i = 0
while i < len(numbers):
if numbers[i] % 2 == 0:
output.append(numbers[i])
i += 1
print(output)
def filter_even():
for n in numbers:
if n % 2 == 0:
output.append(n)
filter_even()
print(output)
def filter_even(unfilteres_list):
output = []
for n in unfiltered_list:
if n % 2 == 0:
output.append(n)
return output
output = filter_even(numbers)
print(output)
|
C++ | UTF-8 | 527 | 2.53125 | 3 | [] | no_license | #pragma once
#include "Buffer/Buffer.h"
#include "MathLibrary/Helper.h"
#include "Vertex.h"
#include "Light/Light.h"
class Triangle;
class Rasterizer
{
public:
Rasterizer(Buffer& Buffer) : buffer(Buffer) {};
void DrawTriangle(Triangle& triangle);
void DrawTriangle(float3 v1, float3 v2, float3 v3, Color c1, Color c2, Color c3);
void DrawTriangle(Vertex &v1, Vertex &v2, Vertex &v3, Light &light, VertexProcessor &vp);
float CalculateCanonicalViewX(float x);
float CalculateCanonicalViewY(float y);
Buffer& buffer;
}; |
C++ | UTF-8 | 1,147 | 2.65625 | 3 | [] | no_license | /* Copyright (C) Antonio Bonafonte, 2012
* Universitat Politecnica de Catalunya, Barcelona, Spain.
*
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#ifndef UPC_WAVMONOPCM
#define UPC_WAVMONOPCM
#include <vector>
#include <string>
/**
Read wav files which are mono and pcm with 16 bits.
The results are return in a vector of floats (values are not change, maxvalue = MAX_SHORT)
The sampling rate is also returned.
The function returns 0 if there is not error.
**/
int wavmonopcm_read(const std::string& inputFileName, std::vector<float> &x, float &sampling_rate);
/**
Write mono wav files. The samles are written as pcm with 16 bits
The sampling rate needs to be provided.
If the outputFileName include a directory which does not exists, it is created.
**/
int wavmonopcm_write(const std::string& outputFileName, std::vector<float> const &x, float sampling_rate);
#endif
|
Swift | UTF-8 | 2,104 | 2.890625 | 3 | [
"MIT"
] | permissive | //
// CSS_FulfillmentTests.swift
// CSS_FulfillmentTests
//
// Created by Ravi Vooda on 1/25/21.
// Copyright © 2021 Ravi Vooda. All rights reserved.
//
import XCTest
@testable import CSS_Fulfillment
class DecayManagerDelegateImpl: DecayManagerDelegate {
var expiredOrder:Order? = nil
var decayTimeCall: Date? = nil
var expectation = XCTestExpectation(description: "expiration called")
func handleExpiration(order: Order) {
self.expiredOrder = order
self.decayTimeCall = Date()
self.expectation.fulfill()
}
}
class CSS_FulfillmentTests: XCTestCase {
let decayManager = DecayManager()
let delegate = DecayManagerDelegateImpl()
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
decayManager.delegate = delegate
}
/*
* Create an expectation to wait for the expectation to be fulfilled asynchronously
*/
func testDecayManager_expires() {
let order = Order(id: UUID(uuidString: "75534993-2b41-4fdc-b3c8-3419ee5eca48")!,
name: "test name",
temp: .hot,
shelfLife: 15,
decayRate: 0.5)
let epochTime = Date().currentTimeMillis()
let dispatchTime = DispatchTime.now()
let shelf = Shelf(config: ShelfConfiguration(capacity: 10, decayModifier: 1))
decayManager.begin(order: order, time: dispatchTime, shelf: shelf)
wait(for: [delegate.expectation], timeout: 15)
XCTAssertNotNil(delegate.decayTimeCall)
XCTAssertNotNil(delegate.expiredOrder)
let decayTimeCall = delegate.decayTimeCall!.currentTimeMillis()
XCTAssertEqual(Float(decayTimeCall), Float(epochTime), accuracy: 1000, "delegate should be notified about the expiry")
XCTAssertEqual(delegate.expiredOrder!, order)
}
}
extension Date {
func currentTimeMillis() -> Int64 {
return Int64(self.timeIntervalSince1970 * 1000)
}
}
|
Java | UTF-8 | 538 | 2.484375 | 2 | [] | no_license | package net.rubygrapefruit;
import org.objectweb.asm.Opcodes;
public enum Visibility {
Private,
PackageProtected,
Protected,
Public;
public static Visibility fromAccessField(int field) {
if ((field & 0xff & Opcodes.ACC_PUBLIC) != 0) {
return Public;
}
if ((field & 0xff & Opcodes.ACC_PROTECTED) != 0) {
return Protected;
}
if ((field & 0xff & Opcodes.ACC_PRIVATE) == 0) {
return PackageProtected;
}
return Private;
}
}
|
TypeScript | UTF-8 | 1,061 | 3.046875 | 3 | [] | no_license | import * as localization from '../actions/localization';
export interface State {
languageCode: string;
dictionary: { [key: string]: string };
loading: boolean;
}
const initialState: State = {
languageCode: "en",
dictionary: {},
loading: false
};
export function reducer(state = initialState, action: localization.Actions): State {
switch (action.type) {
case localization.LOAD:
return {
...state,
loading: true,
};
case localization.LOAD_COMPLETE:
return {
loading: false,
dictionary: action.payload.dictionary,
languageCode: action.payload.languageCode,
};
default: {
return state;
}
}
}
export const getDictionary = (state: State) => state.dictionary;
export const getDictionaryByKey = (state: State, key: string) => {
let value = state.dictionary[key];
return value === undefined ? key : value;
};
export const getDictionaryForEnglish = (state: State) => {
let value = state.dictionary['EN'];
return value === undefined ? 'EN' : value;
}; |
Java | UTF-8 | 12,717 | 2.125 | 2 | [
"CC0-1.0"
] | permissive | package org.fundacionjala.automation.scenario.steps.admin.resource;
import java.util.List;
import org.fundacionjala.automation.framework.pages.admin.home.AdminPage;
import org.fundacionjala.automation.framework.pages.admin.resource.AddResourcePage;
import org.fundacionjala.automation.framework.pages.admin.resource.RemoveResourcePage;
import org.fundacionjala.automation.framework.pages.admin.resource.ResourcePage;
import org.fundacionjala.automation.framework.pages.admin.resource.SelectIconPage;
import org.fundacionjala.automation.framework.utils.api.managers.ResourceAPIManager;
import org.fundacionjala.automation.framework.utils.api.objects.admin.Resource;
import org.fundacionjala.automation.framework.utils.common.BrowserManager;
import org.fundacionjala.automation.framework.utils.common.PropertiesReader;
import org.testng.Assert;
import com.mashape.unirest.http.exceptions.UnirestException;
import cucumber.api.java.After;
import cucumber.api.java.en.Then;
public class ResourceThenSteps {
@Then("^Validate that the resource with name \"([^\"]*)\" is diplayed in resource page$")
public void validate_that_the_resource_with_name_is_diplayed(
String resourceName) throws Throwable {
ResourcePage resources = new ResourcePage();
BrowserManager.getDriver().navigate().refresh();
AdminPage admin = new AdminPage();
admin.leftMenu.clickOnConferenceRoomsButton();
admin.leftMenu.clickOnResourcesButton();
boolean expectedResult = resources.verifyResourceExist(resourceName);
deleteResourceByName(resourceName);
Assert.assertTrue(expectedResult);
}
@Then("^Validate that the resource with the name \"([^\"]*)\" has been deleted$")
public void validate_that_the_resource_with_the_name_has_been_deleted(
String arg1) throws Throwable {
BrowserManager.getDriver().navigate().refresh();
AdminPage admin = new AdminPage();
admin.leftMenu.clickOnConferenceRoomsButton();
ResourcePage resource = admin.leftMenu.clickOnResourcesButton();
boolean isResourceNotPresent = resource.verifyResourceNotExist(arg1);
Assert.assertTrue(isResourceNotPresent);
}
@Then("^Validate the resource \"([^\"]*)\" is displayed$")
public void validate_the_resource_is_displayed(String resourceName)
throws Throwable {
ResourcePage resourcePage = new ResourcePage();
boolean expectedResult = resourcePage.verifyResourceExist(resourceName);
deleteResourceByName(resourceName);
Assert.assertTrue(expectedResult);
}
@Then("^Validate that the resource \"([^\"]*)\" is modified according the changes \\(\"([^\"]*)\" field with value \"([^\"]*)\"\\)$")
public void validate_that_the_resource_is_modified(String resourceName,
String nameField, String value) throws Throwable {
ResourcePage resourcePage = new ResourcePage();
resourcePage = (new AdminPage()).leftMenu.clickOnResourcesButton();
boolean expectedResult = resourcePage.verifyResourceModifiedByField(
resourceName, nameField, value);
deleteResourceByName(resourceName);
Assert.assertTrue(expectedResult);
}
@Then("^Validate that the 'next' page is displayed on resource table$")
public void validate_that_the_next_page_is_displayed() throws Throwable {
ResourcePage resources = new ResourcePage();
Assert.assertTrue(resources.verifyNextPage("2"));
}
@Then("^Validate that the 'previous' page is displayed on resource table$")
public void validate_the_previous_page_is_displayed() throws Throwable {
ResourcePage resources = new ResourcePage();
int previousPage = resources.getTheTotalNumberPage();
Assert.assertTrue(resources.verifyPreviousPage(previousPage));
}
@Then("^Validate that the \"([^\"]*)\" page is displayed$")
public void validate_that_the_page_is_displayed(String NumberPage)
throws Throwable {
List<Resource> listResource = ResourceAPIManager
.getRequest(PropertiesReader.getServiceURL() + "/resources");
int resourceIndx = ((Integer.parseInt(NumberPage) - 1) * 50) + 1;
ResourcePage resources = new ResourcePage();
String firstElement = listResource.get(resourceIndx - 1).name;
Assert.assertTrue(resources
.verifyTheFirstElementOnThePage(firstElement));
}
@Then("^Validate that resource with \"([^\"]*)\", \"([^\"]*)\" and \"([^\"]*)\" is displayed$")
public void validate_that_resource_with_and_is_displayed(
String resourceName, String displayname, String icon)
throws Throwable {
ResourcePage resources = new ResourcePage();
BrowserManager.getDriver().navigate().refresh();
AdminPage admin = new AdminPage();
admin.leftMenu.clickOnConferenceRoomsButton();
admin.leftMenu.clickOnResourcesButton();
boolean expectedResult = resources.verifyResourceDisplayed(
resourceName, displayname, icon);
deleteResourceByName(resourceName);
Assert.assertTrue(expectedResult);
}
@Then("^Validate that all resources are displayed in resource table$")
public void validate_all_resources_are_displayed() throws Throwable {
ResourcePage resources = new ResourcePage();
List<Resource> listResource = ResourceAPIManager
.getRequest(PropertiesReader.getServiceURL() + "/resources");
Assert.assertTrue(resources
.verifyResourcesOnResourceTable(listResource));
}
@Then("^Validate that total resources are displayed$")
public void validate_total_resources_are_displayed() throws Throwable {
ResourcePage resources = new ResourcePage();
AdminPage home = new AdminPage();
BrowserManager.getDriver().navigate().refresh();
home.leftMenu.clickOnConferenceRoomsButton();
home.leftMenu.clickOnResourcesButton();
List<Resource> listResource = ResourceAPIManager
.getRequest(PropertiesReader.getServiceURL() + "/resources");
int totalItems = listResource.size();
Assert.assertTrue(resources.verifyTotalItems(totalItems));
}
@Then("^Validate that the resource table size is same than the option \"([^\"]*)\" selected$")
public void validate_resource_table_size(String sizeTable) throws Throwable {
ResourcePage resources = new ResourcePage();
Assert.assertTrue(resources.verifyNumberOfResources(sizeTable));
}
@Then("^Validate that the association with the \"([^\"]*)\" room is displayed$")
public void validate_resource_association(String RoomName) throws Throwable {
RemoveResourcePage removeResource = new RemoveResourcePage();
boolean expectedResult = removeResource
.verifyAssociatedRoomExist(RoomName);
Assert.assertTrue(expectedResult);
removeResource.clickOnRemoveButton();
}
@Then("^Validate that the first page is displayed on resource table$")
public void validate_the_first_page() throws Throwable {
ResourcePage resources = new ResourcePage();
Assert.assertTrue(resources.verifyTheFirstPage("1"));
}
@Then("^Validate that the last page is displayed on resource table$")
public void validate_the_last_page() throws Throwable {
ResourcePage resources = new ResourcePage();
Assert.assertTrue(resources.verifyTheLastPage());
}
@After("@resouceDelete")
public void tearDown() throws Throwable {
deleteResourcesCreated();
}
private void deleteResourceByName(String resourceName)
throws UnirestException {
String idResource = "";
List<Resource> listResource = ResourceAPIManager
.getRequest(PropertiesReader.getServiceURL() + "/resources");
for (Resource resource : listResource) {
if (resource.name.equalsIgnoreCase(resourceName)) {
idResource = resource._id;
}
}
ResourceAPIManager.deleteRequest(PropertiesReader.getServiceURL()
+ "/resources", idResource);
}
private void deleteResourcesCreated() throws UnirestException {
List<Resource> listResource = ResourceAPIManager
.getRequest(PropertiesReader.getServiceURL() + "/resources");
for (Resource resource : listResource) {
if (resource.name.contains("Gift")) {
ResourceAPIManager.deleteRequest(
PropertiesReader.getServiceURL() + "/resources",
resource._id);
}
}
}
@Then("^Validate that a form with \"([^\"]*)\" resource and \"([^\"]*)\" icon is displayed$")
public void displayResourceInformation(
String resourceName, String iconName) throws Throwable {
RemoveResourcePage removeResourcePage = new RemoveResourcePage();
Assert.assertTrue(
removeResourcePage.verifyResourceInformation(resourceName, iconName),
"The information of Resource is Incorrect");
removeResourcePage.clickOnCloseButton();
}
@Then("^Validate that a form to create a resource is diplayed$")
public void validate_that_a_form_to_create_a_resource_is_diplayed() throws Throwable {
AddResourcePage addResourcePage = new AddResourcePage();
Assert.assertTrue(
addResourcePage.verifyIfFormIsDisplayed(),
"The form is not displayed");
addResourcePage.clickOnCancelButton();
}
@Then("^Validate that an error message is displayed$")
public void validate_that_an_error_message_is_displayed() throws Throwable {
AddResourcePage addResourcePage = new AddResourcePage();
Assert.assertTrue(
addResourcePage.verifyErrorMessagesWhenFieldsAreEmpty(),
"The form is not displayed");
addResourcePage.clickOnCancelButton();
}
@Then("^Validate that an error message is displayed for special characters$")
public void validate_that_an_error_message_is_displayed_for_special_characters() throws Throwable {
AddResourcePage addResourcePage = new AddResourcePage();
Assert.assertTrue(
addResourcePage.verifyErrorMessageWhenSpecialCharactersAreEntered(),
"The form is not displayed");
addResourcePage.clickOnCancelButton();
}
@Then("^Validate that a form to remove a resource is displayed$")
public void validate_that_a_form_to_remove_a_resource_is_diplayed() throws Throwable {
RemoveResourcePage removeResourcePage = new RemoveResourcePage();
Assert.assertTrue(
removeResourcePage.verifyFormToRemoveResource(),
"The form is not displayed");
removeResourcePage.clickOnCancelButton();
}
@Then("^Validate that an error message is displayed when I want to create a new resource that already exists\\.$")
public void validate_that_an_error_message_is_displayed_when_I_want_to_create_a_new_resource_that_already_exists() throws Throwable {
}
@Then("^the Resource Info Page is closed$")
public void verifyIfAddResourcePageisClosed() {
ResourcePage resource = new ResourcePage();
Assert.assertFalse(resource.isAddResourcePageOpen());
}
@Then("^the quantity of selected resources displayed is the same as the number of resources selected \"([^\"]*)\"$")
public void verifyNumberOfResourceSelected(String resourceNumber) {
int expectedResourceSelectedNumber = Integer.parseInt(resourceNumber);
ResourcePage resource = new ResourcePage();
int actualResourceSelectedNumber = resource.getSelectedItems();
Assert.assertEquals(actualResourceSelectedNumber, expectedResourceSelectedNumber);
}
@Then("^All the resources are selected$")
public void verifyAllResourceAreSelected() {
ResourcePage resource = new ResourcePage();
int expectedTotalNumberOfItems = resource.getTotalItems();
int actualTotalNumberOfItems = resource.getSelectedItems();
Assert.assertEquals(actualTotalNumberOfItems, expectedTotalNumberOfItems);
}
@Then("^All the resources are unselected$")
public void verifyNoResourcesAreSelected() {
ResourcePage resource = new ResourcePage();
int expectedTotalNumberOfItems = 0;
int actualTotalNumberOfItems = resource.getSelectedItems();
Assert.assertEquals(actualTotalNumberOfItems, expectedTotalNumberOfItems);
}
@Then("^the Remove button is enabled$")
public void verifyIfRemoveButtonIsEnabled() {
ResourcePage resource = new ResourcePage();
Assert.assertFalse(resource.isRemoveButtonDisabled());
}
@Then("^the resource \"([^\"]*)\" is checked$")
public void verifyIfTheResourceIsChecked(String resourceName) {
ResourcePage resource = new ResourcePage();
Assert.assertTrue(resource.isResourceChecked(resourceName));
}
@Then("^Validate that icon image is updated to \"([^\"]*)\" Icon on add page\\.$")
public void validate_that_icon_image_is_updated_on_add_page(String icon) throws Throwable {
AddResourcePage addResourcePage = new AddResourcePage();
Assert.assertTrue(
addResourcePage.verifyIconUpdate(icon),
"The Icon is not updated to " + icon);
addResourcePage.clickOnCancelButton();
}
@Then("^Validate that icon page change to \"([^\"]*)\"$")
public void validate_that_icon_page_change_to(String button) throws Throwable {
SelectIconPage selectIconPage = new SelectIconPage();
Assert.assertTrue(
selectIconPage.verifyIfIconPageChanged(button),
"The Icon page does not change to " + button);
}
}
|
TypeScript | UTF-8 | 4,512 | 3.65625 | 4 | [
"MIT"
] | permissive | export type NamedEntity = {
first_name: string
last_name?: string
}
export type Payload<T> = { payload: T }
/**
* @format uuid
*/
export type UUID = string
/**
* @format uuid
*/
export type TeacherID = UUID
/**
* @format uuid
*/
export type LessonID = UUID
/**
* @format uuid
*/
export type TaskID = UUID
/**
* @format uuid
*/
export type UserID = UUID
/**
* @format uuid
*/
export type EntityID = TeacherID | LessonID | TaskID
export type EntityType = "teacher" | "lesson" | "task"
export type IDOf<Entity extends EntityType> = Entity extends "teacher"
? TeacherID
: Entity extends "lesson"
? LessonID
: TaskID
/**
* @format jwt
* @pattern [a-zA-Z0-9_=\-]{18,24}\.[a-zA-Z0-9_=\-]{128,256}\.[a-zA-Z0-9_=\-]{36,48}
*/
export type JWT = string
export type Monday = 1
export type Tuesday = 2
export type Wednesday = 3
export type Thursday = 4
export type Friday = 5
export type Saturday = 6
export type Sunday = 7
export type WeekDay =
| Monday
| Tuesday
| Wednesday
| Thursday
| Friday
| Saturday
| Sunday
/**
* @format date
*/
export type ISODate = string
/**
* @format time
*/
export type ISOTime = string
/**
* @format date-time
*/
export type ISODateTime = string
/**
* @format date-time
*/
export type SingleOccurrence = ISODateTime
export interface Repetition {
/**
* @description The start date, before which repetitions do not occur.
* start_date is inclusive (meaning, if the event is repeated on that day, it is present)
*/
start_date: ISODate
/**
* @description Optional end date, after which repetitions do not occur.
* If end_date is not set, it is assumed that event repetition do not end.
* end_date is inclusive (meaning, if the event is repeated on that day, it is present)
*/
end_date?: ISODate
}
export interface DailyRepetition extends Repetition {
/** @description Time of day when lesson takes place */
at: ISOTime
}
export interface WeeklyRepetition extends Repetition {
/**
* @description Frequency at which lessons are to be repeated counted in weeks.
* If lesson were to be repeated every week, the value would be 1, biweekly - 2
* @type integer
* @minimum 1
*/
every: number
/**
* @description Day of the week when repetition occurs.
* 1 - Monday
* 2 - Tuesday
* 3 - Wednesday
* 4 - Thursday
* 5 - Friday
* 6 - Saturday
* 7 - Sunday
* * Sorry North America *
*/
day: WeekDay
/** @description Time of day when lesson takes place */
at: ISOTime
}
export interface MonthlyRepetition extends Repetition {
/**
* @description Frequency at which lessons are to be repeated counted in months.
* If lesson were to be repeated every month, the value would be 1, bimonthly - 2
* @type integer
* @minimum 1
*/
every: number
/**
* @description This is a complicated one.
* Time part is used to determine when in the day lesson occurs.
* From the date part only the day is used.
* The day of the month is then used to provide stable day of every months repetition.
* @todo Maybe split time of day repetition and day of the month into a separate field
*/
at: ISODateTime
}
export interface Lesson {
id: LessonID
title: string
/**
* @description Date-times at which events will occur
* @item.format date-time
* @item.type string
*/
singles: SingleOccurrence[]
/**
* @description Times where lesson is repeated every single (for now) day.
*/
daily: DailyRepetition[]
weekly: WeeklyRepetition[]
monthly: MonthlyRepetition[]
/**
* @description Array of Teacher IDs
* @abstract if you have read access to the lesson, you get read access to the teachers assigned to it
* @items.format uuid
* @items.type string
*/
teachers: TeacherID[]
description?: string
}
export interface Teacher extends NamedEntity {
id: TeacherID
associated_account_id?: UserID
// lessons: LessonID[] // not MVP
}
export interface Task {
id: TaskID
name: string
description?: string
lesson?: LessonID
// teacher?: TeacherID // not MVP
}
export interface User extends NamedEntity {
id: UserID
}
|
JavaScript | UTF-8 | 1,322 | 2.515625 | 3 | [
"MIT"
] | permissive | function chooseImage() {
$("#upfile").change(function(e) {
var imgBox = e.target;
uploadImg($('#bcd'), imgBox)
});
function uploadImg(element, tag) {
var file = tag.files[0];
var imgSrc;
if (!/image\/\w+/.test(file.type)) {
alert("看清楚,这个需要图片!");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
console.log(this.result);
imgSrc = this.result;
var imgs = document.createElement("img");
$(imgs).attr("src", imgSrc);
element.append(imgs);
};
}
}
function upLoad(){
var fd = new FormData();
fd.append("upload", 1);
fd.append("file", $("#upfile").get(0).files[0]);
fd.append("userId", userId);
$.ajax({
url: "http://localhost:8080/upload",
type: "POST",
processData: false,
contentType: false,
data: fd,
success: function(d) {
$.cookie("stroy",JSON.stringify(d.data),{ expires: 7 });
$('#userImg').attr('src', "/spingboottext/templates"+d.data.portrait);
var s=$.cookie("stroy");
console.log(d);
}
});
}
function getPage(){
return 13;
} |
TypeScript | UTF-8 | 665 | 2.859375 | 3 | [] | no_license | import * as fromDeals from './../actions/deals.actions';
export interface State {
data: Array<any>;
}
export const initialState: State = {
data: []
};
export function reducer(state = initialState, action: fromDeals.DealsActions): State {
switch (action.type) {
case fromDeals.LOAD_DEALS_SUCCESS: {
return {
...state,
data: action.payload
};
}
case fromDeals.LOAD_DEALS_FAILURE: {
return {
data: []
};
}
default: {
return state;
}
}
}
export const getData = (state: State) => state.data;
|
C | UTF-8 | 741 | 3.140625 | 3 | [] | no_license | /*************************************************************************
> File Name: euler_7.c
> Author:
> Mail:
> Created Time: 2018年07月31日 星期二 14时45分20秒
************************************************************************/
#include<stdio.h>
#define MAX_N 500000
int prime[MAX_N + 5] = {0};
int main() {
for(int i = 2; i <= MAX_N; i++) {
if(!prime[i]) {
prime[++prime[0]] = i;
}
for(int j = 1; j <= prime[0] && prime[j] * i <= MAX_N; j++) {
prime[i * prime[j]] = 1;
if(i % prime[j] == 0) break;
}
}
for(int i = 1; i <= prime[0]; i++) {
printf("%d\n", prime[i]);
}
printf("%d", prime[10001]);
return 0;
}
|
C | UTF-8 | 422 | 3.71875 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
unsigned age;
};
void sprint(struct student stu);
void sprint(struct student stu)
{
printf(" Id is: %d \n", stu.id);
printf(" Name is: %s \n", stu.name);
printf(" Age is: %u \n", stu.age);
}
int main()
{
struct student stu;
stu.age = 18;
strcpy(stu.name, "Tiger");
stu.id = 22588;
sprint(stu);
} |
Python | UTF-8 | 119 | 3.421875 | 3 | [] | no_license | #Create a dictionary of two keys, a and b and two values 1 and 2 for keys a and b respectively.
d = {"a": 1, "b": 2}
|
Java | UTF-8 | 1,941 | 1.875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2018-2018 adorsys GmbH & Co KG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.adorsys.aspsp.xs2a.domain.ais;
import de.adorsys.aspsp.xs2a.domain.SingleAccountAccess;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "Request Body for created by some methods in the Ais Service")
public class AisInformationRequestBody {
@ApiModelProperty(value = "Requested access service per account.", required = true)
private SingleAccountAccess[] accounts;
@ApiModelProperty(value = "This parameter is requesting a valid until date for the requested consent. The content is the local ASPSP date in ISODate Format", required = true, example = "2017-10-30")
private String valid_until;
@ApiModelProperty(value = "This field indicates the requested maximum frequency for an access per day. For a once-off access, this attribute is set to 1", required = true, example = "4")
private Integer frequency_per_day;
@ApiModelProperty(value = "\"true\", if the consent is for recurring access to the account data \"false\", if the consent is for one access to the account data", required = true)
private boolean recurring_indicator;
@ApiModelProperty(value = "If \"true\" indicates that a payment initiation service will be addressed in the same \"session\"", required = true)
private boolean combined_service_indicator;
}
|
Python | UTF-8 | 4,751 | 2.71875 | 3 | [] | no_license | '''
Wrapper for composite AOIs (AOIs defined as a set of polygons).
Created on 2014-5-25
@author: lalles
'''
import sys, os
def init_composite_AOIs(aoifilename, aoifilename_composite):
"""
Convert a composite AOI definition file to a simple file by exploding all composite AOIs (defined as a set of polygons) in a set of new AOIs defined as one single polygon
Args:
aoifilename: path of the AOIs definition file
aoifilename_composite: destination of the temporary composite AOIs file
Returns:
List of new AOIs name
"""
try:
aoifile=open(aoifilename, 'rb')
aoifile_out=open(aoifilename_composite, 'wb')
aoilines = aoifile.readlines()
dynamic_aoi = []
aoinewline = []
aoinames = []
for line in aoilines:
if line.find(";") >-1: #multiple polygons
chunks_polys=line.strip().split(';')
for i in range(0,len(chunks_polys)):
chunks_polys[i]=chunks_polys[i].split("\t")
if i == 0:
aoi_id=chunks_polys[i][0]
chunks_polys[i][0] = aoi_id+"___"+str(i)
else:
chunks_polys[i][0] = aoi_id+"___"+str(i)+chunks_polys[i][0]
aoinames.append(aoi_id+"___"+str(i))
chunks_polys[i] = '\t'.join(chunks_polys[i])
aoinewline.append(chunks_polys)
else:
aoinewline.append([line.strip()])
if not line.strip().startswith('#'):
chunks=line.strip().split('\t')
aoinames.append(chunks[0])
for numl, lines in enumerate(aoinewline):
if not lines[0].startswith('#'):
for l in lines:
aoifile_out.write(l+'\n')
if numl<len(aoinewline)-1 and aoinewline[numl+1][0].startswith('#'):
aoifile_out.write(aoinewline[numl+1][0]+'\n')
aoifile.close()
aoifile_out.close()
return aoinames
except:
exc_type, exc_obj, exc_tb = sys.exc_info()
print "Exception", sys.exc_info()
print "Line ", exc_tb.tb_lineno
def postprocess_composite_AOIs(outfilename, aoinames, aoi_feat):
"""
Post-process the features output file by merging all exploded single AOI (init_composite_AOIs() must be called first)
Args:
outfilename: features output file
aoinames: list of AOIs names (returned by init_composite_AOIs())
aoi_feat: list of AOI features
"""
try:
outfile=open(outfilename, 'rb')
outlines = outfile.readlines()
if not outlines[0].find("___")>-1:
outfile.close()
return 0 #no composite AOI, nothing to do
#else
outfile.close()
outfile=open(outfilename, 'wb')
header_feat = outlines[0].split('\t')
merge_id = []
merge_subid = []
to_remove=[]
for col in aoinames:
if col.find("___")>-1:
col_c = col.split("___")
if col_c[1] == '0':
merge_id.append( header_feat.index(col+"_"+aoi_feat[0]) )
merge_subid.append([])
else:
last_id = 0 if len(merge_subid) == 0 else len(merge_subid)-1
merge_subid[last_id].append( header_feat.index(col+"_"+aoi_feat[0]) )
for i in range(0,len(aoi_feat)):
to_remove.append(header_feat.index(col+"_"+aoi_feat[0])+i)
# print merge_id
# print merge_subid
to_remove.sort()
to_remove.reverse()
for numl,l in enumerate(outlines):
if numl == 0:
chunk = l.split('\t')
for mid in merge_id:
for i in range(0,len(aoi_feat)):
chunk[mid+i] = chunk[mid+i].replace("___0", "")
for delid in to_remove: #remove all polygons of the composite AOI except the first
chunk.pop(delid)
out=('\t'.join(chunk))
if out.find('\n')==-1:
out = out+'\n'
outfile.write(out) #clean header
else:
chunk = l.split('\t')
for idc,col_feat0 in enumerate(merge_id): #for all first polygons of a composite AOI
for idf, feat in enumerate(aoi_feat): # for all AOI features
init_val = float(chunk[col_feat0+idf])
for col_subfeat in merge_subid[idc]: #for all other polygons of the composite AOI
if feat == "fixationrate" or feat == "numfixations" or feat == "proportionnum" or feat == "proportiontime" or feat == "totaltimespent":
init_val = init_val + float(chunk[col_subfeat+idf])
elif feat == "longestfixation" or feat == "timetolastfixation":
init_val = max(init_val, float(chunk[col_subfeat+idf]))
elif feat == "timetofirstfixation":
init_val = min(init_val, float(chunk[col_subfeat+idf]))
else:
raise Exception("Unknown AOI feature : "+feat)
chunk[col_feat0+idf] = str(init_val) # merge values in the column of the first polygon
for delid in to_remove: #remove all polygons of the composite AOI except the first
chunk.pop(delid)
out=('\t'.join(chunk))
if out.find('\n')==-1:
out = out+'\n'
outfile.write(out)
outfile.close()
except:
exc_type, exc_obj, exc_tb = sys.exc_info()
print "Exception", sys.exc_info()
print "Line ", exc_tb.tb_lineno
|
Java | UTF-8 | 1,325 | 2.828125 | 3 | [] | no_license | package org.rnd.jmagic.cards;
import static org.rnd.jmagic.Convenience.*;
import org.rnd.jmagic.engine.*;
import org.rnd.jmagic.engine.generators.*;
import org.rnd.jmagic.gameTypes.*;
@Name("Krosa")
@Types({Type.PLANE})
@SubTypes({SubType.DOMINARIA})
@ColorIdentity({Color.WHITE, Color.BLUE, Color.BLACK, Color.RED, Color.GREEN})
public final class Krosa extends Card
{
public static final class PumpOfKrosa extends StaticAbility
{
public PumpOfKrosa(GameState state)
{
super(state, "All creatures get +2/+2.");
this.addEffectPart(modifyPowerAndToughness(CreaturePermanents.instance(), 2, 2));
this.canApply = PlanechaseGameRules.staticAbilityCanApply;
}
}
public static final class ChaosMana extends EventTriggeredAbility
{
public ChaosMana(GameState state)
{
super(state, "Whenever you roll (C), you may add (W)(U)(B)(R)(G) to your mana pool.");
this.addPattern(PlanechaseGameRules.wheneverYouRollChaos());
EventFactory mana = addManaToYourManaPoolFromAbility("(W)(U)(B)(R)(G)");
this.addEffect(youMay(mana, "You may add (W)(U)(B)(R)(G) to your mana pool."));
this.canTrigger = PlanechaseGameRules.triggeredAbilityCanTrigger;
}
}
public Krosa(GameState state)
{
super(state);
this.addAbility(new PumpOfKrosa(state));
this.addAbility(new ChaosMana(state));
}
}
|
JavaScript | UTF-8 | 267 | 3.265625 | 3 | [] | no_license | function getMissingNumbersCount(arr){
var missingNumbersCount = 0;
arr.sort(function(a,b){return a-b});
for(var i = 0; i < arr.length-1; i++){
if(arr[i+1] != arr[i]){
missingNumbersCount += arr[i+1]-arr[i]-1;
}
}
return missingNumbersCount;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.