repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
krzyk240/simlib
test/event_queue.cc
26377
#include "simlib/event_queue.hh" #include "simlib/concurrent/semaphore.hh" #include "simlib/defer.hh" #include "simlib/file_descriptor.hh" #include "simlib/repeating.hh" #include <chrono> #include <cstddef> #include <cstdint> #include <fcntl.h> #include <gtest/gtest-death-test.h> #include <gtest/gtest.h> #include <memory> #include <optional> #include <thread> #include <type_traits> #include <unistd.h> using std::array; using std::chrono::milliseconds; using std::chrono::system_clock; using std::chrono_literals::operator""ms; using std::chrono_literals::operator""ns; using std::chrono_literals::operator""us; using std::chrono_literals::operator""s; using std::function; using std::string; using std::vector; // NOLINTNEXTLINE TEST(EventQueue, add_time_handler_time_point) { auto start = system_clock::now(); int times = 0; EventQueue eq; eq.add_time_handler(start + 30us, [&] { ++times; EXPECT_LE(start + 30us, system_clock::now()); eq.add_time_handler(start + 60us, [&] { ++times; EXPECT_LE(start + 60us, system_clock::now()); }); }); eq.add_time_handler(start + 20us, [&] { ++times; EXPECT_LE(start + 20us, system_clock::now()); eq.add_time_handler(start + 40us, [&] { ++times; EXPECT_LE(start + 40us, system_clock::now()); }); }); eq.add_time_handler(start + 50us, [&] { ++times; EXPECT_LE(start + 50us, system_clock::now()); }); EXPECT_EQ(times, 0); eq.run(); EXPECT_EQ(times, 5); } // NOLINTNEXTLINE TEST(EventQueue, add_time_handler_duration) { auto start = system_clock::now(); int times = 0; EventQueue eq; eq.add_time_handler(30us, [&] { ++times; EXPECT_LE(start + 30us, system_clock::now()); eq.add_time_handler(30us, [&] { ++times; EXPECT_LE(start + 60us, system_clock::now()); }); }); eq.add_time_handler(20us, [&] { ++times; EXPECT_LE(start + 20us, system_clock::now()); eq.add_time_handler(20us, [&] { ++times; EXPECT_LE(start + 40us, system_clock::now()); }); }); eq.add_time_handler(50us, [&] { ++times; EXPECT_LE(start + 50us, system_clock::now()); }); EXPECT_EQ(times, 0); eq.run(); EXPECT_EQ(times, 5); } // NOLINTNEXTLINE TEST(EventQueue, add_ready_handler) { auto start = system_clock::now(); string order; EventQueue eq; eq.add_ready_handler([&] { order += "0"; }); eq.add_time_handler(10us, [&] { EXPECT_LE(start + 10us, system_clock::now()); order += "1"; }); EXPECT_EQ(order, ""); eq.run(); EXPECT_EQ(order, "01"); } // NOLINTNEXTLINE TEST(EventQueue, add_repeating_handler) { auto start = system_clock::now(); string order; EventQueue eq; eq.add_repeating_handler(20us, [&, iter = 0]() mutable { order += char('a' + iter); ++iter; EXPECT_LE(start + iter * 20us, system_clock::now()); return iter == 10 ? stop_repeating : continue_repeating; }); EXPECT_EQ(order, ""); eq.run(); EXPECT_EQ(order, "abcdefghij"); } // NOLINTNEXTLINE TEST(EventQueue, adding_mutable_handler) { EventQueue eq; size_t times = 0; eq.add_ready_handler([&, x = 0]() mutable { ++x; ++times; }); eq.add_time_handler(0ns, [&, x = 0]() mutable { ++x; ++times; }); eq.add_time_handler(system_clock::now(), [&, x = 0]() mutable { ++x; ++times; }); eq.add_repeating_handler(0ns, [&, x = 0]() mutable { ++x; ++times; return stop_repeating; }); FileDescriptor fd("/dev/null", O_RDONLY); ASSERT_TRUE(fd.is_open()); EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&, x = 0]() mutable { ++x; ++times; eq.remove_handler(hid); }); EXPECT_EQ(times, 0); eq.run(); EXPECT_EQ(times, 5); } static void pause_immediately_from_handler( const std::function<void(EventQueue&, size_t&)>& stopper_installer) { EventQueue eq; size_t times = 0; auto handler_impl = [&](auto& self) -> void { ++times; eq.add_ready_handler([&self] { self(self); }); }; eq.add_ready_handler([&] { handler_impl(handler_impl); }); FileDescriptor fd("/dev/null", O_WRONLY); ASSERT_TRUE(fd.is_open()); eq.add_file_handler(fd, FileEvent::WRITEABLE, [&] { ++times; }); eq.add_repeating_handler(0ns, [&] { ++times; return continue_repeating; }); stopper_installer(eq, times); eq.run(); EXPECT_EQ(times, 0); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_time_handler) { pause_immediately_from_handler([](EventQueue& eq, size_t& times) { eq.add_time_handler(100us, [&] { times = 0; eq.pause_immediately(); }); }); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_repeating_handler) { pause_immediately_from_handler([](EventQueue& eq, size_t& times) { eq.add_repeating_handler(8us, [&, iter = 0]() mutable { if (++iter == 10) { times = 0; eq.pause_immediately(); } return continue_repeating; }); }); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_file_handler) { FileDescriptor fd("/dev/null", O_WRONLY); pause_immediately_from_handler([&](EventQueue& eq, size_t& times) { eq.add_file_handler(fd, FileEvent::WRITEABLE, [&, iter = 0]() mutable { if (++iter == 4) { times = 0; eq.pause_immediately(); } return true; }); }); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_other_thread_while_running_time_handlers) { EventQueue eq; size_t times = 0; concurrent::Semaphore sem(0); auto handler_impl = [&](auto& self) -> void { if (++times > 4) { sem.post(); } eq.add_ready_handler([&self] { self(self); }); }; eq.add_ready_handler([&] { handler_impl(handler_impl); }); std::thread other([&] { sem.wait(); std::this_thread::sleep_for(8us); eq.pause_immediately(); }); EXPECT_EQ(times, 0); eq.run(); other.join(); EXPECT_GT(times, 4); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_other_thread_while_running_repeating_handler) { EventQueue eq; size_t times = 0; concurrent::Semaphore sem(0); eq.add_repeating_handler(0ns, [&] { if (++times > 4) { sem.post(); } return continue_repeating; }); std::thread other([&] { sem.wait(); std::this_thread::sleep_for(8us); eq.pause_immediately(); }); EXPECT_EQ(times, 0); eq.run(); other.join(); EXPECT_GT(times, 4); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_other_thread_while_running_file_handlers) { EventQueue eq; size_t writes = 0; concurrent::Semaphore sem(0); FileDescriptor fd("/dev/null", O_WRONLY); ASSERT_TRUE(fd.is_open()); eq.add_file_handler(fd, FileEvent::WRITEABLE, [&] { if (++writes > 4) { sem.post(); } }); std::thread other([&] { sem.wait(); std::this_thread::sleep_for(8us); eq.pause_immediately(); }); EXPECT_EQ(writes, 0); eq.run(); other.join(); EXPECT_GT(writes, 4); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_from_other_thread_while_waiting) { EventQueue eq; int times = 0; std::array<int, 2> pfd{}; ASSERT_EQ(pipe2(pfd.data(), O_CLOEXEC), 0); Defer guard = [&pfd] { for (int fd : pfd) { (void)close(fd); } }; eq.add_file_handler(pfd[0], FileEvent::READABLE, [&] { ++times; }); concurrent::Semaphore sem(0); eq.add_ready_handler([&] { ++times; sem.post(); }); std::thread other([&] { sem.wait(); std::this_thread::sleep_for(80us); eq.pause_immediately(); }); EXPECT_EQ(times, 0); eq.run(); other.join(); EXPECT_EQ(times, 1); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_before_run_is_no_op) { EventQueue eq; string order; eq.pause_immediately(); eq.add_ready_handler([&] { order += "x"; }); eq.add_ready_handler([&] { order += "x"; }); eq.pause_immediately(); EXPECT_EQ(order, ""); eq.run(); EXPECT_EQ(order, "xx"); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_and_run_again) { EventQueue eq; std::string order; eq.add_time_handler(1us, [&] { eq.pause_immediately(); order += "1"; eq.pause_immediately(); }); eq.add_time_handler(2us, [&] { eq.pause_immediately(); order += "2"; eq.pause_immediately(); }); EXPECT_EQ(order, ""); eq.run(); EXPECT_EQ(order, "1"); eq.run(); EXPECT_EQ(order, "12"); eq.run(); EXPECT_EQ(order, "12"); } // NOLINTNEXTLINE TEST(EventQueue, pause_immediately_and_run_again_loop) { EventQueue eq; std::string order; eq.add_repeating_handler(0ns, [&, iter = 0]() mutable { eq.pause_immediately(); order += static_cast<char>(++iter + '0'); return continue_repeating; }); EXPECT_EQ(order, ""); eq.run(); EXPECT_EQ(order, "1"); eq.run(); EXPECT_EQ(order, "12"); eq.run(); EXPECT_EQ(order, "123"); eq.run(); EXPECT_EQ(order, "1234"); eq.run(); EXPECT_EQ(order, "12345"); eq.run(); EXPECT_EQ(order, "123456"); eq.run(); EXPECT_EQ(order, "1234567"); eq.run(); EXPECT_EQ(order, "12345678"); eq.run(); EXPECT_EQ(order, "123456789"); } // NOLINTNEXTLINE TEST(EventQueue, remove_time_handler) { auto start = system_clock::now(); int times = 0; EventQueue eq; EventQueue::handler_id_t hid = 0; eq.add_time_handler(start + 20us, [&] { ++times; EXPECT_LE(start + 20us, system_clock::now()); eq.remove_handler(hid); eq.add_time_handler(40us, [&] { ++times; EXPECT_LE(start + 40us, system_clock::now()); }); eq.add_ready_handler([&] { ++times; EXPECT_LE(start + 20us, system_clock::now()); }); }); hid = eq.add_time_handler(start + 30us, [&] { ++times; FAIL(); }); EXPECT_EQ(times, 0); eq.run(); EXPECT_EQ(times, 3); } // NOLINTNEXTLINE TEST(EventQueue_DeathTest, time_handler_removes_itself) { EXPECT_EXIT( { EventQueue eq; EventQueue::handler_id_t hid; hid = eq.add_time_handler(system_clock::now(), [&] { eq.remove_handler(hid); }); eq.run(); }, ::testing::KilledBySignal(SIGABRT), "BUG"); EXPECT_EXIT( { EventQueue eq; EventQueue::handler_id_t hid; hid = eq.add_time_handler(0ns, [&] { eq.remove_handler(hid); }); eq.run(); }, ::testing::KilledBySignal(SIGABRT), "BUG"); } // NOLINTNEXTLINE TEST(EventQueue_DeathTest, ready_handler_removes_itself) { EXPECT_EXIT( { EventQueue eq; EventQueue::handler_id_t hid; hid = eq.add_ready_handler([&] { eq.remove_handler(hid); }); eq.run(); }, ::testing::KilledBySignal(SIGABRT), "BUG"); } // NOLINTNEXTLINE TEST(EventQueue, compaction_of_file_handlers_edge_case_regression_test) { EventQueue eq; string order; FileDescriptor fd("/dev/null", O_WRONLY); EventQueue::handler_id_t hid1 = 0; EventQueue::handler_id_t hid2 = 0; hid1 = eq.add_file_handler(fd, FileEvent::WRITEABLE, [&] { eq.remove_handler(hid1); order += "1"; hid2 = eq.add_file_handler(fd, FileEvent::WRITEABLE, [&] { // Now compaction removes the previous handler eq.remove_handler(hid2); order += "2"; eq.pause_immediately(); eq.add_file_handler(fd, FileEvent::WRITEABLE, [&] { order += "3"; eq.pause_immediately(); }); }); }); EXPECT_EQ(order, ""); eq.run(); EXPECT_EQ(order, "12"); eq.run(); EXPECT_EQ(order, "123"); } // NOLINTNEXTLINE TEST(EventQueue, time_only_fairness) { auto start = system_clock::now(); bool time_handler_run = false; EventQueue eq; eq.add_time_handler(start + 20us, [&] { EXPECT_LE(start + 20us, system_clock::now()); time_handler_run = true; }); uint64_t looper_iters = 0; auto looper = [&](auto&& self) { if (looper_iters > 4 and time_handler_run) { return; } ++looper_iters; if (system_clock::now() > start + 10s) { FAIL(); } eq.add_ready_handler([&] { self(self); }); }; eq.add_ready_handler([&] { looper(looper); }); EXPECT_EQ(looper_iters, 0); EXPECT_EQ(time_handler_run, false); eq.run(); EXPECT_GT(looper_iters, 4); EXPECT_EQ(time_handler_run, true); } // NOLINTNEXTLINE TEST(EventQueue, file_only_fairness) { uint64_t iters_a = 0; uint64_t iters_b = 0; EventQueue eq; FileDescriptor fd_a("/dev/zero", O_RDONLY); EventQueue::handler_id_t file_a_hid = eq.add_file_handler(fd_a, FileEvent::READABLE, [&](FileEvent /*unused*/) { if (iters_b + iters_b > 500) { return eq.remove_handler(file_a_hid); } ++iters_a; }); FileDescriptor fd_b("/dev/null", O_WRONLY); EventQueue::handler_id_t file_b_hid = eq.add_file_handler(fd_b, FileEvent::WRITEABLE, [&](FileEvent /*unused*/) { if (iters_b + iters_b > 500) { return eq.remove_handler(file_b_hid); } ++iters_b; }); EXPECT_EQ(iters_a, 0); EXPECT_EQ(iters_b, 0); eq.run(); EXPECT_EQ(iters_a, iters_b); } // NOLINTNEXTLINE TEST(EventQueue, time_file_fairness) { auto start = system_clock::now(); uint64_t looper_iters = 0; bool stop = false; EventQueue eq; function<void()> looper = [&] { if (stop) { return; } ++looper_iters; if (system_clock::now() > start + 10s) { FAIL(); } eq.add_ready_handler(looper); }; eq.add_ready_handler(looper); bool time_handler_run = false; eq.add_time_handler(start + 20us, [&] { EXPECT_LE(start + 20us, system_clock::now()); time_handler_run = true; }); FileDescriptor fd("/dev/zero", O_RDONLY); int file_iters = 0; EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&](FileEvent /*unused*/) { if (stop) { return eq.remove_handler(hid); } if (system_clock::now() > start + 10s) { FAIL(); return eq.remove_handler(hid); } ++file_iters; }); eq.add_repeating_handler(10us, [&] { if (looper_iters > 4 and file_iters > 4 and time_handler_run) { stop = true; return stop_repeating; } return continue_repeating; }); EXPECT_EQ(looper_iters, 0); EXPECT_EQ(file_iters, 0); EXPECT_EQ(time_handler_run, false); eq.run(); EXPECT_GT(looper_iters, 4); EXPECT_GT(file_iters, 4); EXPECT_EQ(time_handler_run, true); } // NOLINTNEXTLINE TEST(EventQueue, full_fairness) { auto start = system_clock::now(); uint64_t iters_a = 0; uint64_t iters_b = 0; bool stop = false; EventQueue eq; FileDescriptor fd_a("/dev/zero", O_RDONLY); EventQueue::handler_id_t file_a_hid = eq.add_file_handler(fd_a, FileEvent::READABLE, [&](FileEvent /*unused*/) { if (stop) { return eq.remove_handler(file_a_hid); } if (system_clock::now() > start + 10s) { FAIL(); return eq.remove_handler(file_a_hid); } ++iters_a; }); FileDescriptor fd_b("/dev/null", O_WRONLY); EventQueue::handler_id_t file_b_hid = eq.add_file_handler(fd_b, FileEvent::WRITEABLE, [&](FileEvent /*unused*/) { if (stop) { return eq.remove_handler(file_b_hid); } if (system_clock::now() > start + 10s) { FAIL(); return eq.remove_handler(file_b_hid); } ++iters_b; }); uint looper_iters = 0; function<void()> looper = [&] { if (stop) { return; } ++looper_iters; if (system_clock::now() > start + 10s) { FAIL(); } eq.add_ready_handler(looper); }; eq.add_ready_handler(looper); bool time_handler_run = false; eq.add_time_handler(start + 20us, [&] { EXPECT_LE(start + 20us, system_clock::now()); time_handler_run = true; }); eq.add_repeating_handler(10us, [&] { if (looper_iters > 4 and iters_a > 4 and iters_b > 4 and time_handler_run) { stop = true; return stop_repeating; } return continue_repeating; }); EXPECT_EQ(looper_iters, 0); EXPECT_EQ(iters_a, 0); EXPECT_EQ(iters_b, 0); EXPECT_EQ(time_handler_run, false); eq.run(); EXPECT_GT(looper_iters, 4); EXPECT_GT(iters_a, 4); EXPECT_GT(iters_b, 4); EXPECT_NEAR(iters_a, iters_b, 1); EXPECT_EQ(time_handler_run, true); } // NOLINTNEXTLINE TEST(EventQueue, file_unready_read_and_close_event) { std::array<int, 2> pfd{}; ASSERT_EQ(pipe2(pfd.data(), O_NONBLOCK | O_CLOEXEC), 0); FileDescriptor rfd(pfd[0]); FileDescriptor wfd(pfd[1]); std::string buff(10, '\0'); EventQueue eq; auto start = system_clock::now(); eq.add_time_handler(start + 20us, [&] { write(wfd, "Test", sizeof("Test")); }); EXPECT_EQ(read(rfd, buff.data(), buff.size()), -1); EXPECT_EQ(errno, EAGAIN); int round = 0; std::array expected_events = {FileEvent::READABLE, FileEvent::CLOSED}; EventQueue::handler_id_t hid = eq.add_file_handler(rfd, FileEvent::READABLE, [&](FileEvent events) { eq.add_ready_handler([&] { (void)wfd.close(); }); EXPECT_EQ(events, expected_events[round++]); if (events == FileEvent::CLOSED) { return eq.remove_handler(hid); } int rc = read(rfd, buff.data(), buff.size()); ASSERT_EQ(rc, sizeof("Test")); buff.resize(rc - 1); ASSERT_EQ(buff, "Test"); }); EXPECT_EQ(round, 0); eq.run(); EXPECT_EQ(round, 2); } // NOLINTNEXTLINE TEST(EventQueue, file_simultaneous_read_and_close_event) { std::array<int, 2> pfd{}; ASSERT_EQ(pipe2(pfd.data(), O_NONBLOCK | O_CLOEXEC), 0); FileDescriptor rfd(pfd[0]); FileDescriptor wfd(pfd[1]); write(wfd, "Test", sizeof("Test")); (void)wfd.close(); int times = 0; EventQueue eq; EventQueue::handler_id_t hid = eq.add_file_handler(rfd, FileEvent::READABLE, [&](FileEvent events) { ++times; EXPECT_EQ(events, FileEvent::READABLE | FileEvent::CLOSED); eq.remove_handler(hid); }); EXPECT_EQ(times, 0); eq.run(); EXPECT_EQ(times, 1); } // NOLINTNEXTLINE TEST(EventQueueDeathTest, time_handler_removing_itself) { auto start = system_clock::now(); EventQueue eq; int iters = 0; EventQueue::handler_id_t hid = eq.add_time_handler(start + 10us, [&] { ++iters; ASSERT_DEATH({ eq.remove_handler(hid); }, ""); }); EXPECT_EQ(iters, 0); eq.run(); EXPECT_EQ(iters, 1); } // NOLINTNEXTLINE TEST(EventQueue, file_handler_removing_itself) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters = 0; EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&](FileEvent /*unused*/) { ++iters; eq.remove_handler(hid); }); EXPECT_EQ(iters, 0); eq.run(); EXPECT_EQ(iters, 1); } // NOLINTNEXTLINE TEST(EventQueue, time_handler_removing_file_handler) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters = 0; auto hid = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters; }); eq.add_repeating_handler(10us, [&] { if (iters > 4) { eq.remove_handler(hid); return stop_repeating; } return continue_repeating; }); EXPECT_EQ(iters, 0); eq.run(); EXPECT_GT(iters, 4); } // NOLINTNEXTLINE TEST(EventQueue, time_handler_removing_file_handler_while_processing_file_handlers) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters_a = 0; int iters_b = 0; EventQueue::handler_id_t hid_a = 0; EventQueue ::handler_id_t hid_b = 0; hid_a = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_a; eq.add_ready_handler([&] { EXPECT_EQ(iters_b, 0); eq.remove_handler(hid_b); }); std::this_thread::sleep_for(1ms); // Makes the time quantum of file handlers expire, so // that time handlers are processed just after this // handler finishes eq.remove_handler(hid_a); }); hid_b = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_b; eq.remove_handler(hid_b); // In case of error }); EXPECT_EQ(iters_a, 0); EXPECT_EQ(iters_b, 0); eq.run(); EXPECT_EQ(iters_a, 1); EXPECT_EQ(iters_b, 0); } // NOLINTNEXTLINE TEST(EventQueue, file_handler_removing_other_file_handler) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue::handler_id_t hid_a = 0; EventQueue::handler_id_t hid_b = 0; EventQueue::handler_id_t hid_c = 0; EventQueue::handler_id_t hid_d = 0; int iters_a = 0; int iters_b = 0; int iters_c = 0; int iters_d = 0; EventQueue eq; hid_a = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_a; if (iters_a == 1) { eq.remove_handler(hid_b); } }); hid_b = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_b; ASSERT_LT(iters_b, 1000); // In case of error }); hid_c = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_c; ASSERT_LT(iters_c, 1000); // In case of error }); hid_d = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_d; if (iters_d == 1) { eq.remove_handler(hid_c); } else if (iters_d == 2) { eq.add_ready_handler([&] { eq.remove_handler(hid_a); eq.remove_handler(hid_d); }); } }); EXPECT_EQ(iters_a, 0); EXPECT_EQ(iters_b, 0); EXPECT_EQ(iters_c, 0); EXPECT_EQ(iters_d, 0); eq.run(); EXPECT_GT(iters_a, 1); EXPECT_EQ(iters_b, 0); EXPECT_EQ(iters_c, 1); EXPECT_GE(iters_d, 2); } // NOLINTNEXTLINE TEST(EventQueue, adding_new_file_handlers_after_removing_old_ones) { FileDescriptor fd("/dev/null", O_RDONLY); vector<EventQueue::handler_id_t> hids; vector<int> iters; EventQueue eq; for (int i = 0; i < 100; ++i) { constexpr auto handlers_to_add = 10; eq.add_ready_handler([&] { for (int j = 0; j < handlers_to_add; ++j) { auto hid = eq.add_file_handler( fd, FileEvent::READABLE, [&eq, &iters, &hids, idx = hids.size()] { ++iters[idx]; eq.remove_handler(hids[idx]); }); hids.emplace_back(hid); iters.emplace_back(0); } }); } EXPECT_EQ(size(iters), 0); EXPECT_EQ(size(hids), 0); eq.run(); EXPECT_EQ(size(iters), size(hids)); for (size_t i = 0; i < size(iters); ++i) { EXPECT_EQ(iters[i], 1) << "i: " << i; } } // NOLINTNEXTLINE TEST(EventQueue, move_constructor_and_move_operator) { EventQueue eq; string order; int run = 0; array iters_a = {0, 0}; array iters_b = {0, 0}; eq.add_repeating_handler(10us, [&] { ++iters_a[run]; return iters_a[1] == 5 ? stop_repeating : continue_repeating; }); eq.add_repeating_handler(20us, [&] { ++iters_b[run]; return iters_b[1] == 3 ? stop_repeating : continue_repeating; }); int times_pipe_was_read = 0; std::array<int, 2> pfd{}; ASSERT_EQ(pipe2(pfd.data(), O_CLOEXEC), 0); Defer guard = [&pfd] { for (int fd : pfd) { (void)close(fd); } }; // File handler that will read twice: before and after the pause EventQueue::handler_id_t fhid = 0; fhid = eq.add_file_handler(pfd[0], FileEvent::READABLE, [&]() { std::array<char, 2> buf{}; ASSERT_EQ(read(pfd[0], buf.data(), buf.size()), 1); if (++times_pipe_was_read == 2) { eq.remove_handler(fhid); } }); ASSERT_EQ(write(pfd[1], "x", 1), 1); eq.add_repeating_handler(100us, [&] { if (iters_a[0] > 5 and iters_b[0] > 3 and times_pipe_was_read > 0) { eq.pause_immediately(); return stop_repeating; } return continue_repeating; }); EXPECT_EQ(iters_a, (array{0, 0})); EXPECT_EQ(iters_b, (array{0, 0})); eq.run(); EXPECT_GT(iters_a[0], 5); EXPECT_GT(iters_b[0], 3); EXPECT_EQ(times_pipe_was_read, 1); // Move eq around bool r1 = false; bool r2 = false; eq.add_ready_handler([&] { r1 = true; }); EventQueue other = std::move(eq); other.add_ready_handler([&] { r2 = true; }); eq = std::move(other); // Second run ASSERT_EQ(write(pfd[1], "y", 1), 1); run = 1; eq.run(); EXPECT_EQ(iters_a[1], 5); EXPECT_EQ(iters_b[1], 3); EXPECT_EQ(times_pipe_was_read, 2); EXPECT_EQ(r1, true); EXPECT_EQ(r2, true); }
mit
iamso/u.strength.js
dist/u.strength.js
2745
/*! * u.strength.js - Version 0.4.0 * password strength plugin for u.js/jquery * Author: Steve Ottoz <so@dev.so> * Build date: 2016-07-29 * Copyright (c) 2016 Steve Ottoz * Released under the MIT license */ ;(function (factory) { 'use strict'; if (/^f/.test(typeof define) && define.amd) { define(['ujs'], factory); } else if (/^o/.test(typeof exports)) { factory(require('ujs')); } else { factory(ujs); } })(function ($) { 'use strict'; var pluginName = 'strength', defaults = { meter: '#password-meter', classes: [ 'veryweak', 'veryweak', 'weak', 'medium', 'strong', 'secure' ], specialChars: /[^a-zA-Z0-9]/, delay: 0, min: 8 }; function Strength(element, options) { this.el = element; this.$el = $(this.el); this.options = $.extend({}, defaults, options); this._defaults = defaults; this.init(); } Strength.prototype = { init: function() { var characters = 0; var capitalletters = 0; var loweletters = 0; var number = 0; var special = 0; var upperCase = /[A-Z]/; var lowerCase = /[a-z]/; var numbers = /[0-9]/; var specialChars = this.options.specialChars; var classes = this.options.classes; var meter = $(this.options.meter); var min = this.options.min; var checkDelay = this.options.delay; var checkTimeout; function checkStrength(value, total, exponent) { exponent = value.length > min ? 1 + (value.length / 100) : 1; characters = Math.floor(value.length / (min * exponent)) || -1; capitalletters = +!!value.match(upperCase); loweletters = +!!value.match(lowerCase); number = +!!value.match(numbers); special = +!!value.match(specialChars); total = characters + capitalletters + loweletters + number + special; !value.length && (total = -1); updateMeter(total); } function updateMeter(total) { meter.removeClass(classes.join(' ')); total >= 0 && meter.addClass(classes[Math.min(total, classes.length -1)]); } this.$el.on('input', function(event) { clearTimeout(checkTimeout); checkTimeout = setTimeout(checkStrength, checkDelay, this.value); }).trigger('input'); } }; // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn[pluginName] = function(options) { return this.each(function() { if (!$(this).data(pluginName)) { $(this).data(pluginName, new Strength(this, options)); } }); }; });
mit
ahazem/ember-simple-auth-tok
specs/simple-auth-tok/configuration-test.js
1701
import Configuration from '/simple-auth-tok/configuration'; describe('Configuration', function() { describe('serverAuthenticateEndpoint', function() { it('defaults to /login', function() { expect(Configuration.serverAuthenticateEndpoint).to.eq('/login'); }); }); describe('serverInvalidateEndpoint', function() { it('defaults to /logout', function() { expect(Configuration.serverInvalidateEndpoint).to.eq('/logout'); }); }); describe('modelName', function() { it('defaults to "user"', function() { expect(Configuration.modelName).to.eq('user'); }); }); describe('tokenAttributeName', function() { it('defaults to "token"', function() { expect(Configuration.tokenAttributeName).to.eq('token'); }); }); describe('.load', function() { it('sets serverAuthenticateEndpoint correctly', function() { Configuration.load(this.container, { serverAuthenticateEndpoint: '/sign_in' }); expect(Configuration.serverAuthenticateEndpoint).to.eq('/sign_in'); }); it('sets serverInvalidateEndpoint correctly', function() { Configuration.load(this.container, { serverInvalidateEndpoint: '/sign_out' }); expect(Configuration.serverInvalidateEndpoint).to.eq('/sign_out'); }); it('sets modelName correctly', function() { Configuration.load(this.container, { modelName: 'account' }); expect(Configuration.modelName).to.eq('account'); }); it('sets tokenAttributeName correctly', function() { Configuration.load(this.container, { tokenAttributeName: 'authenticationToken' }); expect(Configuration.tokenAttributeName).to.eq('authenticationToken'); }); }); });
mit
allotory/coeligena
src/main/java/com/coeligena/dao/RoleAuthUserDAO.java
271
package com.coeligena.dao; import com.coeligena.model.RoleAuthUserDO; /** * <p> * 角色验证用户数据访问接口 * </p> * Created by Ellery on 2017/12/16. */ public interface RoleAuthUserDAO { void saveRoleAuthUser(RoleAuthUserDO roleAuthUserDO); }
mit
ZhackerZ/Capstone
iRehab/db/migrate/20160418201727_create_records.rb
405
class CreateRecords < ActiveRecord::Migration def up create_table :records, force: :cascade do |r| r.string "username", limit: 10, null: false r.string "appointment_date", null: false r.string "appointment_time", null: false r.string "advisor", limit: 20, null: false r.string "description", limit: 1000 r.string "instruction", limit: 1000 end end def down drop_table :records end end
mit
studiodev/play2-client-logging
modules/clientlog/client/karma-e2e.conf.js
1124
// Karma E2E configuration // Base path, that will be used to resolve files and exclude. basePath = ''; // List of files / patterns to load in the browser. files = [ ANGULAR_SCENARIO, ANGULAR_SCENARIO_ADAPTER, 'test/e2e/**/*.js' ]; // List of files to exclude. exclude = []; // Test results reporter to use. // Possible values: dots || progress || growl. reporters = ['progress']; // Web server port port = 8080; // cli runner port runnerPort = 9100; // Enable / disable colors in the output (reporters and logs). colors = true; // Level of logging // Possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG. logLevel = LOG_INFO; // Enable / disable watching file and executing tests whenever any file changes. autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['Chrome']; // If browser does not capture in given timeout [ms], kill it. captureTimeout = 5000; // CI mode // If true, it capture browsers, run tests and exit. singleRun = false;
mit
frogstarr78/rails-pg-procs
lib/rails_pg_procs.rb
218
require 'active_record' require "active_support/inflector" require 'lib/inflector' require 'lib/sql_format' require 'lib/schema_procs' require 'lib/schema_dumper' require 'lib/connection_adapters/connection_adapters'
mit
goldsborough/algs4
geometric/java/Geometric/src/PointIntersectionSearch.java
2098
import java.util.ArrayList; /** * Created by petergoldsborough on 10/03/15. */ public class PointIntersectionSearch { public static class Point implements Comparable<Point> { Point(Integer x, Integer y) { this.x = x; this.y = y; } public int compareTo(Point other) { if (this.x < other.x) return -1; else if (this.x > other.x) return +1; else if (this.y > other.y) return +1; else if (this.y < other.y) return -1; else return 0; } public final Integer x; public final Integer y; public Line line; } public static class Line { Line(Point start, Point end) { this.start = start; this.start.line = this; this.end = end; this.end.line = this; } public final Point start; public final Point end; } public static void main(String[] args) { ArrayList<Line> lines = new ArrayList<>(); lines.add(new Line(new Point(0, 1), new Point(5, 1))); lines.add(new Line(new Point(3, 2), new Point(6, 2))); lines.add(new Line(new Point(1, 0), new Point(1, 4))); lines.add(new Line(new Point(4, 0), new Point(4, 3))); for (Point point : PointIntersectionSearch.find(lines)) { System.out.printf("(%d, %d) ", point.x, point.y); } } public static Iterable<Point> find(ArrayList<Line> lines) { ArrayList<Point> points = new ArrayList<>(); for (Line line : lines) { points.add(line.start); points.add(line.end); } points.sort(Point::compareTo); ArrayList<Point> intersections = new ArrayList<>(); BinarySearchTree1D tree = new BinarySearchTree1D(); boolean skip = false; for (Point point : points) { if (skip) { skip = false; continue; } if (isVertical(point.line)) { for (Integer y : tree.rangeSearch(point.y, point.line.end.y)) { intersections.add(new Point(point.x, y)); } skip = true; } else if (point.equals(point.line.start)) { tree.insert(point.y); } else tree.erase(point.y); } return intersections; } public static boolean isVertical(Line line) { return line.start.x.equals(line.end.x); } }
mit
braiins/RelayNode
c++/client.cpp
10822
#include <map> #include <vector> #include <thread> #include <mutex> #include <assert.h> #include <string.h> #include <unistd.h> #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else // WIN32 #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #endif // !WIN32 #define BITCOIN_UA_LENGTH 24 #define BITCOIN_UA {'/', 'R', 'e', 'l', 'a', 'y', 'N', 'e', 't', 'w', 'o', 'r', 'k', 'C', 'l', 'i', 'e', 'n', 't', ':', '4', '2', '/', '\0'} #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include "utils.h" #include "p2pclient.h" /*********************************************** **** Relay network client processing class **** ***********************************************/ class RelayNetworkClient { private: RELAY_DECLARE_CLASS_VARS const char* server_host; const std::function<void (std::vector<unsigned char>&)> provide_block; const std::function<void (std::shared_ptr<std::vector<unsigned char> >&)> provide_transaction; int sock; std::mutex send_mutex; std::thread* net_thread, *new_thread; public: RelayNetworkClient(const char* serverHostIn, const std::function<void (std::vector<unsigned char>&)>& provide_block_in, const std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in) : RELAY_DECLARE_CONSTRUCTOR_EXTENDS, server_host(serverHostIn), provide_block(provide_block_in), provide_transaction(provide_transaction_in), sock(0), net_thread(NULL), new_thread(NULL) { send_mutex.lock(); new_thread = new std::thread(do_connect, this); send_mutex.unlock(); } RelayNetworkClient() : RELAY_DECLARE_CONSTRUCTOR_EXTENDS {} // Fake... RELAY_DECLARE_FUNCTIONS private: void reconnect(std::string disconnectReason, bool alreadyLocked=false) { if (!alreadyLocked) send_mutex.lock(); if (sock) { printf("Closing relay socket, %s (%i: %s)\n", disconnectReason.c_str(), errno, errno ? strerror(errno) : ""); #ifndef WIN32 errno = 0; #endif close(sock); } sleep(1); new_thread = new std::thread(do_connect, this); send_mutex.unlock(); } static void do_connect(RelayNetworkClient* me) { me->send_mutex.lock(); if (me->net_thread) me->net_thread->join(); me->net_thread = me->new_thread; me->sock = socket(AF_INET6, SOCK_STREAM, 0); if (me->sock <= 0) return me->reconnect("unable to create socket", true); sockaddr_in6 addr; if (!lookup_address(me->server_host, &addr)) return me->reconnect("unable to lookup host", true); int v6only = 0; setsockopt(me->sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only)); addr.sin6_port = htons(8336); if (connect(me->sock, (struct sockaddr*)&addr, sizeof(addr))) return me->reconnect("failed to connect()", true); #ifdef WIN32 unsigned long nonblocking = 0; ioctlsocket(me->sock, FIONBIO, &nonblocking); #else fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) & ~O_NONBLOCK); #endif #ifdef X86_BSD int nosigpipe = 1; setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int)); #endif me->net_process(); } void net_process() { recv_tx_cache.clear(); send_tx_cache.clear(); relay_msg_header version_header = { RELAY_MAGIC_BYTES, VERSION_TYPE, htonl(strlen(VERSION_STRING)) }; if (send_all(sock, (char*)&version_header, sizeof(version_header)) != sizeof(version_header)) return reconnect("failed to write version header", true); if (send_all(sock, VERSION_STRING, strlen(VERSION_STRING)) != strlen(VERSION_STRING)) return reconnect("failed to write version string", true); int nodelay = 1; setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay)); if (errno) return reconnect("error during connect", true); send_mutex.unlock(); while (true) { relay_msg_header header; if (read_all(sock, (char*)&header, 4*3) != 4*3) return reconnect("failed to read message header"); if (header.magic != RELAY_MAGIC_BYTES) return reconnect("invalid magic bytes"); uint32_t message_size = ntohl(header.length); if (message_size > 1000000) return reconnect("got message too large"); if (header.type == VERSION_TYPE) { char data[message_size]; if (read_all(sock, data, message_size) < (int64_t)(message_size)) return reconnect("failed to read version message"); if (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size)))) return reconnect("unknown version string"); else printf("Connected to relay node with protocol version %s\n", VERSION_STRING); } else if (header.type == MAX_VERSION_TYPE) { char data[message_size]; if (read_all(sock, data, message_size) < (int64_t)(message_size)) return reconnect("failed to read max_version string"); if (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size)))) printf("Relay network is using a later version (PLEASE UPGRADE)\n"); else return reconnect("got MAX_VERSION of same version as us"); } else if (header.type == BLOCK_TYPE) { auto res = decompressRelayBlock(sock, message_size); if (std::get<2>(res)) return reconnect(std::get<2>(res)); provide_block(*std::get<1>(res)); std::vector<unsigned char> fullhash(32); CSHA256 hash; // Probably not BE-safe hash.Write(&(*std::get<1>(res))[sizeof(struct bitcoin_msg_header)], 80).Finalize(&fullhash[0]); hash.Reset().Write(&fullhash[0], fullhash.size()).Finalize(&fullhash[0]); struct tm tm; time_t now = time(NULL); gmtime_r(&now, &tm); printf("[%d-%02d-%02d %02d:%02d:%02d+00] ", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); for (unsigned int i = 0; i < fullhash.size(); i++) printf("%02x", fullhash[fullhash.size() - i - 1]); printf(" recv'd, size %lu with %u bytes on the wire\n", (unsigned long)std::get<1>(res)->size() - sizeof(bitcoin_msg_header), std::get<0>(res)); } else if (header.type == END_BLOCK_TYPE) { } else if (header.type == TRANSACTION_TYPE) { if (message_size > MAX_RELAY_TRANSACTION_BYTES && (recv_tx_cache.flagCount() >= MAX_EXTRA_OVERSIZE_TRANSACTIONS || message_size > MAX_RELAY_OVERSIZE_TRANSACTION_BYTES)) { printf("Freely relayed tx of size %u, with %lu oversize txn already present\n", message_size, recv_tx_cache.flagCount()); return reconnect("got freely relayed transaction too large"); } auto tx = std::make_shared<std::vector<unsigned char> > (message_size); if (read_all(sock, (char*)&(*tx)[0], message_size) < (int64_t)(message_size)) return reconnect("failed to read loose transaction data"); recv_tx_cache.add(tx, message_size > MAX_RELAY_TRANSACTION_BYTES); provide_transaction(tx); printf("Received transaction of size %u from relay server\n", message_size); } else return reconnect("got unknown message type"); } } public: void receive_transaction(const std::shared_ptr<std::vector<unsigned char> >& tx) { #ifndef FOR_VALGRIND if (!send_mutex.try_lock()) return; #else send_mutex.lock(); #endif if (send_tx_cache.contains(tx) || (tx->size() > MAX_RELAY_TRANSACTION_BYTES && (send_tx_cache.flagCount() >= MAX_EXTRA_OVERSIZE_TRANSACTIONS || tx->size() > MAX_RELAY_OVERSIZE_TRANSACTION_BYTES))) { send_mutex.unlock(); return; } std::vector<unsigned char> msg(sizeof(struct relay_msg_header)); struct relay_msg_header *header = (struct relay_msg_header*)&msg[0]; header->magic = RELAY_MAGIC_BYTES; header->type = TRANSACTION_TYPE; header->length = htonl(tx->size()); msg.insert(msg.end(), tx->begin(), tx->end()); if (send_all(sock, (char*)&msg[0], msg.size()) != int(msg.size())) printf("Error sending transaction to relay server\n"); else { send_tx_cache.add(tx, tx->size() > MAX_RELAY_OVERSIZE_TRANSACTION_BYTES); printf("Sent transaction of size %lu to relay server\n", (unsigned long)tx->size()); } send_mutex.unlock(); } void receive_block(const std::vector<unsigned char>& block) { #ifndef FOR_VALGRIND if (!send_mutex.try_lock()) return; #else send_mutex.lock(); #endif auto compressed_block = compressRelayBlock(block); if (!compressed_block->size()) { printf("Failed to process block from bitcoind\n"); send_mutex.unlock(); return; } if (send_all(sock, (char*)&(*compressed_block)[0], compressed_block->size()) != int(compressed_block->size())) printf("Error sending block to relay server\n"); else { struct relay_msg_header header = { RELAY_MAGIC_BYTES, END_BLOCK_TYPE, 0 }; if (send_all(sock, (char*)&header, sizeof(header)) != int(sizeof(header))) printf("Error sending end block message to relay server\n"); else { std::vector<unsigned char> fullhash(32); CSHA256 hash; // Probably not BE-safe hash.Write(&block[sizeof(struct bitcoin_msg_header)], 80).Finalize(&fullhash[0]); hash.Reset().Write(&fullhash[0], fullhash.size()).Finalize(&fullhash[0]); for (unsigned int i = 0; i < fullhash.size(); i++) printf("%02x", fullhash[fullhash.size() - i - 1]); printf(" sent, size %lu with %lu bytes on the wire\n", (unsigned long)block.size(), (unsigned long)compressed_block->size()); } } send_mutex.unlock(); } }; class P2PClient : public P2PRelayer { public: P2PClient(const char* serverHostIn, uint16_t serverPortIn, const std::function<void (std::vector<unsigned char>&, struct timeval)>& provide_block_in, const std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in) : P2PRelayer(serverHostIn, serverPortIn, provide_block_in, provide_transaction_in) {}; private: bool send_version() { struct bitcoin_version_with_header version_msg; version_msg.version.start.timestamp = htole64(time(0)); version_msg.version.start.user_agent_length = BITCOIN_UA_LENGTH; // Work around apparent gcc bug return send_message("version", (unsigned char*)&version_msg, sizeof(struct bitcoin_version)); } }; int main(int argc, char** argv) { if (argc != 4) { printf("USAGE: %s RELAY_SERVER BITCOIND_ADDRESS BITCOIND_PORT\n", argv[0]); return -1; } #ifdef WIN32 WSADATA wsaData; if (WSAStartup(MAKEWORD(2,2), &wsaData)) return -1; #endif RelayNetworkClient* relayClient; P2PClient p2p(argv[2], std::stoul(argv[3]), [&](std::vector<unsigned char>& bytes, struct timeval) { relayClient->receive_block(bytes); }, [&](std::shared_ptr<std::vector<unsigned char> >& bytes) { relayClient->receive_transaction(bytes); }); relayClient = new RelayNetworkClient(argv[1], [&](std::vector<unsigned char>& bytes) { p2p.receive_block(bytes); }, [&](std::shared_ptr<std::vector<unsigned char> >& bytes) { p2p.receive_transaction(bytes); }); while (true) { sleep(1000); } }
mit
Producenta/TelerikAcademy
C# OOP/Bgcoder/Trade and Travel/Trade and Travel/Program.cs
24292
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TradeAndTravel { public abstract class WorldObject { static readonly Random random = new Random(); public string Id { get; private set; } private const int IdLength = 128; private const string IdChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789_"; private static HashSet<string> allObjectIds = new HashSet<string>(); public string Name { get; protected set; } protected WorldObject(string name = "") { this.Name = name; this.Id = WorldObject.GenerateObjectId(); } public static string GenerateObjectId() { StringBuilder resultBuilder = new StringBuilder(); string result; do { for (int i = 0; i < WorldObject.IdLength; i++) { resultBuilder.Append(IdChars[random.Next(0, WorldObject.IdChars.Length)]); } result = resultBuilder.ToString(); } while (allObjectIds.Contains(result)); return result; } public override int GetHashCode() { return this.Id.GetHashCode(); } public override bool Equals(object obj) { return this.Id.Equals((obj as WorldObject).Id); } } } namespace TradeAndTravel { public class Wood : Item { public Wood(string name, Location location = null) : base(name, 2, ItemType.Wood, location) { } public override void UpdateWithInteraction(string interaction) { switch (interaction) { case "drop": this.Value = this.Value > 0 ? this.Value = this.Value - 1 : this.Value = this.Value; break; default: base.UpdateWithInteraction(interaction); break; } } } } namespace TradeAndTravel { public class Weapon : Item { public Weapon(string name, Location location = null) : base(name, 10, ItemType.Weapon, location) { } } } namespace TradeAndTravel { public class Traveller : Person, ITraveller { public Traveller(string name, Location location) : base(name, location) { } public virtual void TravelTo(Location location) { this.Location = location; } } } namespace TradeAndTravel { public class Town : Location { public Town(string name) : base(name, LocationType.Town) { } } } namespace TradeAndTravel { public class Shopkeeper : Person, IShopkeeper { public Shopkeeper(string name, Location location) : base(name, location) { } public virtual int CalculateSellingPrice(Item item) { return item.Value; } public virtual int CalculateBuyingPrice(Item item) { return item.Value / 2; } } } namespace TradeAndTravel { class Program { static void Main(string[] args) { var engine = new Engine(new ExtendedInteractionManager()); engine.Start(); } } } namespace TradeAndTravel { public class Person : WorldObject { HashSet<Item> inventoryItems; public Location Location { get; protected set; } public Person(string name, Location location) : base(name) { this.Location = location; this.inventoryItems = new HashSet<Item>(); } public void AddToInventory(Item item) { this.inventoryItems.Add(item); } public void RemoveFromInventory(Item item) { this.inventoryItems.Remove(item); } public List<Item> ListInventory() { List<Item> items = new List<Item>(); foreach (var item in this.inventoryItems) { items.Add(item); } return items; } } } namespace TradeAndTravel { public class Mine : GatheringInformation { public Mine(string name) : base(name,LocationType.Mine, ItemType.Iron, ItemType.Armor) { } public override Item ProduceItem(string name) { return new Iron(name, null); } } } namespace TradeAndTravel { public class Merchant : Shopkeeper, ITraveller { public Merchant(string name, Location location) : base(name, location) { } public void TravelTo(Location location) { this.Location = location; } } } namespace TradeAndTravel { public enum LocationType { Mine, Town, Forest, } } namespace TradeAndTravel { public abstract class Location : WorldObject { public LocationType LocationType { get; private set; } public Location(string name, string type) : base(name) { foreach (var locType in (LocationType[])Enum.GetValues(typeof(LocationType))) { if (locType.ToString() == type) { this.LocationType = locType; } } } public Location(string name, LocationType type) : base(name) { this.LocationType = type; } } } namespace TradeAndTravel { public interface ITraveller { void TravelTo(Location location); Location Location {get;} } } namespace TradeAndTravel { public enum ItemType { Weapon, Armor, Wood, Iron, } } namespace TradeAndTravel { public abstract class Item : WorldObject { public ItemType ItemType { get; private set; } public int Value { get; protected set; } protected Item(string name, int itemValue, string type, Location location = null) : base(name) { this.Value = itemValue; foreach (var itemType in (ItemType[])Enum.GetValues(typeof(ItemType))) { if (itemType.ToString() == type) { this.ItemType = itemType; } } } protected Item(string name, int itemValue, ItemType type, Location location = null) : base(name) { this.Value = itemValue; this.ItemType = type; } public virtual void UpdateWithInteraction(string interaction) { } } } namespace TradeAndTravel { public interface IShopkeeper { int CalculateSellingPrice(Item item); int CalculateBuyingPrice(Item item); } } namespace TradeAndTravel { public class Iron : Item { public Iron(string name, Location location = null) : base(name, 3, ItemType.Iron, location) { } } } namespace TradeAndTravel { public class InteractionManager { const int InitialPersonMoney = 100; protected Dictionary<Person, int> moneyByPerson = new Dictionary<Person, int>(); protected Dictionary<Item, Person> ownerByItem = new Dictionary<Item, Person>(); protected Dictionary<Location, List<Item>> strayItemsByLocation = new Dictionary<Location, List<Item>>(); protected HashSet<Location> locations = new HashSet<Location>(); protected HashSet<Person> people = new HashSet<Person>(); protected Dictionary<string, Person> personByName = new Dictionary<string, Person>(); protected Dictionary<string, Location> locationByName = new Dictionary<string, Location>(); protected Dictionary<Location, List<Person>> peopleByLocation = new Dictionary<Location, List<Person>>(); public void HandleInteraction(string[] commandWords) { if (commandWords[0] == "create") { this.HandleCreationCommand(commandWords); } else { var actor = this.personByName[commandWords[0]]; this.HandlePersonCommand(commandWords, actor); } } protected virtual void HandlePersonCommand(string[] commandWords, Person actor) { switch (commandWords[1]) { case "drop": HandleDropInteraction(actor); break; case "pickup": HandlePickUpInteraction(actor); break; case "sell": this.HandleSellInteraction(commandWords, actor); break; case "buy": HandleBuyInteraction(commandWords, actor); break; case "inventory": HandleListInventoryInteraction(actor); break; case "money": Console.WriteLine(moneyByPerson[actor]); break; case "travel": HandleTravelInteraction(commandWords, actor); break; default: break; } } private void HandleTravelInteraction(string[] commandWords, Person actor) { var traveller = actor as ITraveller; if (traveller != null) { var targetLocation = this.locationByName[commandWords[2]]; peopleByLocation[traveller.Location].Remove(actor); traveller.TravelTo(targetLocation); peopleByLocation[traveller.Location].Add(actor); foreach (var item in actor.ListInventory()) { item.UpdateWithInteraction("travel"); } } } private void HandleListInventoryInteraction(Person actor) { var inventory = actor.ListInventory(); foreach (var item in inventory) { if (ownerByItem[item] == actor) { Console.WriteLine(item.Name); item.UpdateWithInteraction("inventory"); } } if (inventory.Count == 0) { Console.WriteLine("empty"); } } private void HandlePickUpInteraction(Person actor) { foreach (var item in strayItemsByLocation[actor.Location]) { this.AddToPerson(actor, item); item.UpdateWithInteraction("pickup"); } strayItemsByLocation[actor.Location].Clear(); } private void HandleDropInteraction(Person actor) { foreach (var item in actor.ListInventory()) { if (ownerByItem[item] == actor) { strayItemsByLocation[actor.Location].Add(item); this.RemoveFromPerson(actor, item); item.UpdateWithInteraction("drop"); } } } private void HandleBuyInteraction(string[] commandWords, Person actor) { Item saleItem = null; string saleItemName = commandWords[2]; var buyer = personByName[commandWords[3]] as Shopkeeper; if (buyer != null && peopleByLocation[actor.Location].Contains(buyer)) { foreach (var item in buyer.ListInventory()) { if (ownerByItem[item] == buyer && saleItemName == item.Name) { saleItem = item; } } var price = buyer.CalculateSellingPrice(saleItem); moneyByPerson[buyer] += price; moneyByPerson[actor] -= price; this.RemoveFromPerson(buyer, saleItem); this.AddToPerson(actor, saleItem); saleItem.UpdateWithInteraction("buy"); } } private void HandleSellInteraction(string[] commandWords, Person actor) { Item saleItem = null; string saleItemName = commandWords[2]; foreach (var item in actor.ListInventory()) { if (ownerByItem[item] == actor && saleItemName == item.Name) { saleItem = item; } } var buyer = personByName[commandWords[3]] as Shopkeeper; if (buyer != null && peopleByLocation[actor.Location].Contains(buyer)) { var price = buyer.CalculateBuyingPrice(saleItem); moneyByPerson[buyer] -= price; moneyByPerson[actor] += price; this.RemoveFromPerson(actor, saleItem); this.AddToPerson(buyer, saleItem); saleItem.UpdateWithInteraction("sell"); } } protected void AddToPerson(Person actor, Item item) { actor.AddToInventory(item); ownerByItem[item] = actor; } protected void RemoveFromPerson(Person actor, Item item) { actor.RemoveFromInventory(item); ownerByItem[item] = null; } protected void HandleCreationCommand(string[] commandWords) { if (commandWords[1] == "item") { string itemTypeString = commandWords[2]; string itemNameString = commandWords[3]; string itemLocationString = commandWords[4]; this.HandleItemCreation(itemTypeString, itemNameString, itemLocationString); } else if (commandWords[1] == "location") { string locationTypeString = commandWords[2]; string locationNameString = commandWords[3]; this.HandleLocationCreation(locationTypeString, locationNameString); } else { string personTypeString = commandWords[1]; string personNameString = commandWords[2]; string personLocationString = commandWords[3]; this.HandlePersonCreation(personTypeString, personNameString, personLocationString); } } protected virtual void HandleLocationCreation(string locationTypeString, string locationName) { Location location = CreateLocation(locationTypeString, locationName); locations.Add(location); strayItemsByLocation[location] = new List<Item>(); peopleByLocation[location] = new List<Person>(); locationByName[locationName] = location; } protected virtual void HandlePersonCreation(string personTypeString, string personNameString, string personLocationString) { var personLocation = locationByName[personLocationString]; Person person = CreatePerson(personTypeString, personNameString, personLocation); personByName[personNameString] = person; peopleByLocation[personLocation].Add(person); moneyByPerson[person] = InteractionManager.InitialPersonMoney; } protected virtual void HandleItemCreation(string itemTypeString, string itemNameString, string itemLocationString) { var itemLocation = locationByName[itemLocationString]; Item item = null; item = CreateItem(itemTypeString, itemNameString, itemLocation, item); ownerByItem[item] = null; strayItemsByLocation[itemLocation].Add(item); } protected virtual Item CreateItem(string itemTypeString, string itemNameString, Location itemLocation, Item item) { switch (itemTypeString) { case "armor": item = new Armor(itemNameString, itemLocation); break; default: break; } return item; } protected virtual Person CreatePerson(string personTypeString, string personNameString, Location personLocation) { Person person = null; switch (personTypeString) { case "shopkeeper": person = new Shopkeeper(personNameString, personLocation); break; case "traveller": person = new Traveller(personNameString, personLocation); break; default: break; } return person; } protected virtual Location CreateLocation(string locationTypeString, string locationName) { Location location = null; switch (locationTypeString) { case "town": location = new Town(locationName); break; default: break; } return location; } } } namespace TradeAndTravel { public interface IGatheringLocation { ItemType GatheredType { get; } ItemType RequiredItem { get; } Item ProduceItem(string name); } } namespace TradeAndTravel { public abstract class GatheringInformation : Location, IGatheringLocation { public ItemType GatheredType { get; protected set;} public ItemType RequiredItem { get; protected set; } public GatheringInformation(string name, LocationType location, ItemType gatheredType, ItemType requiredType) : base(name, location) { this.GatheredType = gatheredType; this.RequiredItem = requiredType; } public abstract Item ProduceItem(string name); } } namespace TradeAndTravel { public class Forest : GatheringInformation { public Forest(string name) : base(name, LocationType.Forest, ItemType.Wood, ItemType.Weapon) { } public override Item ProduceItem(string name) { return new Wood(name, null); } } } namespace TradeAndTravel { public class ExtendedInteractionManager : InteractionManager { protected override Item CreateItem(string itemTypeString, string itemNameString, Location itemLocation, Item item) { switch (itemTypeString) { case "weapon": item = new Weapon(itemNameString, itemLocation); break; case "wood": item = new Wood(itemNameString, itemLocation); break; case "iron": item = new Iron(itemNameString, itemLocation); break; default: item = base.CreateItem(itemTypeString, itemNameString, itemLocation, item); break; } return item; } protected override Location CreateLocation(string locationTypeString, string locationName) { Location location = null; switch (locationTypeString) { case "mine": location = new Mine(locationName); break; case "forest": location = new Forest(locationName); break; default: location = base.CreateLocation(locationTypeString, locationName); break; } return location; } protected override void HandlePersonCommand(string[] commandWords, Person actor) { switch (commandWords[1]) { case "gather": HadleGatherInteraction(actor, commandWords[2]); break; case "craft": HadleCraftInteraction(actor, commandWords[2], commandWords[3]); break; default: base.HandlePersonCommand(commandWords, actor); break; } } private void HadleCraftInteraction(Person actor, string craftItemType, string craftItemName) { switch (craftItemType) { case "armor": CraftArmor(actor, craftItemName); break; case "weapon": CraftWeapon(actor, craftItemName); break; default: break; } } private void CraftWeapon(Person actor, string craftItemName) { var actorInventory = actor.ListInventory(); if (actorInventory.Any((item) => item.ItemType == ItemType.Iron && item.ItemType == ItemType.Wood)) { this.AddToPerson(actor, new Weapon(craftItemName, null)); } } private void CraftArmor(Person actor, string craftItemName) { var actorInventory = actor.ListInventory(); if (actorInventory.Any((item) => item.ItemType == ItemType.Iron)) { this.AddToPerson(actor, new Armor(craftItemName, null)); } } private void HadleGatherInteraction(Person actor, string ItemName) { var actorInventory = actor.ListInventory(); var IsGatherType = actor.Location as IGatheringLocation; if (IsGatherType != null) { foreach (var actorInv in actorInventory) { if (actorInv.ItemType == IsGatherType.RequiredItem) { var createItem = IsGatherType.ProduceItem(ItemName); this.AddToPerson(actor,createItem); break; } } } } protected override Person CreatePerson(string personTypeString, string personNameString, Location personLocation) { Person person = null; switch (personTypeString) { case "merchant": person = new Shopkeeper(personNameString, personLocation); break; default: person = base.CreatePerson(personTypeString, personNameString, personLocation); break; } return person; } } } namespace TradeAndTravel { public class Engine { protected InteractionManager interactionManager; public Engine(InteractionManager interactionManager) { this.interactionManager = interactionManager; } public void ParseAndDispatch(string command) { this.interactionManager.HandleInteraction(command.Split(' ')); } public void Start() { bool endCommandReached = false; while (!endCommandReached) { string command = Console.ReadLine(); if (command != "end") { this.ParseAndDispatch(command); } else { endCommandReached = true; } } } } } namespace TradeAndTravel { public class Armor : Item { const int GeneralArmorValue = 5; public Armor(string name, Location location = null) : base(name, Armor.GeneralArmorValue, ItemType.Armor, location) { } static List<ItemType> GetComposingItems() { return new List<ItemType>() { ItemType.Iron }; } } }
mit
NyaaPantsu/nyaa
models/users/helpers.go
2196
package users import ( "errors" "net/http" "strconv" "github.com/NyaaPantsu/nyaa/models" "github.com/NyaaPantsu/nyaa/utils/log" "github.com/NyaaPantsu/nyaa/utils/validator/user" "golang.org/x/crypto/bcrypt" ) // CheckEmail : check if email is in database func CheckEmail(email string) bool { if len(email) == 0 { return false } var count int models.ORM.Model(models.User{}).Where("email = ?", email).Count(&count) return count != 0 } // Exists : check if the users credentials match to a user in db func Exists(email string, pass string) (user *models.User, status int, err error) { if email == "" || pass == "" { return user, http.StatusNotFound, errors.New("no_username_password") } var userExist = &models.User{} // search by email or username if userValidator.EmailValidation(email) { if models.ORM.Where("email = ?", email).First(userExist).RecordNotFound() { status, err = http.StatusNotFound, errors.New("user_not_found") return } } else if models.ORM.Where("username = ?", email).First(userExist).RecordNotFound() { status, err = http.StatusNotFound, errors.New("user_not_found") return } user = userExist err = bcrypt.CompareHashAndPassword([]byte(userExist.Password), []byte(pass)) if err != nil { status, err = http.StatusUnauthorized, errors.New("incorrect_password") return } if userExist.IsScraped() { status, err = http.StatusUnauthorized, errors.New("account_need_activation") return } status, err = http.StatusOK, nil return } // SuggestUsername suggest user's name if user's name already occupied. func SuggestUsername(username string) string { var count int var usernameCandidate string models.ORM.Model(models.User{}).Where(&models.User{Username: username}).Count(&count) log.Debugf("count Before : %d", count) if count == 0 { return username } var postfix int for { usernameCandidate = username + strconv.Itoa(postfix) log.Debugf("usernameCandidate: %s\n", usernameCandidate) models.ORM.Model(models.User{}).Where(&models.User{Username: usernameCandidate}).Count(&count) log.Debugf("count after : %d\n", count) postfix = postfix + 1 if count == 0 { break } } return usernameCandidate }
mit
leadwit/AdminUI
service-manager/modules/systemParam/controller/add-controller.js
1054
(function($) { var ngmod = angular.module("framework.controllers", ["framework.systemParamService"]); ngmod.controller("systemParamAddCtrl",function($scope,systemParamRES,systemParamTRES){ $scope.project = new Object(); $scope.project.status="1"; $scope.project.required="1"; $scope.project.direction="0"; systemParamTRES.get({ method:"tlist", category : "SIMPLE" }, function(project) { $scope.typeList = project.models; }); $scope.save = function(invalid) { if(invalid){ alert('错误信息:必填信息不能为空,请检查表单项!'); return; } systemParamRES.save({'method':"add"},$scope.project, function(project) { if(project.respCode=="00"){ alert('温馨提示:操作成功'); }else { alert('操作失败'+project.respDesc); } }); }; }); })(jQuery);
mit
tavaresgerson/scriptum
admin/index.php
5218
<?php spl_autoload_register(function($class){ require_once '../class/'.$class.'.php'; require_once '../class/defines.php'; }); if(session_status() == 1 || session_status() == 0) session_start(); ClassAccess::access_prot_pag(); ?> <!DOCTYPE HTML> <html lang="pt-br"> <head> <meta charset="utf-8"> <meta name="robots" content="noindex, nofollow"> <meta name="robots" content="noarchive"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><?php echo SITE_TITLE.' '.$_SESSION['usuarioNome']; ?></title> <link rel="shortcut icon" href="img/favicon.png" /> <link type="text/css" rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css" /> <link type="text/css" rel="stylesheet" href="assets/css/resets.css" /> <link type="text/css" rel="stylesheet" href="assets/css/layout.css" /> <link type="text/css" rel="stylesheet" href="assets/css/sidebar.css" /> <link type="text/css" rel="stylesheet" href="assets/css/layout_index.css" /> <script type="text/javascript" src="assets/js-plugins/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="assets/js-plugins/jquery-ui.min.js"></script> <script type="text/javascript" src="assets/js-plugins/jquery.mobile.custom.min.js"></script> <script type="text/javascript" src="assets/js/sidebar.js"></script> <script src="assets/js/index.js" type="text/javascript"></script> </head> <body> <?php include('assets/sidebar.php'); ?> <div class="content_section_title" style="background: url(assets/img/inicio.jpg) scroll center center no-repeat;background-size:cover;-moz-background-size:cover;-webkit-background-size:cover;"> <div class="content_section_title_inner"> <h1>Bem vindo <?php echo $_SESSION['usuarioNome']; ?></h1> </div> <div class="content_section_title_color"></div> </div> <section class="content"> <div class="box1 clearfix"> <div class="box1_left"> <div class="box1_left_inner"> <h1><i class="fa fa-user-circle fa-fw"></i> Últimos Acessos</h1> <div class="box1_left_inner_list"> <?php $LastAccess = new ClassAccess(); $DataAccess = $LastAccess->AccessReturnReg(0, 6); if($DataAccess != false){ foreach($DataAccess as $UsersData){ echo '<div class="box1_left_inner_line">'; echo '<h2><i class="fa fa-laptop fa-fw"></i> '.$UsersData->acesso_nome.' - <span>'.$UsersData->acesso_descricao.'</span></h2>'; echo '<h3>'.date('d/m/Y H:i', strtotime($UsersData->acesso_data)).'h</h3>'; echo '</div>'; } }else{ echo '<div class="box1_left_inner_line">'; echo '<h2><i class="fa fa-info-circle"></i> Nenhum Registro</h2>'; echo '</div>'; } ?> </div> </div> </div> <div class="box1_right"> <div class="box1_right_inner"> <h1><i class="fa fa-address-book fa-fw"></i> Atividades Recentes</h1> <div class="box1_right_inner_list"> <?php $Activity = new ClassActivity(); $Data = $Activity->getActivityReg(0, 8); if($Data != false){ foreach($Data as $values){ echo '<div class="box1_right_inner_line">'; echo '<h2><i class="fa fa-info-circle fa-fw"></i> '.$values->atividade_usuario_nome.' - <span>'.$values->atividade_descricao.'</span></h2>'; echo '<h3>Registrado em: '.date('d/m/Y H:i', strtotime($values->atividade_hora)).'h</h3>'; echo '</div>'; } } ?> </div> </div> </div> </div> <div class="posts"> <div class="box2 clearfix"> </div> <div class="more">Mais</div> <div class="endload">Acabou a tinta...</div> </div> </section> </body> </html>
mit
hpham33/schoolmanager
modules/users/client/controllers/authentication.client.controller.js
1949
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator', function ($scope, $state, $http, $location, $window, Authentication, PasswordValidator) { $scope.authentication = Authentication; $scope.popoverMsg = PasswordValidator.getPopoverMsg(); // Get an eventual error defined in the URL query string: $scope.error = $location.search().err; // If user is signed in then redirect back home if ($scope.authentication.user) { $location.path('/'); } $scope.signup = function () { $scope.error = null; $http.post('/api/auth/signup', $scope.credentials).success(function (response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the previous or home page $state.go($state.previous.state.name || 'home', $state.previous.params); }).error(function (response) { $scope.error = response.message; }); }; $scope.signin = function () { $scope.error = null; $http.post('/api/auth/signin', $scope.credentials).success(function (response) { // If successful we assign the response to the global user model $scope.authentication.user = response; $window.user = response; // And redirect to the previous or home page $state.go($state.previous.state.name || 'home', $state.previous.params); }).error(function (response) { $scope.error = response.message; }); }; // OAuth provider request $scope.callOauthProvider = function (url) { if ($state.previous && $state.previous.href) { url += '?redirect_to=' + encodeURIComponent($state.previous.href); } // Effectively call OAuth authentication route: $window.location.href = url; }; } ]);
mit
Azure/azure-sdk-for-go
services/search/mgmt/2015-08-19/search/version.go
671
package search import "github.com/Azure/azure-sdk-for-go/version" // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { return "Azure-SDK-For-Go/" + Version() + " search/2015-08-19" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { return version.Number }
mit
DXkite/suda
suda/src/framework/debug/Caller.php
1105
<?php namespace suda\framework\debug; use Psr\Log\LoggerTrait; use function array_merge; /** * 回溯调用者 */ class Caller { protected $ignorePath = [__FILE__]; protected $backtrace; public function __construct(array $backtrace, array $ignorePath =[]) { $this->ignorePath = array_merge($this->ignorePath, $ignorePath); $rc = new \ReflectionClass(LoggerTrait::class); $file = $rc->getFileName(); if ($file) { $this->ignorePath[] = $file; } $this->backtrace = $backtrace; } public function getCallerTrace():?array { foreach ($this->backtrace as $trace) { if (array_key_exists('file', $trace)) { if (!$this->isIgnore($trace['file'])) { return $trace; } } } return null; } protected function isIgnore(string $file):bool { foreach ($this->ignorePath as $path) { if (strpos($file, $path) === 0) { return true; } } return false; } }
mit
messenger4j/messenger4j
src/main/java/com/github/messenger4j/webhook/factory/AccountLinkingEventFactory.java
2388
package com.github.messenger4j.webhook.factory; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_ACCOUNT_LINKING; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_AUTHORIZATION_CODE; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_ID; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_RECIPIENT; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_SENDER; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_STATUS; import static com.github.messenger4j.internal.gson.GsonUtil.Constants.PROP_TIMESTAMP; import static com.github.messenger4j.internal.gson.GsonUtil.getPropertyAsInstant; import static com.github.messenger4j.internal.gson.GsonUtil.getPropertyAsString; import static com.github.messenger4j.internal.gson.GsonUtil.hasProperty; import com.github.messenger4j.webhook.event.AccountLinkingEvent; import com.google.gson.JsonObject; import java.time.Instant; import java.util.Optional; /** * @author Max Grabenhorst * @since 1.0.0 */ final class AccountLinkingEventFactory implements BaseEventFactory<AccountLinkingEvent> { @Override public boolean isResponsible(JsonObject messagingEvent) { return hasProperty(messagingEvent, PROP_ACCOUNT_LINKING); } @Override public AccountLinkingEvent createEventFromJson(JsonObject messagingEvent) { final String senderId = getPropertyAsString(messagingEvent, PROP_SENDER, PROP_ID) .orElseThrow(IllegalArgumentException::new); final String recipientId = getPropertyAsString(messagingEvent, PROP_RECIPIENT, PROP_ID) .orElseThrow(IllegalArgumentException::new); final Instant timestamp = getPropertyAsInstant(messagingEvent, PROP_TIMESTAMP) .orElseThrow(IllegalArgumentException::new); final AccountLinkingEvent.Status status = getPropertyAsString(messagingEvent, PROP_ACCOUNT_LINKING, PROP_STATUS) .map(String::toUpperCase) .map(AccountLinkingEvent.Status::valueOf) .orElseThrow(IllegalArgumentException::new); final Optional<String> authorizationCode = getPropertyAsString(messagingEvent, PROP_ACCOUNT_LINKING, PROP_AUTHORIZATION_CODE); return new AccountLinkingEvent(senderId, recipientId, timestamp, status, authorizationCode); } }
mit
ProductiveMobile/material-ui
lib/svg-icons/communication/call-received.js
427
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var CommunicationCallReceived = React.createClass({ displayName: 'CommunicationCallReceived', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: "M20 5.41L18.59 4 7 15.59V9H5v10h10v-2H8.41z" }) ); } }); module.exports = CommunicationCallReceived;
mit
multunus/moveit-mobile
android/app/src/main/java/com/multunus/moveit/MainActivity.java
1555
package com.multunus.moveit; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.github.xinthink.rnmk.ReactMaterialKitPackage; import com.multunus.moveit.config.RNConfig; import com.remobile.splashscreen.*; import com.chymtt.reactnativedropdown.DropdownPackage; import com.microsoft.codepush.react.CodePush; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "MoveIt"; } @Override protected String getJSBundleFile() { return CodePush.getBundleUrl(); } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new CodePush("", this, BuildConfig.DEBUG), new RNConfig(), new ReactMaterialKitPackage(), new DropdownPackage(), new RCTSplashScreenPackage(this) ); } }
mit
Aevin1387/instaVIN
lib/instavin.rb
230
require "instavin/version" require "instavin/errors" require "instavin/reports" require "symboltable" module InstaVIN extend self def configure yield config end def config @@config ||= SymbolTable.new end end
mit
AndyRazafy/fid-dirt-actp
application/models/Pdf_Model.php
2179
<?php require_once("Base_Model.php"); class Pdf_Model extends Base_Model { function __construct() { parent::__construct(); } public function get_data_pdf($idclient) { $sql = "select idclient, nom, prenom, nomta, nomaction, nomemploye, dateappel, dureeappel, dateaction, commentaireaction from detailappel where idclient=$idclient"; $query = $this->db->query($sql); $retour = $query->result(); return $retour; } public function get_table_pdf() { $pdf = new PDFTABLE('L', 'mm', array(300, 200)); $header = array('Nom', 'Prenom', 'Email', 'Date Appel', 'duree', 'Client', 'Numero', 'Action'); $this->load->model('AgentAppel_Model'); for($i = 1;$i<=30;$i++) { $this->load->model('Agent_Model'); $agent = $this->Agent_Model->findById($i); $data = $this->AgentAppel_Model->findByAgentId($agent->getId()); $pdf->AddPage(); $pdf->SetFont('Arial', '', 10); $pdf->FancyTable($header, $data); } $pdf->Output(); } } class PDFTABLE extends FPDF { function FancyTable($header, $data) { $this->Cell(0, 10, "", 0, 0, 'L'); $this->Ln(); $this->SetFillColor(101,171,119); $this->SetTextColor(255); $this->SetDrawColor(128,0,0); $this->SetLineWidth(.3); $this->SetFont('','B'); $w = array(25, 25, 55, 40, 20, 35, 35, 45); for($i = 0; $i < count($header); $i++) $this->Cell($w[$i],8,$header[$i],1,0,'C',true); $this->Ln(); $this->SetFillColor(224,235,255); $this->SetTextColor(0); $this->SetFont(''); $fill = false; foreach($data as $row) { $this->Cell($w[0],6,$row->getNom(),'LR',0,'L',$fill); $this->Cell($w[1],6,$row->getPrenom(),'LR',0,'L',$fill); $this->Cell($w[2],6,$row->getEmail().' s','LR',0,'L',$fill); $this->Cell($w[3],6,$row->getDateAppel(),'LR',0,'L',$fill); $this->Cell($w[4],6,$row->getDuree(),'LR',0,'L',$fill); $this->Cell($w[5],6,$row->getClient(),'LR',0,'L',$fill); $this->Cell($w[6],6,$row->getNumero(),'LR',0,'L',$fill); $this->Cell($w[7],6,$row->getAction(),'LR',0,'L',$fill); $this->Ln(); $fill = !$fill; } $this->Cell(array_sum($w),0,'','T'); } }
mit
cpimhoff/End-of-the-Line
Unity Project/End of the Line/Assets/World Generation/Generation/PatchGenerator.cs
2998
using UnityEngine; using System.Collections.Generic; public class PatchGenerator : MonoBehaviour { public MatchMaker matchMaker; public List<GameObject> templatePatches = new List<GameObject>(); public GameObject characterTemplate; public GameObject animalTemplate; public List<GameObject> props; // Returns a new patch for the world (these start as inactive!) public GameObject NextPatch() { // get a random patch type int randIndex = Random.Range (0, templatePatches.Count); GameObject patch = GameObject.Instantiate (templatePatches [randIndex]); // replace objects tagged with ReplaceWithCharacter with characters GameObject[] replaceThese = GameObject.FindGameObjectsWithTag ("ReplaceWithCharacter"); // Grab pairs (object_i, object_{i+1}), (object_{i+2}, object_{i+3}), etc // and set replace with characters for (int i = 0; i < replaceThese.Length-1; i++) { var pair = matchMaker.getPair (); if (pair.First == null) { // do nothing. } else { GameObject character1; if (pair.First.type == "animal") { character1 = GameObject.Instantiate (animalTemplate); } else { character1 = GameObject.Instantiate (characterTemplate); } character1.GetComponent<InitFromCharacterStruct> ().SetCharacterInfo (pair.First); character1.transform.SetParent (patch.transform); character1.transform.position = replaceThese [i].transform.position; character1.transform.rotation = replaceThese [i].transform.rotation; } if (pair.Second == null) { // do nothing. especially don't do anything bad. } else { GameObject character2 = GameObject.Instantiate (characterTemplate); if (pair.Second.type == "animal") { character2 = GameObject.Instantiate (animalTemplate); } else { character2 = GameObject.Instantiate (characterTemplate); } character2.GetComponent<InitFromCharacterStruct> ().SetCharacterInfo (pair.Second); character2.transform.SetParent (patch.transform); character2.transform.position = replaceThese [i+1].transform.position; character2.transform.rotation = replaceThese [i+1].transform.rotation; } replaceThese [i].tag = "Untagged"; replaceThese [i].SetActive (false); replaceThese [i + 1].tag = "Untagged"; replaceThese [i + 1].SetActive (false); // want i to go up by two, so increment it once here, and once more at the top of the loop :/ i++; } // Grab Props GameObject[] replaceTheseProps = GameObject.FindGameObjectsWithTag("ReplaceWithProp"); foreach (GameObject replaceMe in replaceTheseProps) { int randomIndex = Random.Range (0, props.Count); GameObject funProp = GameObject.Instantiate (props[randomIndex]); funProp.transform.SetParent (patch.transform); funProp.transform.position = replaceMe.transform.position; replaceMe.tag = "Untagged"; replaceMe.SetActive (false); Destroy (replaceMe); } // return template (now properly constructed) patch.SetActive (false); return patch; } }
mit
r7kamura/fastladder
app/assets/javascripts/common.js
35294
//= require i18n //= require i18n/translations I18n.locale = (typeof Language !== 'undefined' && Language === 'English') ? 'en' : 'ja'; I18n.defaultSeparator = '/'; I18n.missingTranslation = function(scope) { return scope; }; /* 良く使う関数 */ var GLOBAL = this; // bench function $(el){ //return typeof el == 'string' ? document.getElementById(el) : el; if(typeof el == 'string'){ return ($.cacheable[el]) ? $.cache[el] || ($.cache[el] = document.getElementById(el)) : document.getElementById(el) } else { return el } } $.cache = {}; $.cacheable = {}; function getlocale(){ var na = window.navigator; /* na.language na.userLanguage*/ } var _ = {}; $N = function (name, attr, childs) { var ret = document.createElement(name); for (k in attr) { if (!attr.hasOwnProperty(k)) continue; v = attr[k]; (k == "class") ? (ret.className = v) : (k == "style") ? setStyle(ret,v) : ret.setAttribute(k, v); } var t = typeof clilds; (isString(childs))? ret.appendChild(document.createTextNode(childs)) : (isArray(childs)) ? foreach(childs,function(child){ isString(child) ? ret.appendChild(document.createTextNode(child)) : ret.appendChild(child); }) : null; return ret; }; function $DF(){ var df = document.createDocumentFragment(); foreach(arguments,function(f){ df.appendChild(f) }); return df; } function reserveName(name){ var root = this; var ns = name.split("."); for(var i=0;i<ns.length;i++){ var current = ns[i]; if(!root[current]) root[current] = {}; root = root[current] } } function True(){return true} function False(){return false} // function BrowserDetect(){ var ua = navigator.userAgent; if(ua.indexOf( "KHTML" ) > -1) this.isKHTML = true; if(ua.indexOf( "Macintosh" ) > -1) this.isMac = true; if(ua.indexOf( "Windows" ) > -1) this.isWin = true; if(ua.indexOf( "Gecko" ) > -1 && !this.isKHTML) this.isGecko = true; if(ua.indexOf( "Firefox" ) > -1) this.isFirefox = true; this.isWindows = this.isWin; if(window.opera){ this.isOpera = true; } else if(ua.indexOf( "MSIE" ) > -1){ this.isIE = true; } } Array.from = function(array) { // arguments if(array.callee){ return Array.prototype.slice.call(array,0) } var length = array.length; var result = new Array(length); for (var i = 0; i < length; i++) result[i] = array[i]; return result; }; Function.prototype.cut = function() { var func = this; var template = Array.from(arguments); return function() { var args = Array.from(arguments); return func.apply(null, template.map(function(arg) { return arg == _ ? args.shift() : arg; })); } }; Function.prototype.o = function(a) { var f = this; return function() { return f(a.apply(null, arguments)); } }; /* Class */ Class = function(){return function(){return this}}; Class.Traits = {}; Class.create = function(traits){ var f = function(){ this.initialize.apply(this, arguments); }; f.prototype.initialize = function(){}; f.isClass = true; f.extend = function(other){ extend(f.prototype,other); return f; }; if(traits && Class.Traits[traits]) f.extend(Class.Traits[traits]); return f; }; // 他のクラスまたはオブジェクトをベースに新しいクラスを作成する Class.base = function(base_class){ if(base_class.isClass){ var child = Class.create(); child.prototype = new base_class; return child; } else { var base = Class(); base.prototype = base_class; var child = Class.create(); child.prototype = new base; return child; } }; // クラスを合成 Class.merge = function(a,b){ var c = Class.create(); var ap = a.prototype; var bp = b.prototype; var cp = c.prototype; var methods = Array.concat(keys(ap),keys(bp)).uniq(); foreach(methods,function(key){ if(isFunction(ap[key]) && isFunction(bp[key])){ cp[key] = function(){ ap[key].apply(this,arguments); return bp[key].apply(this,arguments); } } else { cp[key] = isFunction(ap[key]) ? ap[key] : isFunction(bp[key]) ? bp[key] : null } }); return c; } function extend(self,other){ for(var i in other){ self[i] = other[i] } return self; } function base(obj){ function f(){return this}; f.prototype = obj; return new f; } function clone(obj){ var o = {}; for(var i in obj){ o[i] = obj[i] }; return o } function keys(hash){ var tmp = []; for(var key in hash){ tmp.push(key) } return tmp; } function each(obj,callback){ for(var i in obj){ callback(obj[i],i) } } function foreach(a,f){ var c = 0; var len = a.length; var i = len % 8; if (i>0) do { f(a[c],c++,a); } while (--i); i = parseInt(len >> 3); if (i>0) do { f(a[c],c++,a);f(a[c],c++,a); f(a[c],c++,a);f(a[c],c++,a); f(a[c],c++,a);f(a[c],c++,a); f(a[c],c++,a);f(a[c],c++,a); } while (--i); }; /* function foreach(array,callback){ var len = array.length; for(var i=0;i<len;i++){ callback(array[i],i,array) } } */ /* Perlのjoin、中の配列も含めて同じルールでjoinする */ function join(){ var args = Array.from(arguments); var sep = args.shift(); var to_s = Array.prototype.toString; Array.prototype.toString = function(){return this.join(sep)} var res = args.join(sep); Array.prototype.toString = to_s; return res; } /* */ function Arg(n){ return function(){ return arguments[n] } } function This(){ return function(){ return this } } // 関数の結果に対してsend Function.prototype.send = function(method,args){ var self = this; return function(){ return send(self.apply(this,arguments),method,args) } }; function send(self,method,args){ if(isFunction(self[method])) return self[method].apply(self,args); else if(isFunction(self.method_missing)) return self.method_missing(method,args) else return null } // methodに別名を付ける function alias(method){ return function(){ return this[method].apply(this,arguments) } } /* transform functions */ function sender(method){ var args = Array.slice(arguments,1); return function(self){ var ex_args = Array.from(arguments); return send(self,method,args.concat(ex_args)) } } // thisに対してmethodを呼び出す関数を生成する // methodは文字列もしくは関数 /* invoker(arg(1),) */ function invoker(method){ var args = Array.slice(arguments,1); if(isFunction(method)){ return function(){ var ex_args = Array.from(arguments); return method.apply(this,args.concat(ex_args)) } } else { return function(){ var ex_args = Array.from(arguments); return send(this,method,args.concat(ex_args)) } } } /* push : function(item){ return this.list.push(item) } -> push : delegator("list","push"); */ function delegator(key,method){ return function(){ var self = this[key]; return self[method].apply(self,arguments); } } function getter(attr){ return function(self){return self[attr]} } /* extend buildin object */ foreach("String,Number,Array,Function".split(","),function(c){ var klass = GLOBAL[c]; klass.isClass = true; klass.extend = function(other){ return extend(klass.prototype,other); } klass.prototype["is"+c] = true }) Object.extend = extend; /* and more extra methods */ Array.prototype.min = function(cmp){return (cmp?this.sort(cmp):this.sort()).first()} Array.prototype.max = function(cmp){return (cmp?this.sort(cmp):this.sort()).last()} Array.prototype.compact = function(){ return this.remove(""); } Array.extend({ isArray : true, clone : function(){ return this.concat() }, clear : function(){ this.length = 0; return this }, delete_at : function(pos){ return this.splice(pos,1); }, first : function(size){ return (size == undefined) ? this[0] : this.slice(0,size) }, last : function(size){ return (size == undefined) ? this[this.length-1] : this.slice(this.length-size) }, select : alias("filter"), remove : function(to_remove){ return this.select(function(val){return val != to_remove ? true : false}); }, compact : invoke("remove",""), // 重複をなくす、破壊的 uniq : function(){ var tmp = {}; var len = this.length; for(var i=0;i<this.length;i++){ if(tmp.hasOwnProperty(this[i])){ this.splice(i,1); if(this.length == i){break} i--; }else{ tmp[this[i]] = true; } } return this; }, // 各要素にメソッドを送る invoke : function(){ var args = Array.from(arguments); var method = args.shift(); return this.map(sender(method,args)); }, // ハッシュの配列から指定キーのvalueのみを集めた配列を返す pluck : function(name){ return this.map(getter(name)) }, partition : function(callback,thisObj) { var trues = [], falses = []; this.forEach(function(v,i,self){ (callback.call(thisObj,v,i,self) ? trues : falses).push(v); }); return [trues, falses]; } }); /* detect */ function isString(obj){ return (typeof obj == "string" || obj instanceof String) ? true : false } function isNumber(obj){ return (typeof obj == "number" || obj instanceof Number) ? true : false; } function isElement(obj){ return obj.nodeType ? true : false; } function isFunction(obj){ return typeof obj == "function"; } function isArray(obj){ return obj instanceof Array; } function isRegExp(obj){ return obj instanceof RegExp } function isDate(obj){ return obj instanceof Date } /* Accessor */ function Accessor(){ var value; var p_getter = this.getter; var p_setter = this.setter; var accessor = function(new_value){ if(arguments.length){ var setter = accessor.setter || p_setter; return (value = setter(new_value, value)); } else { var getter = accessor.getter || p_getter; return getter(value) } return (arguments.length) ? (value = new_value) : value }; accessor.isAccessor = true; return accessor; } Accessor.prototype.getter = function(value){ return value }; Accessor.prototype.setter = function(value){ return value }; /* Cookie */ var Cookie = Class.create(); Cookie.extend({ initialize: function(opt){ this._options = "name,value,expires,path,domain,secure".split(","); this._mk_accessors(this._options); this.expires.setter = function(value){ if(isDate(value)){ value = this.expires.toString(); } else if(isNumber(value)){ value = new Date(new Date() - 0 + value).toString(); } return value } if(opt) this._set_options(opt); }, _set_options : function(opt){ var self = this; this._options.forEach(function(key){ opt.hasOwnProperty(key) && self[key](opt[key]) }) }, _mk_accessors: function(args){ for(var i=0;i<args.length;i++){ var name = args[i]; this[name] = new Accessor() } }, parse: function(str){ var hash = {}; var ck = str || document.cookie; var pairs = ck.split(/\s*;\s*/); pairs.forEach(function(v){ var tmp = v.split("=",2); hash[tmp[0]] = tmp[1]; }) return hash; }, bake: function(){ document.cookie = this.as_string(); }, as_string: function(){ var e,p,d,s; e = this.expires(); p = this.path(); d = this.domain(); s = this.secure(); var options = [ (e ? ";expires=" + e.toGMTString() : ""), (p ? ";path=" + p : ""), (d ? ";domain=" + d : ""), (s ? ";secure" : "") ].join(""); var cookie = [this.name(),"=",this.value(),options].join(""); return cookie; } }); Cookie.default_expire = 60*60*24*365*1000; function setCookie(name,value,expires,path,domain,secure){ if(isDate(expires)){ expire_str = "expires="+expires.toString(); } else if(isNumber(expires)){ expire_str = "expires="+new Date(new Date() - 0 + expire).toString(); } else { expire_str = "expires="+new Date(new Date() - 0 + Cookie.default_expire).toString(); } if(!path) path = "; path=/;"; var cookie = new Cookie({ name : name, value : value, path : path || "/", expires : expires }); cookie.bake(); } function getCookie(key){ var hash = new Cookie().parse(); return hash[key]; } /* Array */ Array.extend({ collect : alias("map"), reduce : function(callback){ return this.map(callback).join("") } }); /* Number */ Number.extend({ toHex : invoker("toString",16), zerofill : function(len){ var n = "" + this; for(;n.length < len;) n = "0" + n; return n; }, // 両端を含む between : function(a,b){ var min = Math.min(a,b); var max = Math.max(a,b); return (this >= min && this <= max); } }); /* Function */ Function.extend({ applied : function(thisObj,args){ var self = this; return function(){ return self.apply(thisObj,args) } }, bindThis : function(thisObj){ var self = this; return function(){ return self.apply(thisObj,arguments) } }, bind : alias("bindThis"), // 引数をsliceする slicer : function(to,end){ var self = this; return function(){ var sliced = Array.slice(arguments,to,end); return self.apply(this,sliced); } } }); function loadRaw(url){ var req = new XMLHttpRequest; var res; req.open("GET",url,false); req.onload = function(){ res = req.responseText; }; req.send(null); return res; } function loadJson(url,callback){ if(dev){ if(!dummy[url]){return} var json = dummy[url].isString ? eval("("+dummy[url]+")") : dummy[url]; callback(json); return; } var req = new XMLHttpRequest; req.open("GET",url,true); req.onload = function(){ eval("var json ="+req.responseText); callback(json) }; req.send(null) } /* className */ function hasClass(element,classname){ element = $(element); var cl = element.className; var cls = cl.split(/\s+/); return cls.indexOf(classname) != -1; } function addClass(element,classname){ element = $(element); var cl = element.className; if(!contain(cl,classname)){ element.className += " " + classname; } } function removeClass(element,classname){ element = $(element); var cl = element.className; var cls = cl.split(/\s+/); element.className = cls.remove(classname).join(" "); } function switchClass(element, classname){ element = $(element); var cl = element.className; var tmp = classname.split("-"); var ns = tmp[0]; var cls = cl.split(/\s+/); var buf = []; cls.forEach(function(v){ if(v.indexOf(ns+"-") != 0) buf.push(v)} ); buf.push(classname); element.className = buf.join(" "); } function toggleClass(element, classname){ element = $(element); hasClass(element, classname) ? removeClass(element, classname): addClass(element, classname); } /* 文字列が含まれているかの判別 */ function contain(self,other){ if(isString(self) && isString(other)){ return self.indexOf(other) != -1 } if(isRegExp(other)){ return other.test(self) } } /* Form */ var Form = {}; Form.toJson = function(form){ var json = {}; var len = form.elements.length; foreach(form.elements, function(el){ if(!el.name) return; var value = Form.getValue(el); if(value != null){ json[el.name] = value } }); return json; }; Form.getValue = function(el){ return ( (/text|hidden|submit/.test(el.type)) ? el.value : (el.type == "checkbox" && el.checked) ? el.value : (el.type == "radio" && el.checked) ? el.value : (el.tagName == "SELECT") ? el.options[el.selectedIndex].value : null ) }; // formを埋める Form.fill = function(form,json){ form = $(form); foreach(form.elements, function(el){ var name = el.name; var value = json[name]; if(!name || value == null) return; (/text|hidden|select|submit/.test(el.type)) ? (el.value = value) : (el.type == "checkbox") ? (el.value = value, el.checked = true) : (el.type == "radio") ? (value == el.value) ? (el.checked = true) : (el.checked = false) : null }) } Form.setValue = function(el, value){ el.value = value; } Object.extend(Form,{ disable: function(el){ $(el).disabled = "disabled"; }, enable: function(el){ $(el).disabled = ""; }, disable_all: function(el){ el = $(el); Form.disable(el); var child = el.getElementsByTagName("*"); foreach(child, Form.disable); }, enable_all: function(el){ el = $(el); Form.enable(el); var child = el.getElementsByTagName("*"); foreach(child, Form.enable); } }); /* DateTime */ function DateTime(time){ this._date = time ? new Date(time) : new Date; this._update(); this.toString = function(){ return [this.ymd(),this.hms()].join(" ")} this.valueOf = function(){ return this._date - 0 }; } DateTime.now = function(){ return new DateTime; }; DateTime.prototype = { _update : function(){ var dt = this._date; this.year = dt.getFullYear(); this.month = this.mon = dt.getMonth() + 1; this.day = this.mday = this.day_of_month = dt.getDate(); this.hour = dt.getHours(); this.minute = this.min = dt.getMinutes(); this.second = this.sec = dt.getSeconds(); }, ymd : function(sep){ sep = arguments.length ? sep : "/"; return [this.year,this.month,this.day].invoke("zerofill",2).join(sep) }, hms : function(sep){ sep = arguments.length ? sep : ":"; return [this.hour,this.minute,this.second].invoke("zerofill",2).join(sep) } }; DateTime.prototype.ymd_jp = function(){ var ymd = [this.year,this.month,this.day].invoke("zerofill",2) return ymd[0]+"年"+ymd[1]+"月"+ymd[2]+"日"; }; /* Cache */ var Cache = Class.create(); Cache.extend({ initialize : function(option){ this._index = {}; this._exprs = {}; this._cache = []; if(option){ this.max = option.max || 0; } }, _get: function(key){ return this._index["_" + key]; }, get: function(key){ return this._get(key)[1] }, set: function(key,value){ // delete if(this.max && this._cache.length > this.max){ var to_delete = this._cache.shift(); delete this._index["_" + to_delete[0]]; } // update if(this.has(key)){ this._get(key)[1] = value; } else { // create var pair = [key,value]; this._cache.push(pair); this._index["_"+key] = pair; } return value; }, set_expr: function(key,expr){ this._exprs["_" + key] = expr; }, get_expr: function(key){ return this._exprs["_" + key] || null; }, check_expr: function(key){ var expr = this.get_expr(key); if(expr){ var r = new Date() - expr; var f = (r < 0) ? true : false; // if(!f) message("再読み込みします") return f; } else { return true; } }, has : function(key){ return (this._index.hasOwnProperty("_" + key) && this.check_expr(key)); }, clear : function(){ this._index = {}; this._cache = []; }, find_or_create : function(key,callback){ return this.has(key) ? this.get(key) : this.set(key,callback()) } }); Number.extend({ times: function(callback){ var c = 0; for(;c<this;c++) callback(c) } }); String.escapeRules = [ [/&/g , "&amp;"], [/</g , "&lt;"], [/>/g , "&gt;"] ]; String.unescapeRules = [ [/&lt;/g, "<"], [/&gt;/g, ">"], [/&amp;/g, "&"] ]; String.extend({ strip : invoker("replace",/^\s+(.*?)\s+$/,"$1"), repeat : function(num){ var buf = []; for(var i=0;i<num;buf[i++]=this); return buf.join(""); }, mreplace : function(rule){ var tmp = ""+this; foreach(rule,function(v){ tmp = tmp.replace(v[0],v[1]) }); return tmp; }, escapeHTML : invoker("mreplace",String.escapeRules), unescapeHTML : invoker("mreplace",String.unescapeRules), ry : function(max,str){ if(this.length <= max) return this; var tmp = this.split(""); return Array.concat(this.slice(0,max/2),str,this.slice(-max/2)).join("") }, camelize : invoker("replace",/-([a-z])/g, Arg(1).send("toUpperCase")) }); /* Math */ Math.rand = function(num){return Math.random() * num}; function inspect(obj){ return keys(obj).map(function(key){ return key +" = "+obj[key] + "\n"; }) } Object.hasMethod = function(object,method){ if(object && typeof object[method] == "function") return true; else return false; }; /* JSON */ var JSON = {}; JSON.parse = function(str){ try{ var res = eval("(" + str + ")"); } catch(e){ // alert(inspect(e)) return null; } return res; } Array.toJSON = function(array){ var i=0,len=array.length,json=[]; for(;i<len;i++) json[i] = (array[i] != null) ? Object.toJSON(array[i]) : "null"; return "[" + json.join(",") + "]"; } Array.prototype.toJSON = function(){ return Array.toJSON(this); } String.toJSON = function(string){ return '"' + string.replace(/(\\|\")/g,"\\$1") .replace(/\n|\r|\t/g,function(){ var a = arguments[0]; return (a == '\n') ? '\\n': (a == '\r') ? '\\r': (a == '\t') ? '\\t': "" }) + '"' } String.prototype.toJSON = function(){ return String.toJSON(this) } Number.toJSON = function(number){ return isFinite(number) ? String(number) : 'null' } Number.prototype.toJSON = function(){ return Number.toJSON(this) } Boolean.prototype.toJSON = function(){return this} Function.prototype.toJSON = function(){return this} RegExp.prototype.toJSON = function(){return this} // strict but slow String.prototype.toJSON = function(){ var tmp = this.split(""); for(var i=0;i<tmp.length;i++){ var c = tmp[i]; (c >= ' ') ? (c == '\\') ? (tmp[i] = '\\\\'): (c == '"') ? (tmp[i] = '\\"' ): 0 : (tmp[i] = (c == '\n') ? '\\n' : (c == '\r') ? '\\r' : (c == '\t') ? '\\t' : (c == '\b') ? '\\b' : (c == '\f') ? '\\f' : (c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16))) ) } return '"' + tmp.join("") + '"'; } Object.toJSON = function(obj){ var json = []; if(typeof obj == 'undefined') return "null"; if(obj == null) return "null"; if(typeof obj.toJSON == 'function'){ return obj.toJSON(); } for(var i in obj){ if(!obj.hasOwnProperty(i)) continue; if(typeof obj[i] == "function") continue; json.push( i.toJSON()+":"+((obj[i] != null)? Object.toJSON(obj[i]) : "null") ) } return "{" + json.join(",") + "}"; } Object.toQuery = function(self){ var buf = []; for(var key in self){ var value = self[key]; if(isFunction(value)) continue; buf.push( encodeURIComponent(key)+"="+ encodeURIComponent(value) ) } return buf.join("&"); } /* from prototype.js */ var Position = { // set to true if needed, warning: firefox performance problems // NOT neeeded for page scrolling, only if draggable contained in // scrollable elements includeScrollOffsets: false, // must be called before calling withinIncludingScrolloffset, every time the // page is scrolled prepare: function() { this.deltaX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0; this.deltaY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; }, realOffset: function(element) { var valueT = 0, valueL = 0; do { valueT += element.scrollTop || 0; valueL += element.scrollLeft || 0; element = element.parentNode; } while (element); return [valueL, valueT]; }, cumulativeOffset: function(element) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); return [valueL, valueT]; }, positionedOffset: function(element) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; if (element) { p = Element.getStyle(element, 'position'); if (p == 'relative' || p == 'absolute') break; } } while (element); return [valueL, valueT]; }, offsetParent: function(element) { if (element.offsetParent) return element.offsetParent; if (element == document.body) return element; while ((element = element.parentNode) && element != document.body) if (Element.getStyle(element, 'position') != 'static') return element; return document.body; }, // caches x/y coordinate pair to use with overlap within: function(element, x, y) { if (this.includeScrollOffsets) return this.withinIncludingScrolloffsets(element, x, y); this.xcomp = x; this.ycomp = y; this.offset = this.cumulativeOffset(element); return (y >= this.offset[1] && y < this.offset[1] + element.offsetHeight && x >= this.offset[0] && x < this.offset[0] + element.offsetWidth); }, withinIncludingScrolloffsets: function(element, x, y) { var offsetcache = this.realOffset(element); this.xcomp = x + offsetcache[0] - this.deltaX; this.ycomp = y + offsetcache[1] - this.deltaY; this.offset = this.cumulativeOffset(element); return (this.ycomp >= this.offset[1] && this.ycomp < this.offset[1] + element.offsetHeight && this.xcomp >= this.offset[0] && this.xcomp < this.offset[0] + element.offsetWidth); }, // within must be called directly before overlap: function(mode, element) { if (!mode) return 0; if (mode == 'vertical') return ((this.offset[1] + element.offsetHeight) - this.ycomp) / element.offsetHeight; if (mode == 'horizontal') return ((this.offset[0] + element.offsetWidth) - this.xcomp) / element.offsetWidth; }, clone: function(source, target) { source = $(source); target = $(target); target.style.position = 'absolute'; var offsets = this.cumulativeOffset(source); target.style.top = offsets[1] + 'px'; target.style.left = offsets[0] + 'px'; target.style.width = source.offsetWidth + 'px'; target.style.height = source.offsetHeight + 'px'; }, page: function(forElement) { var valueT = 0, valueL = 0; var element = forElement; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; // Safari fix if (element.offsetParent==document.body) if (Element.getStyle(element,'position')=='absolute') break; } while (element = element.offsetParent); element = forElement; do { valueT -= element.scrollTop || 0; valueL -= element.scrollLeft || 0; } while (element = element.parentNode); return [valueL, valueT]; }, clone: function(source, target) { var options = Object.extend({ setLeft: true, setTop: true, setWidth: true, setHeight: true, offsetTop: 0, offsetLeft: 0 }, arguments[2] || {}) // find page position of source source = $(source); var p = Position.page(source); // find coordinate system to use target = $(target); var delta = [0, 0]; var parent = null; // delta [0,0] will do fine with position: fixed elements, // position:absolute needs offsetParent deltas if (Element.getStyle(target,'position') == 'absolute') { parent = Position.offsetParent(target); delta = Position.page(parent); } // correct by body offsets (fixes Safari) if (parent == document.body) { delta[0] -= document.body.offsetLeft; delta[1] -= document.body.offsetTop; } // set position if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; if(options.setWidth) target.style.width = source.offsetWidth + 'px'; if(options.setHeight) target.style.height = source.offsetHeight + 'px'; }, absolutize: function(element) { element = $(element); if (element.style.position == 'absolute') return; Position.prepare(); var offsets = Position.positionedOffset(element); var top = offsets[1]; var left = offsets[0]; var width = element.clientWidth; var height = element.clientHeight; element._originalLeft = left - parseFloat(element.style.left || 0); element._originalTop = top - parseFloat(element.style.top || 0); element._originalWidth = element.style.width; element._originalHeight = element.style.height; element.style.position = 'absolute'; element.style.top = top + 'px';; element.style.left = left + 'px';; element.style.width = width + 'px';; element.style.height = height + 'px';; }, relativize: function(element) { element = $(element); if (element.style.position == 'relative') return; Position.prepare(); element.style.position = 'relative'; var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); element.style.top = top + 'px'; element.style.left = left + 'px'; element.style.height = element._originalHeight; element.style.width = element._originalWidth; } } // Safari returns margins on body which is incorrect if the child is absolutely // positioned. For performance reasons, redefine Position.cumulativeOffset for // KHTML/WebKit only. if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) { Position.cumulativeOffset = function(element) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; if (element.offsetParent == document.body) if (Element.getStyle(element, 'position') == 'absolute') break; element = element.offsetParent; } while (element); return [valueL, valueT]; } } Position.cumulativeOffsetFrom = function(element,from) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element && element != from); return [valueL, valueT]; }; /* CSS */ function parseCSS(text){ var pairs = text.split(";"); var res = {}; pairs.forEach(function(pair){ var tmp = pair.split(":"); res[tmp[0].strip()] = tmp[1]; }); return res; } // cssセット、透明度、floatの互換性を取る function setStyle(element,style){ element = $(element); var es = element.style; if(isString(style)){ es.cssText ? (es.cssText = style) : setStyle(element,parseCSS(style)); } else { // objectの場合 each(style,function(value,key){ if(setStyle.hack.hasOwnProperty(key)){ var tmp = setStyle.hack[key](key,value); key = tmp[0],value = tmp[1] } element.style[key.camelize()] = value }); } } setStyle.hack = { opacity : function(key,value){ return ( (/MSIE/.test(navigator.userAgent)) ? ["filter" , 'alpha(opacity='+value*100+')'] : [ key , value] ) } } function getStyle(o,s){ var res; try{ if (document.defaultView && document.defaultView.getComputedStyle){ res = document.defaultView.getComputedStyle(o, null).getPropertyValue(s); } else { if (o.currentStyle){ var camelized = s.replace(/-([^-])/g, function(a,b){return b.toUpperCase()}); res = o.currentStyle[camelized]; } } return res; } catch(e){} return ""; } var Element = {}; Element.getStyle = getStyle; /* */ // var Config = {} // Task /* 並列してリクエストを投げる、 - 完了したものからcompleteフラグを立てる - 監視者のupdateメソッドを呼び出す var task = new Task([loadConfig,func,func]); task.oncomplete = function(){ // complete ! }; task.exec(); api["config/load"] = new API("/api/config/load").requester("post"); new Task(loadconfig); API.prototype.toTask = function(){ } */ Object.extend(Function.prototype,{ /* TIMERS */ _timeouts : [], _interals : [], do_later : function(ms){ this._intervals.push(setTimeout(this,ms)); return this; }, bg : function(ms){ this._intervals.push(setInterval(this,ms)); return this; }, kill : function(){ this._timeouts.forEach(function(pid){ clearTimeout(pid) }); this._intervals.forEach(function(pid){ clearInterval(pid) }) }, /* TASK */ observers : [], complete : function(result){ this.result_code = result; this.observers.invoke("update", this) }, _changed : false, changed : function(state){ return arguments.length ? (this._changed = state) : this._changed; }, add_observer : function(observer){ this.observers.push(observer) return this; } }) function loadConfig(){ var task = arguments.callee; var api = new API("/api/config/load"); return api.post({},function(res){ extend(Config,res); task.complete(); }); } function Task(tasks,callback){ var self = this; this.tasks = tasks; tasks.map(function(v){ return isFunction(v) ? v : send(v,"toTask") }).invoke("add_observer", this); if(callback){ this.oncomplete = callback; this.exec(); } return this; } Task.prototype = { isTask : true, exec : function(){ this.tasks.invoke("call",null); }, update : function(f){ send(this,"onprogress"); } } Array.prototype.toTask = function(){ return new Task(this); } /* super */ /* parent this.parent.update(); this.parent.parent.update(); -> parent(this,"update") */ /* function parent(obj, method, args){ var p = obj.parent; while(p){ send(p,method,args); p = obj.parent; } } */ /* invoke 別のクラスに処理を伝播させる invoke(this, "method_name", arguments); */ function invoke(obj, method, args){ var o = obj.parent; for (;typeof(o) != 'undefined'; o = o.parent) { if (typeof(o[method]) == 'function') { return o[method].apply(obj, args); } } return false; } /* next たらいまわしにする。 this.parent.childs next(this, "initialize"); */ function next(obj, method, args){ obj.parent.childs.invoke(method,args) } function childOf(element, ancestor){ element = $(element), ancestor = $(ancestor); while (element = element.parentNode) if (element == ancestor) return true; return false; } function $ref(element){ } String.prototype.op = function(){ return new Function("a,b","return a"+this+"b"); } // regexp merger // 正規表現を複数行にわたって記述できるようにします。 RegExp.prototype.get_body = function(){ var str = this.toString(); return str.slice(1,str.lastIndexOf("/")); }; RegExp.prototype.get_flags = function(){ return [ this.ignoreCase ? "i":"", this.global ? "g":"", this.multiline ? "m":"" ].join(""); }; RegExp.concat = function(){ var args = Array.from(arguments); var buf = []; args.forEach(function(reg){ buf.push(reg.get_body()); }); var flag = args[args.length-1].get_flags(); return new RegExp(buf.join(""), flag); } Array.prototype.flatten = function(){ var res = []; this.forEach(function(a){ if(isArray(a)) a = a.flatten(); res = res.concat(a) }); return res; }; Function.prototype.forEachArgs = function(callback){ var f = this; return function(){ var target = Array.from(arguments).flatten(); if(!target.length) return; target.forEach(function(v){ callback ? f(callback(v)) : f(v) }) } }; /* Element Updater */ function MakeUpdater(label){ var hash = {}; var updater = (label?label+"_":"") + "updater"; var update = (label?label+"_":"") + "update"; function get_func(label){ return( isFunction(hash["_"+label]) ? hash["_" + label] : function(){} ); } var u = GLOBAL[update] = function(label){ if(isRegExp(label)){ keys(hash).filter(function(l){ l = l.slice(1); return label.test(l) }).forEach(function(label){ label = label.slice(1); get_func(label).call($(label)); }) } else { return get_func(label).call($(label)); } }.forEachArgs(); GLOBAL[updater] = function(label, callback){ if(callback){ hash["_"+label] = callback; } else { return function(){ u(label) } } }; } MakeUpdater();
mit
VoronFX/Aurora
Project-Aurora/Project-Aurora/Profiles/CSGO/Layers/CSGOBurningLayerHandler.cs
4132
using Aurora.EffectsEngine; using Aurora.Profiles.CSGO.GSI; using Aurora.Profiles.CSGO.GSI.Nodes; using Aurora.Settings; using Aurora.Settings.Layers; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace Aurora.Profiles.CSGO.Layers { public class CSGOBurningLayerHandlerProperties : LayerHandlerProperties2Color<CSGOBurningLayerHandlerProperties> { public Color? _BurningColor { get; set; } [JsonIgnore] public Color BurningColor { get { return Logic._BurningColor ?? _BurningColor ?? Color.Empty; } } public bool? _Animated { get; set; } [JsonIgnore] public bool Animated { get { return Logic._Animated ?? _Animated ?? false; } } public CSGOBurningLayerHandlerProperties() : base() { } public CSGOBurningLayerHandlerProperties(bool assign_default = false) : base(assign_default) { } public override void Default() { base.Default(); this._BurningColor = Color.FromArgb(255, 70, 0); this._Animated = true; } } public class CSGOBurningLayerHandler : LayerHandler<CSGOBurningLayerHandlerProperties> { private Random randomizer = new Random(); public CSGOBurningLayerHandler() : base() { _ID = "CSGOBurning"; } protected override UserControl CreateControl() { return new Control_CSGOBurningLayer(this); } public override EffectLayer Render(IGameState state) { EffectLayer burning_layer = new EffectLayer("CSGO - Burning"); if (state is GameState_CSGO) { GameState_CSGO csgostate = state as GameState_CSGO; //Update Burning if (csgostate.Player.State.Burning > 0) { double burning_percent = (double)csgostate.Player.State.Burning / 255.0; Color burncolor = Properties.BurningColor; if (Properties.Animated) { int red_adjusted = (int)(burncolor.R + (Math.Cos((Utils.Time.GetMillisecondsSinceEpoch() + randomizer.Next(75)) / 75.0) * 0.15 * 255)); byte red = 0; if (red_adjusted > 255) red = 255; else if (red_adjusted < 0) red = 0; else red = (byte)red_adjusted; int green_adjusted = (int)(burncolor.G + (Math.Sin((Utils.Time.GetMillisecondsSinceEpoch() + randomizer.Next(150)) / 75.0) * 0.15 * 255)); byte green = 0; if (green_adjusted > 255) green = 255; else if (green_adjusted < 0) green = 0; else green = (byte)green_adjusted; int blue_adjusted = (int)(burncolor.B + (Math.Cos((Utils.Time.GetMillisecondsSinceEpoch() + randomizer.Next(225)) / 75.0) * 0.15 * 255)); byte blue = 0; if (blue_adjusted > 255) blue = 255; else if (blue_adjusted < 0) blue = 0; else blue = (byte)blue_adjusted; burncolor = Color.FromArgb(csgostate.Player.State.Burning, red, green, blue); } burning_layer.Fill(burncolor); } } return burning_layer; } public override void SetApplication(Application profile) { (Control as Control_CSGOBurningLayer).SetProfile(profile); base.SetApplication(profile); } } }
mit
dmitrymomot/kohana-restful-api
init.php
894
<?php defined('SYSPATH') OR die('No direct script access.'); $config = Kohana::$config->load('restful_api'); $default_format = Arr::get($config, 'default_format', 'json'); $allowed_formats = implode('|', array_keys(Arr::get($config, 'format_map', array($default_format => $default_format)))); Route::set('resful-api-default', 'api/<version>/<resource>(/<id>(/<rel_resource>(/<rel_id>)))(:<http_method>)(.<format>)', array( 'version' => '(v[0-9]++)', 'resource' => '([a-zA-Z0-9_]++)', 'id' => '[0-9]+', 'rel_resource' => '([a-zA-Z0-9_]++)', 'rel_id' => '[0-9]+', 'format' => '('.$allowed_formats.')', 'http_method' => '(get|post|put|delete)', )) ->filter(array('RESTful_API', 'run')) ->defaults(array( 'format' => $default_format, 'controller' => 'Restful_Api_Error', 'action' => 'undefined', )); unset($config, $allowed_formats, $default_format);
mit
cloew/KaoDecorators
setup.py
256
from distutils.core import setup setup(name='kao_decorators', version='0.1.2', description="Collection of useful decorators", author='Chris Loew', author_email='cloew123@gmail.com', packages=['kao_decorators'], )
mit
TED-996/StackLang
StackLang.Ide/Properties/Resources.Designer.cs
2431
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.21006.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace StackLang.Ide.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("StackLang.Ide.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
mit
dwightwatson/active
src/Route.php
2476
<?php namespace Watson\Active; use Illuminate\Routing\Router; use Illuminate\Support\Str; class Route { /** * Illuminate Router instance. * * @var \Illuminate\Routing\Router */ protected $router; /** * Construct the class. * * @param \Illuminate\Routing\Router $router * @return void */ public function __construct(Router $router) { $this->router = $router; } /** * Get the controller name, separated as necessary and with or without namespaces. * * @param string $separator * @param bool $includeNamespace * @param string $trimNamespace * @return string|null */ public function controller($separator = null, $includeNamespace = true, $trimNamespace = 'App\Http\Controllers\\') { if ($action = $this->router->currentRouteAction()) { $separator = is_null($separator) ? ' ' : $separator; $controller = head(Str::parseCallback($action, null)); // If the controller contains the given namespace, remove it. if (substr($controller, 0, strlen($trimNamespace)) === $trimNamespace) { $controller = substr($controller, strlen($trimNamespace)); } // If the controller contains 'Controller' at the end, remove it. if (substr($controller, - strlen('Controller')) === 'Controller') { $controller = substr($controller, 0, - strlen('Controller')); } // Separate out nested controller resources. $controller = str_replace('_', $separator, Str::snake($controller)); // Either separate out the namespaces or remove them. $controller = $includeNamespace ? str_replace('\\', '', $controller) : substr(strrchr($controller, '\\'), 1); return trim($controller); } return null; } /** * Get the current controller action name. * * @param bool $removeHttpMethod * @return string|null */ public function action($removeHttpMethod = true) { if ($action = $this->router->currentRouteAction()) { $action = last(Str::parseCallback($action, null)); if ($removeHttpMethod) { $action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', $action); } return Str::snake($action, '-'); } return null; } }
mit
rgujju/MeanApp
client/src/app/register/register.component.ts
2469
import { Component, OnInit } from '@angular/core'; import { FormGroup,FormControl, FormBuilder,ReactiveFormsModule,Validators } from '@angular/forms'; import { Router } from '@angular/router'; import {HttpModule} from '@angular/http'; import { User } from '../user'; import { UserService } from '../user.service'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'], providers: [UserService, HttpModule] }) export class RegisterComponent implements OnInit { private registrationForm : FormGroup; private _passwordNotMatched:boolean = false; private _newUser: User; private _registered: boolean = false; constructor( private _fb : FormBuilder, private _router: Router, private _userService: UserService, ){} ngOnInit() { this.registrationForm = this._fb.group({ firstName: ['', [<any>Validators.required, <any>Validators.minLength(5)]], lastName: ['', [<any>Validators.required, <any>Validators.minLength(5)]], username: ['', [<any>Validators.required, <any>Validators.minLength(3),Validators.pattern('[A-Za-z0-9]*')]], email: ['', [<any>Validators.required,Validators.email]], password: ['', [<any>Validators.required, <any>Validators.minLength(8)]], confirmPassword: ['', [<any>Validators.required, <any>Validators.minLength(8)]] }); } onSubmit(form,valid){ if(valid){ if(form.password == form.confirmPassword){ this._passwordNotMatched=false; //this._router.navigate(['login']); // Check at the backend if such a user exists this._newUser = { username: form.username, firstName: form.firstName, lastName: form.lastName, email: form.email, password: form.password } this._userService.register(this._newUser) .subscribe(res => { if(res.success){ this._registered = true; this._router.navigate(['login']); }else{ console.log("Error in registering the user"); this._router.navigate(['register']); } }); this._newUser = null; } else{ this._passwordNotMatched = true; //console.log('Entered Password does not match'); } } } }
mit
indraphan/mean-ez
packages/contact/server/models/contact.js
461
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Contact Schema */ var ContactSchema = new Schema({ name: { type: String, required: true }, phone: { type: Number }, email: { type: String }, facebook: { type: String }, twitter: { type: String }, skype: { type: String }, }); /** * Validations */ /** * Statics */ mongoose.model('Contact', ContactSchema);
mit
bogdananton/php-vcs-control
src/Support/Launchers/ProcOpen.php
1665
<?php namespace PHPVCSControl\Support\Launchers; use PHPVCSControl\Support\Filesystem; use Psr\Log\LoggerInterface; class ProcOpen implements LauncherInterface { /** @var \Monolog\Logger */ protected $logger; /** @var Filesystem */ protected $filesystem; public function __construct(LoggerInterface $logger, Filesystem $filesystem) { $this->logger = $logger; $this->filesystem = $filesystem; } protected $envopts = []; public function run($command) { $descriptorspec = [ 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ]; $env = null; $pipes = []; if (count($_ENV) === 0) { foreach ($this->envopts as $k => $v) { putenv(sprintf("%s=%s", $k, $v)); } } else { $env = array_merge($_ENV, $this->envopts); } $resource = proc_open($command, $descriptorspec, $pipes, $cwd, $env); $stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]); foreach ($pipes as $pipe) { fclose($pipe); } $status = trim(proc_close($resource)); if ($status) { throw new \Exception($stderr); } return $stdout; } /** * Sets custom environment options. * * @param string $key * @param string $value */ public function setenv($key, $value) { $this->envopts[$key] = $value; } public function getFilesystem() { return $this->filesystem; } public function getLogger() { return $this->logger; } }
mit
klinkaren/zeus
src/CImage/CImage.php
15346
<?php /** * ===== CImage ===== * - Modifies, caches och outputs images * * === HOW === * Takes in array containing: * - imageDir (path to image directory) * - cacheDir (path to cache) * ...and optionally: * - maxWidth and maxHeight (of images) * * === EXAMPLE === * $options = array( * 'imageDir' => __DIR__ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR , * 'cacheDir' => __DIR__ . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR , * 'maxWidth' => 2000, * 'maxHeight' => 2000, * ); * $exampleImage = new CImage($options); * */ class CImage { /** * Members */ // Options private $imageDir; // string: instead of IMG_PATH private $cacheDir; // string: instead of CACHE_PATH private $maxWidth; // int private $maxHeight; // int // Parameters private $src; // string: path to image private $verbose; // boolean private $saveAs; // string: image format private $quality; // int, 1-100 private $ignoreCache; // boolean private $newWidth; // int private $newHeight; // int private $cropToFit; // boolean private $sharpen; // boolean private $pathToImage; // string: full path to image // array of supported images private $extensions = array('png', 'jpg', 'jpeg'); // String containing image info private $verboseLog; // Orinal image info private $filesize; // Filesize private $height; // Height private $width; // Width /** * CONSTRUCTOR * Creates an instans of CDatabase, that connects to a MySQL database using PHP PDO. * */ public function __construct($options) { $this->imageDir = $options['imageDir']; $this->cacheDir = $options['cacheDir']; $this->maxWidth = isset($options['maxWidth']) ? $options['maxWidth'] : 2000; $this->maxHeight = isset($options['maxHeight']) ? $options['maxHeight'] : 2000; $this->getParams(); } /** * Show image * */ public function showImage() { // Create path to image file $this->pathToImage = realpath($this->imageDir . $this->src); !isset($this->verbose) or $this->startVerboseLog(); // Validate incoming arguments $this->validate(); // Get image info $this->getImageInfo(); // Open up original image from file $image = $this->openOrginalImage(); // Resize and apply filters if requested if (isset($this->cropToFit) || isset($this->newHeight) || isset($this->newWidth)) { $image = $this->resizeImage($this->width, $this->height, $image); } // Create cache filename $cacheFileName = $this->createCache(); // Check if file already exists, if so output image $this->checkForCache($cacheFileName); // Save file $this->saveImage($cacheFileName, $image); // Output image $this->outputImage($cacheFileName); } /** * Get the incoming arguments * */ private function getParams() { $this->src = isset($_GET['src']) ? $_GET['src'] : null; $this->verbose = isset($_GET['verbose']) ? true : null; $this->saveAs = isset($_GET['save-as']) ? $_GET['save-as'] : null; $this->quality = isset($_GET['quality']) ? $_GET['quality'] : 60; $this->ignoreCache = isset($_GET['no-cache']) ? true : null; $this->newWidth = isset($_GET['width']) ? $_GET['width'] : null; $this->newHeight = isset($_GET['height']) ? $_GET['height'] : null; $this->cropToFit = isset($_GET['crop-to-fit']) ? true : null; $this->sharpen = isset($_GET['sharpen']) ? true : null; $this->pathToImage = realpath($this->imageDir . $this->src); } /** * Sharpen image as http://php.net/manual/en/ref.image.php#56144 * http://loriweb.pair.com/8udf-sharpen.html * * @param resource $image the image to apply this filter on. * @return resource $image as the processed image. */ private function sharpenImage($image) { $matrix = array( array(-1,-1,-1,), array(-1,16,-1,), array(-1,-1,-1,) ); $divisor = 8; $offset = 0; imageconvolution($image, $matrix, $divisor, $offset); return $image; } /** * Resize image * */ private function resizeImage($width, $height, $image) { // Calculate new width and height for the image $aspectRatio = $width / $height; if($this->cropToFit && $this->newWidth && $this->newHeight) { $targetRatio = $this->newWidth / $this->newHeight; $cropWidth = $targetRatio > $aspectRatio ? $width : round($height * $targetRatio); $cropHeight = $targetRatio > $aspectRatio ? round($width / $targetRatio) : $height; if($this->verbose) { $this->verbose("Crop to fit into box of {$newWidth}x{$newHeight}. Cropping dimensions: {$cropWidth}x{$cropHeight}."); } } else if($this->newWidth && !$this->newHeight) { $this->newHeight = round($this->newWidth / $aspectRatio); if($this->verbose) { $this->verbose("New width is known {$newWidth}, height is calculated to {$newHeight}."); } } else if(!$this->newWidth && $this->newHeight) { $this->newWidth = round($this->newHeight * $aspectRatio); if($this->verbose) { $this->verbose("New height is known {$this->newHeight}, width is calculated to {$this->newWidth}."); } } else if($this->newWidth && $this->newHeight) { $ratioWidth = $width / $this->newWidth; $ratioHeight = $height / $this->newHeight; $ratio = ($ratioWidth > $ratioHeight) ? $ratioWidth : $ratioHeight; $this->newWidth = round($width / $ratio); $this->newHeight = round($height / $ratio); if($this->verbose) { $this->verbose("New width & height is requested, keeping aspect ratio results in {$newWidth}x{$newHeight}."); } } else { $this->newWidth = $width; $this->newHeight = $height; if($this->verbose) { $this->verbose("Keeping original width & heigth."); } } // Resize the image if needed if($this->cropToFit) { if($this->verbose) { $this->verbose("Resizing, crop to fit."); } $cropX = round(($width - $cropWidth) / 2); $cropY = round(($height - $cropHeight) / 2); $imageResized = $this->createImageKeepTransparency($this->newWidth, $this->newHeight); imagecopyresampled($imageResized, $image, 0, 0, $cropX, $cropY, $this->newWidth, $this->newHeight, $cropWidth, $cropHeight); $image = $imageResized; $width = $this->newWidth; $height = $this->newHeight; } else if(!($this->newWidth == $width && $this->newHeight == $height)) { if($this->verbose) { $this->verbose("Resizing, new height and/or width."); } $imageResized = $this->createImageKeepTransparency($this->newWidth, $this->newHeight); imagecopyresampled($imageResized, $image, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height); $image = $imageResized; $width = $this->newWidth; $height = $this->newHeight; } return $image; } /** * Create new image and keep transparency * * @param resource $image the image to apply this filter on. * @return resource $image as the processed image. */ function createImageKeepTransparency($width, $height) { $img = imagecreatetruecolor($width, $height); imagealphablending($img, false); imagesavealpha($img, true); return $img; } /** * Create cache * */ private function createCache() { // Creating a filename for the cache $parts = pathinfo($this->pathToImage); $fileExtension = $parts['extension']; $this->saveAs = is_null($this->saveAs) ? $fileExtension : $this->saveAs; $quality_ = is_null($this->quality) ? null : "_q{$this->quality}"; $cropToFit_ = is_null($this->cropToFit) ? null : "_cf"; $sharpen_ = is_null($this->sharpen) ? null : "_s"; $dirName = preg_replace('/\//', '-', dirname($this->src)); $cacheFileName = $this->cacheDir . "-{$dirName}-{$parts['filename']}_{$this->newWidth}_{$this->newHeight}{$quality_}{$cropToFit_}{$sharpen_}.{$this->saveAs}"; $cacheFileName = preg_replace('/^a-zA-Z0-9\.-_/', '', $cacheFileName); if($this->verbose) { $this->verbose("Cache file is: {$cacheFileName}"); } return $cacheFileName; } /** * Save Image * */ private function saveImage($cacheFileName, $image) { // Save the image switch($this->saveAs) { case 'jpeg': case 'jpg': if($this->verbose) { $this->verbose("Saving image as JPEG to cache using quality = {$this->quality}."); } imagejpeg($image, $cacheFileName, $this->quality); break; case 'png': if($this->verbose) { $this->verbose("Saving image as PNG to cache."); } imagealphablending($image, false); imagesavealpha($image, true); imagepng($image, $cacheFileName); break; default: $this->errorMessage('No support to save as this file extension.'); break; } if($this->verbose) { clearstatcache(); $cacheFilesize = filesize($cacheFileName); $this->verbose("File size of cached file: {$cacheFilesize} bytes."); $this->verbose("Cache file has a file size of " . round($cacheFilesize/$this->filesize*100) . "% of the original size."); } } /** * Output an image together with last modified header. * * @param string $file as path to the image. */ private function outputImage($file) { $info = getimagesize($file); !empty($info) or $this->errorMessage("The file doesn't seem to be an image."); $mime = $info['mime']; $lastModified = filemtime($file); $gmdate = gmdate("D, d M Y H:i:s", $lastModified); if($this->verbose) { $this->verbose("Memory peak: " . round(memory_get_peak_usage() /1024/1024) . "M"); $this->verbose("Memory limit: " . ini_get('memory_limit')); $this->verbose("Time is {$gmdate} GMT."); } if(!$this->verbose) header('Last-Modified: ' . $gmdate . ' GMT'); if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModified){ if($this->verbose) { $this->verbose("Would send header 304 Not Modified, but its verbose mode."); echo $this->verboseLog; exit; } header('HTTP/1.0 304 Not Modified'); } else { if($this->verbose) { $this->verbose("Would send header to deliver image with modified time: {$gmdate} GMT, but its verbose mode."); echo $this->verboseLog; exit; } header('Content-type: ' . $mime); readfile($file); } exit; } /** * Display error message. * * @param string $message the error message to display. */ private function errorMessage($message) { header("Status: 404 Not Found"); die('img.php says 404 - ' . htmlentities($message)); } /** * Display log message. * * @param string $message the log message to display. */ private function verbose($message) { $this->verboseLog .= "<p>" . htmlentities($message) . "</p>"; } /** * Start verbose log * */ private function startVerboseLog() { // Start displaying log if verbose mode & create url to current image if($this->verbose) { $query = array(); parse_str($_SERVER['QUERY_STRING'], $query); unset($query['verbose']); $url = '?' . http_build_query($query); $this->verboseLog = <<<EOD <html lang='en'> <meta charset='UTF-8'/> <title>img.php verbose mode</title> <h1>Verbose mode</h1> <p><a href=$url><code>$url</code></a><br> <img src='{$url}' /></p> EOD; } } /** * Start verbose log * */ private function checkForCache($cacheFileName) { $imageModifiedTime = filemtime($this->pathToImage); $cacheModifiedTime = is_file($cacheFileName) ? filemtime($cacheFileName) : null; // If cached image is valid, output it. if(!$this->ignoreCache && is_file($cacheFileName) && $imageModifiedTime < $cacheModifiedTime) { if($this->verbose) { $this->verbose("Cache file is valid, output it."); } $this->outputImage($cacheFileName); } if($this->verbose) { $this->verbose("Cache is not valid, process image and create a cached version of it."); } } /** * Get image info * */ private function getImageInfo() { $imgInfo = list($this->width, $this->height, $type, $attr) = getimagesize($this->pathToImage); !empty($imgInfo) or errorMessage("The file doesn't seem to be an image."); $mime = $imgInfo['mime']; if($this->verbose) { $this->filesize = filesize($this->pathToImage); $this->verbose("Image file: {$this->pathToImage}"); $this->verbose("Image information: " . print_r($imgInfo, true)); $this->verbose("Image width x height (type): {$this->width} x {$this->height} ({$type})."); $this->verbose("Image file size: {$this->filesize} bytes."); $this->verbose("Image mime type: {$mime}."); } } /** * Get image info * */ private function openOrginalImage() { $parts = pathinfo($this->pathToImage); $fileExtension = $parts['extension']; switch($fileExtension) { case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($this->pathToImage); if($this->verbose) { $this->verbose("Opened the image as a JPEG image."); } break; case 'png': $image = imagecreatefrompng($this->pathToImage); if($this->verbose) { $this->verbose("Opened the image as a PNG image."); } break; default: $this->errorMessage('No support for this file extension.'); } if($this->verbose) { $this->verbose("File extension is: {$fileExtension}"); } return $image; } /** * Validate incoming arguments * */ private function validate() { is_dir($this->imageDir) or $this->errorMessage('The image dir is not a valid directory.'); is_writable($this->cacheDir) or $this->errorMessage('The cache dir is not a writable directory.'); isset($this->src) or $this->errorMessage('Must set src-attribute.'); preg_match('#^[a-z0-9A-Z-_\.\/]+$#', $this->src) or $this->errorMessage('Filename contains invalid characters.'); substr_compare($this->imageDir, $this->pathToImage, 0, strlen($this->imageDir)) == 0 or $this->errorMessage('Security constraint: Source image is not directly below the directory IMG_PATH.'); is_null($this->saveAs) or in_array($this->saveAs, array('png', 'jpg', 'jpeg')) or $this->errorMessage('Not a valid extension to save image as'); is_null($this->quality) or (is_numeric($this->quality) and $this->quality > 0 and $this->quality <= 100) or $this->errorMessage('Quality out of range'); is_null($this->newWidth) or (is_numeric($this->newWidth) and $this->newWidth > 0 and $this->newWidth <= $this->maxWidth) or $this->errorMessage('Width out of range'); is_null($this->newHeight) or (is_numeric($this->newHeight) and $this->newHeight > 0 and $this->newHeight <= $this->maxHeight) or $this->errorMessage('Height out of range'); is_null($this->cropToFit) or ($this->cropToFit and $this->newWidth and $this->newHeight) or $this->errorMessage('Crop to fit needs both width and height to work'); } }
mit
JM89/personalfinancemanager
PFM.Website/PersonalFinanceManager/DTOs/Salary/SalaryDetails.cs
740
using System; using System.Collections.Generic; namespace PersonalFinanceManager.DTOs.Salary { public class SalaryDetails { public int Id { get; set; } public string Description { get; set; } public DateTime StartDate { get; set; } public DateTime? EndDate { get; set; } public decimal YearlySalary { get; set; } public decimal MonthlyGrossPay { get; set; } public decimal MonthlyNetPay { get; set; } public string UserId { get; set; } public int CurrencyId { get; set; } public IList<SalaryDeductionDetails> SalaryDeductions { get; set; } public int CountryId { get; set; } public int TaxId { get; set; } } }
mit
alexey-ernest/assembly-line
AssemblyLine/DAL/Entities/Employee.cs
618
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AssemblyLine.DAL.Entities { public class Employee { public int Id { get; set; } public User User { get; set; } [Required] [Display(Name = "First Name")] public string FirstName { get; set; } [Required] [Display(Name = "Last Name")] public string LastName { get; set; } public string Post { get; set; } public DateTime Created { get; set; } public virtual ICollection<TaskPerformer> Tasks { get; set; } } }
mit
andrewaguiar/natural-date
lib/natural-date/matcher/year_matcher.rb
297
module YearMatcher def self.match? date, reference_date, expression_map return expression_map[:year].include?(date.year) if expression_map[:year] return true if expression_map[:week_day] || !expression_map[:day] || !expression_map[:month] date.year == reference_date.year end end
mit
sudheerj/generator-jhipster-primeng
gulpfile.js
2719
const gulp = require('gulp'); const bumper = require('gulp-bump'); const eslint = require('gulp-eslint'); const git = require('gulp-git'); const shell = require('gulp-shell'); const fs = require('fs'); const sequence = require('gulp-sequence'); const path = require('path'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); const nsp = require('gulp-nsp'); const plumber = require('gulp-plumber'); gulp.task('eslint', () => gulp.src(['gulpfile.js', 'generators/app/index.js', 'test/*.js']) // .pipe(plumber({errorHandler: handleErrors})) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()) ); gulp.task('nsp', (cb) => { nsp({ package: path.resolve('package.json') }, cb); }); gulp.task('pre-test', () => gulp.src('generators/app/index.js') .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()) ); gulp.task('test', ['pre-test'], (cb) => { let mochaErr; gulp.src('test/*.js') .pipe(plumber()) .pipe(mocha({ reporter: 'spec', timeout: 500000 })) .on('error', (err) => { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', () => { cb(mochaErr); }); }); gulp.task('bump-patch', bump('patch')); gulp.task('bump-minor', bump('minor')); gulp.task('bump-major', bump('major')); gulp.task('git-commit', () => { const v = `update to version ${version()}`; gulp.src(['./generators/**/*', './README.md', './package.json', './gulpfile.js', './.travis.yml', './travis/**/*']) .pipe(git.add()) .pipe(git.commit(v)); }); gulp.task('git-push', (cb) => { const v = version(); git.push('origin', 'master', (err) => { if (err) return cb(err); git.tag(v, v, (err) => { if (err) return cb(err); git.push('origin', 'master', { args: '--tags' }, cb); return true; }); return true; }); }); gulp.task('npm', shell.task([ 'npm publish' ])); function bump(level) { return function () { return gulp.src(['./package.json']) .pipe(bumper({ type: level })) .pipe(gulp.dest('./')); }; } function version() { return JSON.parse(fs.readFileSync('package.json', 'utf8')).version; } gulp.task('prepublish', ['nsp']); gulp.task('default', ['static', 'test']); gulp.task('deploy-patch', sequence('test', 'bump-patch', 'git-commit', 'git-push', 'npm')); gulp.task('deploy-minor', sequence('test', 'bump-minor', 'git-commit', 'git-push', 'npm')); gulp.task('deploy-major', sequence('test', 'bump-major', 'git-commit', 'git-push', 'npm'));
mit
Soladin/studi-budi
spec/studi-budi_spec.rb
820
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "StudiBudi" do # it "fails" do # fail "hey buddy, you should probably rename this file and start specing for real" # end before do @study_helper = StudiBudi.new end it "should get the user's input" do @study_helper.stub!(:gets) {"1"} # @study_helper.action.should eq @study_helper.should_receive(:create) end it "should begin adding cards after creating a collection" do @study_helper.create.should_receive(:adding_cards) end # "if I make a card collection called 'Potatos'" do # adfld.@collection_name should_eq "Potatos" # end # I "should say I'm sorry I didn't finish this. I spent all my time on the .rb and that first test" do # @sol.apology.should eq "Please forgive me" # end end
mit
bcuff/FodyAddinSamples
AnotarSerilogSample/LogEventExtensions.cs
480
using Serilog.Events; public static class LogEventExtensions { public static string MethodName(this LogEvent logEvent) { var logEventPropertyValue = (ScalarValue)logEvent.Properties["MethodName"]; return (string) logEventPropertyValue.Value; } public static int LineNumber(this LogEvent logEvent) { var logEventPropertyValue = (ScalarValue)logEvent.Properties["LineNumber"]; return (int) logEventPropertyValue.Value; } }
mit
datasift/datasift-ruby
lib/pylon.rb
11021
module DataSift # # Class for accessing DataSift's PYLON API class Pylon < DataSift::ApiResource # Check PYLON CSDL is valid by making an /pylon/validate API call # # @param csdl [String] CSDL you wish to validate # @param boolResponse [Boolean] True if you want a boolean response. # @param service [String] The PYLON service to make this API call against # False if you want the full response object # @return [Boolean, Object] Dependent on value of boolResponse def valid?(csdl = '', boolResponse = true, service = 'facebook') fail BadParametersError, 'csdl is required' if csdl.empty? fail BadParametersError, 'service is required' if service.empty? params = { csdl: csdl } res = DataSift.request(:POST, build_path(service, 'pylon/validate', @config), @config, params) boolResponse ? res[:http][:status] == 200 : res end # Compile PYLON CSDL by making an /pylon/compile API call # # @param csdl [String] CSDL you wish to compile # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def compile(csdl, service = 'facebook') fail BadParametersError, 'csdl is required' if csdl.empty? fail BadParametersError, 'service is required' if service.empty? params = { csdl: csdl } DataSift.request(:POST, build_path(service, 'pylon/compile', @config), @config, params) end # Perform /pylon/get API call to query status of your PYLON recordings # # @param hash [String] Hash you with the get the status for # @param id [String] The ID of the PYLON recording to get # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def get(hash = '', id = '', service = 'facebook') fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty? fail BadParametersError, 'service is required' if service.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(id: id) unless id.empty? DataSift.request(:GET, build_path(service, 'pylon/get', @config), @config, params) end # Perform /pylon/get API call to list all PYLON Recordings # # @param page [Integer] Which page of recordings to retreive # @param per_page [Integer] How many recordings to return per page # @param order_by [String, Symbol] Which field to sort results by # @param order_dir [String, Symbol] Order results in ascending or descending # order # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def list(page = nil, per_page = nil, order_by = '', order_dir = '', service = 'facebook') fail BadParametersError, 'service is required' if service.empty? params = {} params.merge!(page: page) unless page.nil? params.merge!(per_page: per_page) unless per_page.nil? params.merge!(order_by: order_by) unless order_by.empty? params.merge!(order_dir: order_dir) unless order_dir.empty? DataSift.request(:GET, build_path(service, 'pylon/get', @config), @config, params) end # Perform /pylon/update API call to update a given PYLON Recording # # @param id [String] The ID of the PYLON recording to update # @param hash [String] The CSDL filter hash this recording should be subscribed to # @param name [String] Update the name of your recording # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def update(id, hash = '', name = '', service = 'facebook') fail BadParametersError, 'service is required' if service.empty? params = { id: id } params.merge!(hash: hash) unless hash.empty? params.merge!(name: name) unless name.empty? DataSift.request(:PUT, build_path(service, 'pylon/update', @config), @config, params) end # Start recording a PYLON filter by making an /pylon/start API call # # @param hash [String] CSDL you wish to begin (or resume) recording # @param name [String] Give your recording a name. Required when starting a # @param id [String] ID of the recording you wish to start # new recording # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def start(hash = '', name = '', id = '', service = 'facebook') fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty? fail BadParametersError, 'service is required' if service.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(name: name) unless name.empty? params.merge!(id: id) unless id.empty? DataSift.request(:PUT, build_path(service, 'pylon/start', @config), @config, params) end # Restart an existing PYLON recording by making an /pylon/start API call with a recording ID # # @param id [String] CSDL you wish to begin (or resume) recording # @param name [String] Give your recording a name. Required when starting a # new recording # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def restart(id, name = '', service = 'facebook') fail BadParametersError, 'id is required' if id.empty? fail BadParametersError, 'service is required' if service.empty? params = { id: id } params.merge!(name: name) unless name.empty? DataSift.request(:PUT, build_path(service, 'pylon/start', @config), @config, params) end # Stop an active PYLON recording by making an /pylon/stop API call # # @param hash [String] CSDL you wish to stop recording # @param id [String] ID of the recording you wish to stop # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def stop(hash = '', id = '', service = 'facebook') fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty? fail BadParametersError, 'service is required' if service.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(id: id) unless id.empty? DataSift.request(:PUT, build_path(service, 'pylon/stop', @config), @config, params) end # Perform a PYLON analysis query by making an /pylon/analyze API call # # @param hash [String] Hash of the recording you wish to perform an # analysis against # @param parameters [String] Parameters of the analysis you wish to perform. # See the # {http://dev.datasift.com/pylon/docs/api-endpoints/pylonanalyze # /pylon/analyze API Docs} for full documentation # @param filter [String] Optional PYLON CSDL for a query filter # @param start_time [Integer] Optional start timestamp for filtering by date # @param end_time [Integer] Optional end timestamp for filtering by date # @param id [String] ID of the recording you wish to analyze # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def analyze(hash = '', parameters = '', filter = '', start_time = nil, end_time = nil, id = '', service = 'facebook') fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty? fail BadParametersError, 'parameters is required' if parameters.empty? fail BadParametersError, 'service is required' if service.empty? params = { parameters: parameters } params.merge!(hash: hash) unless hash.empty? params.merge!(id: id) unless id.empty? params.merge!(filter: filter) unless filter.empty? params.merge!(start: start_time) unless start_time.nil? params.merge!(end: end_time) unless end_time.nil? DataSift.request(:POST, build_path(service, 'pylon/analyze', @config), @config, params) end # Query the tag hierarchy on interactions populated by a particular # recording # # @param hash [String] Hash of the recording you wish to query # @param id [String] ID of the recording you wish to query # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def tags(hash = '', id = '', service = 'facebook') fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty? fail BadParametersError, 'service is required' if service.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(id: id) unless id.empty? DataSift.request(:GET, build_path(service, 'pylon/tags', @config), @config, params) end # Hit the PYLON Sample endpoint to pull public sample data from a PYLON recording # # @param hash [String] The CSDL hash that identifies the recording you want to sample # @param count [Integer] Optional number of public interactions you wish to receive # @param start_time [Integer] Optional start timestamp for filtering by date # @param end_time [Integer] Optional end timestamp for filtering by date # @param filter [String] Optional PYLON CSDL for a query filter # @param id [String] ID of the recording you wish to sample # @param service [String] The PYLON service to make this API call against # @return [Object] API reponse object def sample(hash = '', count = nil, start_time = nil, end_time = nil, filter = '', id = '', service = 'facebook') fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty? fail BadParametersError, 'service is required' if service.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(id: id) unless id.empty? params.merge!(count: count) unless count.nil? params.merge!(start_time: start_time) unless start_time.nil? params.merge!(end_time: end_time) unless end_time.nil? if filter.empty? DataSift.request(:GET, build_path(service, 'pylon/sample', @config), @config, params) else params.merge!(filter: filter) DataSift.request(:POST, build_path(service, 'pylon/sample', @config), @config, params) end end # Hit the PYLON Reference endpoint to expose reference data sets # # @param service [String] The PYLON service to make this API call against # @param slug [String] Optional slug of the reference data set you would like to explore # **opts # @param per_page [Integer] (Optional) How many data sets should be returned per page of results # @param page [Integer] (Optional) Which page of results to return def reference(service:, slug: '', **opts) params = {} params[:per_page] = opts[:per_page] if opts.key?(:per_page) params[:page] = opts[:page] if opts.key?(:page) DataSift.request(:GET, "pylon/#{service}/reference/#{slug}", @config, params) end end end
mit
venliong/webby
lib/htmlform/input_text_test.go
1508
package htmlform import ( "fmt" "github.com/CJ-Jackson/webby" "net/http" "net/url" "testing" ) func TestFormInputText(t *testing.T) { fmt.Println("InputText Test:\r\n") form := New( &InputText{ Name: "text", MinChar: 1, MaxChar: 8, RegExpRule: "^([a-zA-Z]*)$", RegExpErr: "Letters Only", }, &InputText{ Name: "textmatch", MustMatch: "text", MustMatchErr: "Does not match field above!", }, ) fmt.Println(form.Render()) fmt.Println() web := &webby.Web{ Req: &http.Request{ Form: url.Values{ "text": []string{"hello", "123"}, "textmatch": []string{"hello", "hello"}, }, }, } if !form.IsValid(web) { t.Fail() } if form.IsValidSlot(web, 1) { t.Fail() } fmt.Println(form.Render()) fmt.Println() web = &webby.Web{ Req: &http.Request{ Form: url.Values{ "text": []string{"hello"}, "textmatch": []string{"hellofail"}, }, }, } if form.IsValid(web) { t.Fail() } fmt.Println(form.Render()) fmt.Println() web = &webby.Web{ Req: &http.Request{ Form: url.Values{ "text": []string{"hellohello"}, "textmatch": []string{"hellohello"}, }, }, } if form.IsValid(web) { t.Fail() } fmt.Println(form.Render()) fmt.Println() web = &webby.Web{ Req: &http.Request{ Form: url.Values{ "text": []string{"1234"}, "textmatch": []string{"1234"}, }, }, } if form.IsValid(web) { t.Fail() } fmt.Println(form.Render()) fmt.Println() }
mit
jakimowicz/longurl
test/constants.rb
587
ShortToLong = { :tiny_url => { "http://tinyurl.com/cnuw9a" => "http://fabien.jakimowicz.com", "http://tinyurl.com/blnhsg" => "http://www.google.com/search?q=number+of+horns+on+a+unicorn&ie=UTF-8" }, :is_gd => { "http://is.gd/iUKg" => "http://fabien.jakimowicz.com", "http://is.gd/iYCo" => "http://www.google.com/search?q=number+of+horns+on+a+unicorn&ie=UTF-8" }, :friendfeed => { "http://ff.im/-31OFh" => "http://en.wikipedia.org/wiki/Product_requirements_document", "http://ff.im/-31MWm" => "http://www.infrasystems.com/how-to-write-an-mrd.html" } }
mit
szhnet/kcp-netty
kcp-netty/src/main/java/io/jpower/kcp/netty/KcpOutput.java
194
package io.jpower.kcp.netty; import io.netty.buffer.ByteBuf; /** * @author <a href="mailto:szhnet@gmail.com">szh</a> */ public interface KcpOutput { void out(ByteBuf data, Kcp kcp); }
mit
benburkert/poolparty
spec/poolparty/pool/script_spec.rb
1440
require File.dirname(__FILE__) + '/../spec_helper' describe "Script" do it "should have inflate as a class method" do Script.respond_to?(:inflate).should == true end it "should have inflate_file as an instance method" do Script.respond_to?(:inflate_file).should == true end it "should have inflate as an instance method" do Script.new.respond_to?(:inflate).should == true end describe "with a script" do before(:each) do @script = 'script' @filename = 'filename' @pool = Script.new Script.stub!(:new).and_return(@pool) @pool.stub!(:inflate).and_return true end it "should create a new Script when calling on the class method" do Script.should_receive(:new).and_return @pool end it "should instance eval the script" do @pool.should_receive(:instance_eval).with(@script, @filename).and_return true end it "should call inflate on itself" do @pool.should_receive(:inflate).and_return true end after do Script.inflate(@script, @filename) end describe "save!" do before(:each) do pool :appdotcom do keypair "snoodle" cloud :app do has_file :name => "/etc/httpd/httpd.conf" end end @saved = Script.save!(false) end it "should save the keypair" do @saved.should =~ /keypair "snoodle"/ end end end end
mit
bitdeal/bitdeal
src/qt/locale/bitcoin_ro.ts
22876
<TS language="ro" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Click dreapta pentru a modifica adresa o eticheta</translation> </message> <message> <source>Create a new address</source> <translation>Crează o nouă adresă</translation> </message> <message> <source>&amp;New</source> <translation>Nou</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiază în notițe adresa selectată în prezent</translation> </message> <message> <source>&amp;Copy</source> <translation>Copiază</translation> </message> <message> <source>C&amp;lose</source> <translation>Închide</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Șterge adresa curentă selectata din listă</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportă datele din tabul curent in fisier</translation> </message> <message> <source>&amp;Export</source> <translation>Exportă</translation> </message> <message> <source>&amp;Delete</source> <translation>Șterge</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Secventa de cuvinte a parolei</translation> </message> <message> <source>Enter passphrase</source> <translation>Introduceti parola</translation> </message> <message> <source>New passphrase</source> <translation>Noua parolă</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repetati noua parolă</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Netmask</translation> </message> <message> <source>Banned Until</source> <translation>Blocat până</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Semnează &amp;mesajul...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Se sincronizează cu rețeaua</translation> </message> <message> <source>Node</source> <translation>Nod</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Arată o prezentare generală a portofelului.</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Tranzacții</translation> </message> <message> <source>Browse transaction history</source> <translation>Navighează în istoricul tranzacțiilor</translation> </message> <message> <source>Quit application</source> <translation>Părăsește aplicația</translation> </message> <message> <source>About &amp;Qt</source> <translation>Despre &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Arată informații despre Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opțiuni...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Criptează portofelul...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup portofel</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Schimbă parola...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Trimite adresele...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>&amp;Primește adresele...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Deschide &amp;URI...</translation> </message> <message> <source>Send coins to a Bitdeal address</source> <translation>Trimite monedele către o adresă Bitdeal</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Fă o copie de rezervă a portofelului într-o altă locație</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Schimbă parola folosită pentru criptarea portofelului</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Fereastra pentru depanare</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Pornește consola pentru depanare si diagnoză</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verifică mesajul...</translation> </message> <message> <source>Bitdeal</source> <translation>Bitdeal</translation> </message> <message> <source>Wallet</source> <translation>Portofel</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Trimite</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Primește</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Arată/Ascunde</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Arată sau ascunde fereastra principală</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Criptează cheile private care aparțin portofelului tău.</translation> </message> <message> <source>Sign messages with your Bitdeal addresses to prove you own them</source> <translation>Semnează mesajele cu adresa ta de Bitdeal pentru a face dovada că îți aparțin.</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Bitdeal addresses</source> <translation>Verifică mesajele cu scopul de a asigura faptul că au fost semnate cu adresa de Bitdeal specificată.</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Fișier</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Setări</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ajutor</translation> </message> <message> <source>Request payments (generates QR codes and bitdeal: URIs)</source> <translation>Cerere plată (generează coduri QR și bitdeal: URIs)</translation> </message> <message> <source>Open a bitdeal: URI or payment request</source> <translation>Deschide un bitdeal: URI sau cerere de plată</translation> </message> <message> <source>%1 and %2</source> <translation>%1 și %2</translation> </message> <message> <source>%1 behind</source> <translation>%1 în urmă</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Ultimul bloc primit a fost generat acum %1</translation> </message> <message> <source>Error</source> <translation>Eroare</translation> </message> <message> <source>Warning</source> <translation>Atenționare</translation> </message> <message> <source>Information</source> <translation>Informație</translation> </message> <message> <source>Up to date</source> <translation>Actual</translation> </message> <message> <source>Date: %1 </source> <translation>Data: %1</translation> </message> <message> <source>Amount: %1 </source> <translation>Cantitate: %1</translation> </message> <message> <source>Type: %1 </source> <translation>Tip: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Etichetă: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Adresa: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Trimite tranzacția</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portofelul este &lt;b&gt;criptat&lt;/b&gt; și în prezent &lt;b&gt;deblocat&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portofelul este &lt;b&gt;criptat&lt;/b&gt; și în prezent &lt;b&gt;blocat&lt;/b&gt;</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Selecția monedelor</translation> </message> <message> <source>Quantity:</source> <translation>Cantitatea:</translation> </message> <message> <source>Bytes:</source> <translation>Biți:</translation> </message> <message> <source>Amount:</source> <translation>Cantitate:</translation> </message> <message> <source>Priority:</source> <translation>Prioritate:</translation> </message> <message> <source>Fee:</source> <translation>Taxa:</translation> </message> <message> <source>After Fee:</source> <translation>După taxă:</translation> </message> <message> <source>Change:</source> <translation>Schimbă:</translation> </message> <message> <source>Tree mode</source> <translation>Mod arbore</translation> </message> <message> <source>List mode</source> <translation>Mod listă</translation> </message> <message> <source>Amount</source> <translation>Cantitate</translation> </message> <message> <source>Received with address</source> <translation>Primit cu adresa</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Confirmations</source> <translation>Confirmări</translation> </message> <message> <source>Confirmed</source> <translation>Confirmat</translation> </message> <message> <source>Priority</source> <translation>Prioritate</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Modifică adresa</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>name</source> <translation>Nume</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Directoriul există deja. Adaugă %1 dacă ai intenționat să creezi aici un directoriu nou.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>versiune</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>Start minimized</source> <translation>Pornește minimalizat</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Bine ai venit!</translation> </message> <message> <source>Use the default data directory</source> <translation>Folosește directoriul pentru date din modul implicit.</translation> </message> <message> <source>Error</source> <translation>Eroare</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB de spațiu liber disponibil</numerusform><numerusform>%n GB de spațiu liber disponibil</numerusform><numerusform>%n GB de spațiu liber disponibil</numerusform></translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Deschide URI</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opțiuni</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Accept connections from outside</source> <translation>Acceptă conexiuni externe</translation> </message> <message> <source>Allow incoming connections</source> <translation>Acceptă conexiunea care sosește</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Adresa IP a proxy-ului (ex. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Resetează opțiunile</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Rețea</translation> </message> <message> <source>Expert</source> <translation>Expert</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Portul pentru proxy (ex.: 9050)</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Anulează</translation> </message> <message> <source>default</source> <translation>inițial</translation> </message> <message> <source>none</source> <translation>fără</translation> </message> <message> <source>Confirm options reset</source> <translation>Confirmă resetarea opțiunilor</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Repornirea clientului este necesară pentru ca schimbările să fie activate</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>Clientul va fi oprit. Dorești sa continui?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Această schimbare necesită repornirea clientului.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Available:</source> <translation>Disponibil:</translation> </message> <message> <source>Total:</source> <translation>Total:</translation> </message> <message> <source>Recent transactions</source> <translation>Tranzacții recente</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Cantitate</translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>Client version</source> <translation>Versiunea clientului</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Informații</translation> </message> <message> <source>Debug window</source> <translation>Fereastra pentru depanare</translation> </message> <message> <source>General</source> <translation>General</translation> </message> <message> <source>Network</source> <translation>Rețea</translation> </message> <message> <source>Name</source> <translation>Nume</translation> </message> <message> <source>Number of connections</source> <translation>Numărul de conexiuni</translation> </message> <message> <source>Received</source> <translation>Primit</translation> </message> <message> <source>Sent</source> <translation>Trimis</translation> </message> <message> <source>Direction</source> <translation>Direcția</translation> </message> <message> <source>Version</source> <translation>Versiune</translation> </message> <message> <source>Connection Time</source> <translation>Durata conexiunii</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Deschide</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Consolă</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;ore</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;zi</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;săptămână</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;an</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>Yes</source> <translation>Da</translation> </message> <message> <source>No</source> <translation>Nu</translation> </message> <message> <source>Unknown</source> <translation>Necunoscut</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>Show</source> <translation>Arată</translation> </message> <message> <source>Remove</source> <translation>Elimină</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>&amp;Save Image...</source> <translation>&amp;Salvează imaginea...</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> <message> <source>Quantity:</source> <translation>Cantitatea:</translation> </message> <message> <source>Bytes:</source> <translation>Biți:</translation> </message> <message> <source>Amount:</source> <translation>Cantitate:</translation> </message> <message> <source>Priority:</source> <translation>Prioritate:</translation> </message> <message> <source>Fee:</source> <translation>Taxa:</translation> </message> <message> <source>After Fee:</source> <translation>După taxă:</translation> </message> <message> <source>Change:</source> <translation>Schimbă:</translation> </message> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Bitdeal Core</source> <translation>Bitdeal Core</translation> </message> <message> <source>Information</source> <translation>Informație</translation> </message> <message> <source>Warning</source> <translation>Atenționare</translation> </message> <message> <source>Error</source> <translation>Eroare</translation> </message> </context> </TS>
mit
marshallhumble/python-linkedin
linkedin/linkedin.py
22069
import contextlib import hashlib import random from urllib.parse import quote, quote_plus, urljoin import requests from requests_oauthlib import OAuth1 from io import StringIO from .exceptions import LinkedInError from .models import AccessToken, LinkedInInvitation, LinkedInMessage from .utils import enum, to_utf8, raise_for_error, json __all__ = ['LinkedInAuthentication', 'LinkedInApplication', 'PERMISSIONS'] """ It looks like linked has changed the permissions it will grant to clients, some od these items are no longer allowed. I will put the ones here in the comments that I have removed: EMAIL_ADDRESS='r_emailaddress', """ PERMISSIONS = enum('Permission', COMPANY_ADMIN='rw_company_admin', BASIC_PROFILE='r_basicprofile', EMAIL_ADDRESS='r_emailaddress', SHARE='w_share') ENDPOINTS = enum('LinkedInURL', PEOPLE='https://api.linkedin.com/v1/people', PEOPLE_SEARCH='https://api.linkedin.com/v1/people-search', GROUPS='https://api.linkedin.com/v1/groups', POSTS='https://api.linkedin.com/v1/posts', COMPANIES='https://api.linkedin.com/v1/companies', COMPANY_SEARCH='https://api.linkedin.com/v1/company-search', JOBS='https://api.linkedin.com/v1/jobs', JOB_SEARCH='https://api.linkedin.com/v1/job-search') NETWORK_UPDATES = enum('NetworkUpdate', APPLICATION='APPS', COMPANY='CMPY', CONNECTION='CONN', JOB='JOBS', GROUP='JGRP', PICTURE='PICT', EXTENDED_PROFILE='PRFX', CHANGED_PROFILE='PRFU', SHARED='SHAR', VIRAL='VIRL') class LinkedInDeveloperAuthentication(object): """ Uses all four credentials provided by LinkedIn as part of an OAuth 1.0a flow that provides instant API access with no redirects/approvals required. Useful for situations in which users would like to access their own data or during the development process. """ def __init__(self, consumer_key, consumer_secret, user_token, user_secret, redirect_uri, permissions=[]): self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_token = user_token self.user_secret = user_secret self.redirect_uri = redirect_uri self.permissions = permissions class LinkedInAuthentication(object): """ Implements a standard OAuth 2.0 flow that involves redirection for users to authorize the application to access account data. """ AUTHORIZATION_URL = 'https://www.linkedin.com/uas/oauth2/authorization' ACCESS_TOKEN_URL = 'https://www.linkedin.com/uas/oauth2/accessToken' def __init__(self, key, secret, redirect_uri, permissions=None): self.key = key self.secret = secret self.redirect_uri = redirect_uri self.permissions = permissions or [] self.state = None self.authorization_code = None self.token = None self._error = None @property def authorization_url(self): qd = {'response_type': 'code', 'client_id': self.key, 'scope': (' '.join(self.permissions)).strip(), 'state': self.state or self._make_new_state(), 'redirect_uri': self.redirect_uri} # urlencode uses quote_plus when encoding the query string so, # we ought to be encoding the qs by on our own. # we need to not return this as a string and instead return as bytes for urlib.parse qsl = [] for k, v in list(qd.items()): qsl.append('%s=%s' % (quote(k), quote(v))) return urljoin(self.AUTHORIZATION_URL, '?' + '&'.join(qsl), allow_fragments=True ) @property def last_error(self): return self._error def _make_new_state(self): return hashlib.md5( '{}{}'.format(random.randrange(0, 2 ** 63), self.secret).encode("utf8") ).hexdigest() def get_access_token(self, timeout=60): assert self.authorization_code, 'You must first get the authorization code' qd = {'grant_type': 'authorization_code', 'code': self.authorization_code, 'redirect_uri': self.redirect_uri, 'client_id': self.key, 'client_secret': self.secret} response = requests.post(self.ACCESS_TOKEN_URL, data=qd, timeout=timeout) raise_for_error(response) response = response.json() self.token = AccessToken(response['access_token'], response['expires_in']) return self.token class LinkedInSelector(object): @classmethod def parse(cls, selector): with contextlib.closing(StringIO()) as result: if type(selector) == dict: for k, v in list(selector.items()): result.write('%s:(%s)' % (to_utf8(k), cls.parse(v))) elif type(selector) in (list, tuple): result.write(','.join(map(cls.parse, selector))) else: result.write(to_utf8(selector)) return result.getvalue() class LinkedInApplication(object): BASE_URL = 'https://api.linkedin.com' def __init__(self, authentication=None, token=None): assert authentication or token, 'Either authentication instance or access token is required' self.authentication = authentication if not self.authentication: self.authentication = LinkedInAuthentication('', '', '') self.authentication.token = AccessToken(token, None) def make_request(self, method, url, data=None, params=None, headers=None, timeout=60): if headers is None: headers = {'x-li-format': 'json', 'Content-Type': 'application/json'} else: headers.update({'x-li-format': 'json', 'Content-Type': 'application/json'}) if params is None: params = {} kw = dict(data=data, params=params, headers=headers, timeout=timeout) if isinstance(self.authentication, LinkedInDeveloperAuthentication): # Let requests_oauthlib.OAuth1 do *all* of the work here auth = OAuth1(self.authentication.consumer_key, self.authentication.consumer_secret, self.authentication.user_token, self.authentication.user_secret) kw.update({'auth': auth}) else: params.update({'oauth2_access_token': self.authentication.token.access_token}) return requests.request(method.upper(), url, **kw) def get_profile(self, member_id=None, member_url=None, selectors=None, params=None, headers=None): if member_id: if type(member_id) is list: # Batch request, ids as CSV. url = '%s::(%s)' % (ENDPOINTS.PEOPLE, ','.join(member_id)) else: url = '%s/id=%s' % (ENDPOINTS.PEOPLE, str(member_id)) elif member_url: url = '%s/url=%s' % (ENDPOINTS.PEOPLE, quote_plus(member_url)) else: url = '%s/~' % ENDPOINTS.PEOPLE if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def search_profile(self, selectors=None, params=None, headers=None): if selectors: url = '%s:(%s)' % (ENDPOINTS.PEOPLE_SEARCH, LinkedInSelector.parse(selectors)) else: url = ENDPOINTS.PEOPLE_SEARCH response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_picture_urls(self, member_id=None, member_url=None, params=None, headers=None): if member_id: url = '%s/id=%s/picture-urls::(original)' % (ENDPOINTS.PEOPLE, str(member_id)) elif member_url: url = '%s/url=%s/picture-urls::(original)' % (ENDPOINTS.PEOPLE, quote_plus(member_url)) else: url = '%s/~/picture-urls::(original)' % ENDPOINTS.PEOPLE response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_connections(self, member_id=None, member_url=None, selectors=None, params=None, headers=None): if member_id: url = '%s/id=%s/connections' % (ENDPOINTS.PEOPLE, str(member_id)) elif member_url: url = '%s/url=%s/connections' % (ENDPOINTS.PEOPLE, quote_plus(member_url)) else: url = '%s/~/connections' % ENDPOINTS.PEOPLE if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_memberships(self, member_id=None, member_url=None, group_id=None, selectors=None, params=None, headers=None): if member_id: url = '%s/id=%s/group-memberships' % (ENDPOINTS.PEOPLE, str(member_id)) elif member_url: url = '%s/url=%s/group-memberships' % (ENDPOINTS.PEOPLE, quote_plus(member_url)) else: url = '%s/~/group-memberships' % ENDPOINTS.PEOPLE if group_id: url = '%s/%s' % (url, str(group_id)) if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_group(self, group_id, selectors=None, params=None, headers=None): url = '%s/%s' % (ENDPOINTS.GROUPS, str(group_id)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_posts(self, group_id, post_ids=None, selectors=None, params=None, headers=None): url = '%s/%s/posts' % (ENDPOINTS.GROUPS, str(group_id)) if post_ids: url = '%s::(%s)' % (url, ','.join(map(str, post_ids))) if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_post_comments(self, post_id, selectors=None, params=None, headers=None): url = '%s/%s/comments' % (ENDPOINTS.POSTS, post_id) if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def join_group(self, group_id): url = '%s/~/group-memberships/%s' % (ENDPOINTS.PEOPLE, str(group_id)) response = self.make_request('PUT', url, data=json.dumps({'membershipState': {'code': 'member'}})) raise_for_error(response) return True def leave_group(self, group_id): url = '%s/~/group-memberships/%s' % (ENDPOINTS.PEOPLE, str(group_id)) response = self.make_request('DELETE', url) raise_for_error(response) return True def submit_group_post(self, group_id, title, summary, submitted_url, submitted_image_url, content_title, description): post = { 'title': title, 'summary': summary, 'content': { 'submitted-url': submitted_url, 'title': content_title, 'description': description } } if submitted_image_url: post['content']['submitted-image-url'] = submitted_image_url url = '%s/%s/posts' % (ENDPOINTS.GROUPS, str(group_id)) response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return True def like_post(self, post_id, action): url = '%s/%s/relation-to-viewer/is-liked' % (ENDPOINTS.POSTS, str(post_id)) try: self.make_request('PUT', url, data=json.dumps(action)) except (requests.ConnectionError, requests.HTTPError) as error: raise LinkedInError(error.message) else: return True def comment_post(self, post_id, comment): post = { 'text': comment } url = '%s/%s/comments' % (ENDPOINTS.POSTS, str(post_id)) try: self.make_request('POST', url, data=json.dumps(post)) except (requests.ConnectionError, requests.HTTPError) as error: raise LinkedInError(error.message) else: return True def get_company_by_email_domain(self, email_domain, params=None, headers=None): url = '%s?email-domain=%s' % (ENDPOINTS.COMPANIES, email_domain) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_companies(self, company_ids=None, universal_names=None, selectors=None, params=None, headers=None): identifiers = [] url = ENDPOINTS.COMPANIES if company_ids: identifiers += list(map(str, company_ids)) if universal_names: identifiers += ['universal-name=%s' % un for un in universal_names] if identifiers: url = '%s::(%s)' % (url, ','.join(identifiers)) if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_company_updates(self, company_id, params=None, headers=None): url = '%s/%s/updates' % (ENDPOINTS.COMPANIES, str(company_id)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_company_products(self, company_id, selectors=None, params=None, headers=None): url = '%s/%s/products' % (ENDPOINTS.COMPANIES, str(company_id)) if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def follow_company(self, company_id): url = '%s/~/following/companies' % ENDPOINTS.PEOPLE post = {'id': company_id} response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return True def unfollow_company(self, company_id): url = '%s/~/following/companies/id=%s' % (ENDPOINTS.PEOPLE, str(company_id)) response = self.make_request('DELETE', url) raise_for_error(response) return True def search_company(self, selectors=None, params=None, headers=None): url = ENDPOINTS.COMPANY_SEARCH if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def submit_company_share(self, company_id, comment=None, title=None, description=None, submitted_url=None, submitted_image_url=None, visibility_code='anyone'): post = { 'visibility': { 'code': visibility_code, }, } if comment is not None: post['comment'] = comment if title is not None and submitted_url is not None: post['content'] = { 'title': title, 'submitted-url': submitted_url, 'description': description, } if submitted_image_url: post['content']['submitted-image-url'] = submitted_image_url url = '%s/%s/shares' % (ENDPOINTS.COMPANIES, company_id) response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return response.json() def get_job(self, job_id, selectors=None, params=None, headers=None): url = '%s/%s' % (ENDPOINTS.JOBS, str(job_id)) url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_job_bookmarks(self, selectors=None, params=None, headers=None): url = '%s/~/job-bookmarks' % ENDPOINTS.PEOPLE if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def search_job(self, selectors=None, params=None, headers=None): url = ENDPOINTS.JOB_SEARCH if selectors: url = '%s:(%s)' % (url, LinkedInSelector.parse(selectors)) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def submit_share(self, comment=None, title=None, description=None, submitted_url=None, submitted_image_url=None, visibility_code='anyone'): post = { 'visibility': { 'code': visibility_code, }, } if comment is not None: post['comment'] = comment if title is not None and submitted_url is not None: post['content'] = { 'title': title, 'submitted-url': submitted_url, 'description': description, } if submitted_image_url: post['content']['submitted-image-url'] = submitted_image_url url = '%s/~/shares' % ENDPOINTS.PEOPLE response = self.make_request('POST', url, data=json.dumps(post)) raise_for_error(response) return response.json() def get_network_updates(self, types, member_id=None, self_scope=True, params=None, headers=None): if member_id: url = '%s/id=%s/network/updates' % (ENDPOINTS.PEOPLE, str(member_id)) else: url = '%s/~/network/updates' % ENDPOINTS.PEOPLE if not params: params = {} if types: params.update({'type': types}) if self_scope is True: params.update({'scope': 'self'}) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_network_update(self, types, update_key, self_scope=True, params=None, headers=None): url = '%s/~/network/updates/key=%s' % (ENDPOINTS.PEOPLE, str(update_key)) if not params: params = {} if types: params.update({'type': types}) if self_scope is True: params.update({'scope': 'self'}) response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def get_network_status(self, params=None, headers=None): url = '%s/~/network/network-stats' % ENDPOINTS.PEOPLE response = self.make_request('GET', url, params=params, headers=headers) raise_for_error(response) return response.json() def send_invitation(self, invitation): assert type(invitation) == LinkedInInvitation, 'LinkedInInvitation required' url = '%s/~/mailbox' % ENDPOINTS.PEOPLE response = self.make_request('POST', url, data=json.dumps(invitation.json)) raise_for_error(response) return True def send_message(self, message): assert type(message) == LinkedInMessage, 'LinkedInInvitation required' url = '%s/~/mailbox' % ENDPOINTS.PEOPLE response = self.make_request('POST', url, data=json.dumps(message.json)) raise_for_error(response) return True def comment_on_update(self, update_key, comment): comment = {'comment': comment} url = '%s/~/network/updates/key=%s/update-comments' % (ENDPOINTS.PEOPLE, update_key) response = self.make_request('POST', url, data=json.dumps(comment)) raise_for_error(response) return True def like_update(self, update_key, is_liked=True): url = '%s/~/network/updates/key=%s/is-liked' % (ENDPOINTS.PEOPLE, update_key) response = self.make_request('PUT', url, data=json.dumps(is_liked)) raise_for_error(response) return True def comment_as_company(self, company_id, update_key, comment): comment = {'comment': comment} url = '%s/updates/key=%s/update-comments-as-company' % ( ENDPOINTS.COMPANIES, company_id, update_key) response = self.make_request('PUT', url, data=json.dumps(comment)) raise_for_error(response) return True
mit
sophieottaway/test-project
app/routes.js
520
module.exports = { bind : function (app) { app.get('/', function (req, res) { res.render('index'); }); app.get('/examples/template-data', function (req, res) { res.render('examples/template-data', { 'name' : 'Foo' }); }); // add your routes here app.get('/examples/process1', function (req, res) { res.render('examples/process1/', { "name": "Chris", "age": "James", "address": "50 Sleep Street", "owesTax": true }); }); } };
mit
xmljim/w3odrl21
W3COdrl2/src/main/java/org/w3c/odrl/W3COdrl2/parsers/OdrlContentProcessorException.java
984
/** * */ package org.w3c.odrl.W3COdrl2.parsers; /** * @author Jim Earley <xml.jim@gmail.com> Sep 10, 2014 * */ public class OdrlContentProcessorException extends OdrlParserException { /** * */ private static final long serialVersionUID = -6320596040668800253L; /** * */ public OdrlContentProcessorException() { // TODO Auto-generated constructor stub } /** * @param arg0 */ public OdrlContentProcessorException(final String arg0) { super(arg0); // TODO Auto-generated constructor stub } /** * @param arg0 */ public OdrlContentProcessorException(final Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub } /** * @param arg0 * @param arg1 */ public OdrlContentProcessorException(final String arg0, final Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } }
mit
ffuenf/Ffuenf_CategoryProductSortBackend
skin/adminhtml/default/default/js/categoryproductsortbackend.js
4340
var isBackend = typeof FORM_KEY != 'undefined'; function changeOrder(categoryId, productId, neighbourId, ajaxBlockUrl, listId, listTag) { if (!isBackend) { // display centered loader hint box with icon and text var scrollTop = $(document).viewport.getScrollOffsets().top; var avTop = ($(document).viewport.getHeight() / 2) - ($('categoryproductsortbackend-preloader').getLayout().get('margin-box-height') / 2) + scrollTop; if (avTop <= 10) { avTop = 10; } var styles = { top : avTop + 'px' }; $('categoryproductsortbackend-preloader').setStyle(styles); $('categoryproductsortbackend-preloader').removeClassName('hide'); } new Ajax.Request(ajaxBlockUrl, { parameters: { categoryId: categoryId, productId: productId, neighbourId: neighbourId, isAjax: 'true', form_key: isBackend ? FORM_KEY : '' }, onSuccess: function(transport) { if (isBackend) { try { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON(); if (response.error) { alert(response.message); } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } resetListItems(listId, listTag, response); } else { alert(transport.responseText); } } catch (e) { alert(transport.responseText); } } else { $('categoryproductsortbackend-preloader').addClassName('hide'); } } }); } function processSorting (categoryId, listId, listTag, ajaxUrl) { var listItemId; if (isBackend) { /** * Firefox bug/feature workaround for checkbox deselecting in the category products grid */ $(listId).select(listTag).each(function(item) { clickEvents = item.getStorage().get('prototype_event_registry').get('click'); clickEvents.each(function(wrapper){ Event.observe(item.select('.checkbox').first(), 'click', wrapper.handler); }); item.stopObserving('click'); }); } Sortable.create(listId, { tag: listTag, onUpdate: function(list) { var listSize = list.length; var counter = 0; list.select(listTag).each(function(item) { counter++; if(item.getAttribute('id') == listItemId) { if(counter == 1) { var delta = 0 - item.getAttribute('id').replace('item_',''); } else { var previousItem = item.previous().getAttribute('id').replace('item_',''); var delta = previousItem - item.getAttribute('id').replace('item_',''); } var productId = getProductId(item, listTag); var neighbourId = getProductId(delta > 0 ? item.previous() : item.next(), listTag); changeOrder(categoryId, productId, neighbourId, ajaxUrl, listId, listTag); resetListItems(listId, listTag); throw $break; } }); }, onChange: function(item) { listItemId = item.getAttribute('id'); } }); } function resetListItems(listId, listTag, newOrder) { var i = 0; var changePositions = false; var inputElement, newId; if (typeof newOrder == 'object') { newOrder = object2array(newOrder); changePositions = true; } $(listId).select(listTag).each(function(item) { i++; item.setAttribute('id', 'item_' + i); if (changePositions && (newId = newOrder[getProductId(item, listTag)])) { inputElement = item.select('input[type=text]').first(); inputElement.setAttribute('value', newId); inputElement.triggerEvent('keyup'); } }); } function getProductId (item, listTag) { if (listTag == 'tr') { var productId = item.down().next().innerHTML; } else { var productId = item.getAttribute('productId'); } return parseInt(productId); } function object2array (obj) { var arr = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { arr[key] = obj[key]; } } return arr; } Element.prototype.triggerEvent = function(eventName) { if (document.createEvent) { var evt = document.createEvent('HTMLEvents'); evt.initEvent(eventName, true, true); this.dispatchEvent(evt); } if (this.fireEvent) { this.fireEvent('on' + eventName); } };
mit
zhangqiang110/my4j
pms/src/main/java/com/reasonablespread/service/SplitContactsResponse.java
3776
/** * SplitContactsResponse.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.reasonablespread.service; public class SplitContactsResponse implements java.io.Serializable { private boolean splitContactsResult; public SplitContactsResponse() { } public SplitContactsResponse( boolean splitContactsResult) { this.splitContactsResult = splitContactsResult; } /** * Gets the splitContactsResult value for this SplitContactsResponse. * * @return splitContactsResult */ public boolean isSplitContactsResult() { return splitContactsResult; } /** * Sets the splitContactsResult value for this SplitContactsResponse. * * @param splitContactsResult */ public void setSplitContactsResult(boolean splitContactsResult) { this.splitContactsResult = splitContactsResult; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof SplitContactsResponse)) return false; SplitContactsResponse other = (SplitContactsResponse) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && this.splitContactsResult == other.isSplitContactsResult(); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; _hashCode += (isSplitContactsResult() ? Boolean.TRUE : Boolean.FALSE).hashCode(); __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(SplitContactsResponse.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://service.reasonablespread.com/", ">SplitContactsResponse")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("splitContactsResult"); elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "SplitContactsResult")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
mit
stefanliydov/SoftUniLab
RedoingHomeworkCuzFML/ConsoleApplication1/Properties/AssemblyInfo.cs
1414
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication1")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b0236fe0-4b09-4493-b7cf-0e1c055e1cbc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
getfundament/fundament
src/js/core.js
2909
/*! * Fundament framework v0.4.0 * * https://getfundament.com * * @license MIT * @author Jason Koolman and The Fundament Authors */ window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback){ setTimeout(callback, 0) }; /** * Fundament core variables and utility functions. * * @package Fundament */ var Fm = (function(document) { var cssPrefixes = ['-webkit-', '-moz-', '-ms-', '-o-'], cssDeclaration = document.createElement('div').style; /** * Generate a fairly random unique identifier. * * @returns {string} */ function generateId() { return (Math.random().toString(16) + '000000000').substr(2,8); } /** * Debounces a function which will be called after it stops being * called for x milliseconds. If 'immediate' is passed, trigger * the function on the leading edge, instead of the trailing. * * @param {function} func * @param {int} wait * @param {boolean} immediate */ function debounce(func, wait, immediate) { var timeout; return function() { var self = this, args = arguments, callNow = immediate && !timeout; var later = function() { timeout = null; if ( ! immediate) func.apply(self, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(self, args); }; } /** * Returns a prefixed CSS property. * * @param {string} attr * @returns {string} */ function prefixProp(attr) { if (cssDeclaration[attr] === undefined) { for (var i = 0; i < cssPrefixes.length; i++) { var prefixed = cssPrefixes[i] + attr; if (cssDeclaration[prefixed] !== undefined) { attr = prefixed; } } } return attr; } /** * Returns the supported transitionEnd event. * * @returns {string|null} */ function transitionEnd() { var events = { transition : 'transitionend', OTransition : 'otransitionend', MozTransition : 'transitionend', WebkitTransition : 'webkitTransitionEnd' }; for (var event in events) { if (cssDeclaration[event] !== undefined) { return events[event]; } } return null; } return { createID: generateId, debounce: debounce, prefixProp: prefixProp, transitionEnd: transitionEnd }; })(document);
mit
lcy2080/OpenGL_Example
Template_OpenGL/Template_OpenGL/main.cpp
2645
// // main.cpp // Template_OpenGL // // Created by 이창영 on 2015. 8. 12.. // Copyright (c) 2015년 이창영. All rights reserved. // #include <iostream> using namespace std; /*glut for Windows*/ //#include <GL/glut.h> /*glut for Mac*/ //#include <OpenGL/OpenGL.h> #include <GLUT/GLUT.h> /*GLUT display callback function*/ void display(void); /*GLUT window reshape callback function*/ void reshape(int, int); int main(int argc, char * argv[]) { //init glutInit(&argc, argv); //set the window size 512*512 glutInitWindowSize(512, 512); /* Set the display color to Red,Green,Blue and Alpha Allocate a depth buffer enable double buffering */ glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); //set the window position glutInitWindowPosition(0, 0); //Create the window and Call it "OpenGL_Template" glutCreateWindow("OpenGL_Template"); /* Set the glut display callback function this is the function GLUT will call every time the window needs to be drawn */ glutDisplayFunc(display); /* Set the glut reshape callback function this is the function GLUT will call whenever the window is resized, including when it is first created */ glutReshapeFunc(reshape); /*set the default background color to black*/ glClearColor(0, 0, 0, 1); /* enter the main event loop so that GLUT can process all of the window event messages */ glutMainLoop(); //glutInit(&argc, argv); // insert code here... std::cout << "Hello, World!\n"; return 0; } void display() { //Clear the color buffer glClear(GL_COLOR_BUFFER_BIT); //set the current drawing color to red glColor3f(1, 0, 0); //start drawing triangles, each triangles takes 3 vertices glBegin(GL_TRIANGLES); glVertex2f(10, 10); glVertex2f(250, 400); glVertex2f(400, 10); //tell OpenGL we're done drawing triangles glEnd(); //swap the back and front buffers so we can see what we just drew glutSwapBuffers(); } void reshape(int width, int height) { /* tell OpenGL we want to display in a rectangle that is the same size as the window */ glViewport(0, 0, width, height); //switch to the projection martix glMatrixMode(GL_PROJECTION); //clear the projection matrix glLoadIdentity(); //set the camera view, orthographic projection in 2D gluOrtho2D(0, width, 0, height); //switch back to the model view matrix glMatrixMode(GL_MODELVIEW); }
mit
juankiz/react-native-carousel
Carousel.js
4129
'use strict'; var React = require('react'); var { Dimensions, StyleSheet, Text, View, } = require('react-native'); var TimerMixin = require('react-timer-mixin'); var CarouselPager = require('./CarouselPager'); var Carousel = React.createClass({ mixins: [TimerMixin], getDefaultProps() { return { hideIndicators: false, indicatorColor: '#000000', indicatorSize: 50, inactiveIndicatorColor: '#999999', indicatorAtBottom: true, indicatorOffset: 250, indicatorText: '•', inactiveIndicatorText: '•', width: null, initialPage: 0, indicatorSpace: 25, animate: true, delay: 1000, loop: true, }; }, getInitialState() { return { activePage: this.props.initialPage > 0 ? this.props.initialPage : 0, }; }, getWidth() { if (this.props.width !== null) { return this.props.width; } else { return Dimensions.get('window').width; } }, componentDidMount() { if (this.props.initialPage > 0) { this.refs.pager.scrollToPage(this.props.initialPage, false); } if (this.props.animate && this.props.children){ this._setUpTimer(); } }, indicatorPressed(activePage) { this.setState({activePage}); this.refs.pager.scrollToPage(activePage); }, renderPageIndicator() { if (this.props.hideIndicators === true) { return null; } var indicators = [], indicatorStyle = this.props.indicatorAtBottom ? { bottom: this.props.indicatorOffset } : { top: this.props.indicatorOffset }, style, position; position = { width: this.props.children.length * this.props.indicatorSpace, }; position.left = (this.getWidth() - position.width) / 2; for (var i = 0, l = this.props.children.length; i < l; i++) { if (typeof this.props.children[i] === "undefined") { continue; } style = i === this.state.activePage ? { color: this.props.indicatorColor } : { color: this.props.inactiveIndicatorColor }; indicators.push( <Text style={[style, { fontSize: this.props.indicatorSize }]} key={i} onPress={this.indicatorPressed.bind(this,i)} > { i === this.state.activePage ? this.props.indicatorText : this.props.inactiveIndicatorText } </Text> ); } if (indicators.length === 1) { return null; } return ( <View style={[styles.pageIndicator, position, indicatorStyle]}> {indicators} </View> ); }, _setUpTimer() { if (this.props.children.length > 1) { this.clearTimeout(this.timer); this.timer = this.setTimeout(this._animateNextPage, this.props.delay); } }, _animateNextPage() { var activePage = 0; if (this.state.activePage < this.props.children.length - 1) { activePage = this.state.activePage + 1; } else if (!this.props.loop) { return; } this.indicatorPressed(activePage); this._setUpTimer(); }, _onAnimationBegin() { this.clearTimeout(this.timer); }, _onAnimationEnd(activePage) { this.setState({activePage}); if (this.props.onPageChange) { this.props.onPageChange(activePage); } }, render() { return ( <View style={{ flex: 1 }}> <CarouselPager ref="pager" width={this.getWidth()} contentContainerStyle={styles.container} onBegin={this._onAnimationBeginPage} onEnd={this._onAnimationEnd} > {this.props.children} </CarouselPager> {this.renderPageIndicator()} </View> ); }, }); var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, page: { alignItems: 'center', justifyContent: 'center', borderWidth: 1, }, pageIndicator: { position: 'absolute', flexDirection: 'row', flex: 1, justifyContent: 'space-around', alignItems: 'center', alignSelf: 'center', backgroundColor:'transparent', }, }); module.exports = Carousel;
mit
odaper/angular2-sample-taskmanager
src/app/app.module.ts
1367
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; import { AppRoutingModule } from './app.routing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MaterialComponentsModule } from './material-components/material-components.module'; import { MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule, MdSidenavModule, MdIconModule } from '@angular/material'; import { ComponentsModule } from './core/view/components/components.module'; import { PagesModule } from './business/pages/pages.module'; import 'hammerjs'; import { MyThemeModule } from './themes/my-theme/my-theme.module'; @NgModule({ declarations: [ AppComponent, LoginComponent, HomeComponent, ], imports: [ BrowserModule, AppRoutingModule, MaterialComponentsModule, BrowserAnimationsModule, MdButtonModule, MdCheckboxModule, MdInputModule, MdCardModule, MdSidenavModule, MdIconModule, ComponentsModule, PagesModule, MyThemeModule ], providers: [], bootstrap: [AppComponent], exports: [] }) export class AppModule { }
mit
kmhasan-class/summer2016dslab
Linked List/linkedlist.cpp
1102
#include "linkedlist.h" #include <cstdlib> LinkedList::LinkedList() { head = NULL; } void LinkedList::insertAtFront(int data) { Node *n = new Node(data); n->next = head; head = n; } int LinkedList::removeFromFront() { int data = head->data; Node* t = head; head = head->next; delete t; return data; } bool LinkedList::isEmpty() { if (head == NULL) return true; else return false; } void LinkedList::print() { for (Node* n = head; n != NULL; n = n->next) n->print(); } Node* LinkedList::searchInList(int key) { Node* address = NULL; for (Node* n = head; n != NULL; n = n->next) if (n->data == key) { address = n; // you can break/return from here // if you want to return the first place where you found the key } return address; } void LinkedList::insertAtBack(int data) { Node *z = new Node(data); Node *n; if (head == NULL) { head = z; } else { for (n = head; n->next != NULL; n = n->next) ; n->next = z; } }
mit
jmfeurprier/perf
lib/perf/Persistence/Operation/OperatorFactory.php
3997
<?php namespace perf\Persistence\Operation; use \perf\Persistence\EntityMetadataPool; use \perf\Db\ConnectionPool; /** * * * @package perf */ class OperatorFactory { /** * Entity metadata pool. * * @var EntityMetadataPool */ private $entityMetadataPool; /** * Connection pool. * * @var ConnectionPool */ private $connectionPool; /** * Entity importer. * * @var EntityImporter */ private $entityImporter; /** * Entity exporter. * * @var EntityExporter */ private $entityExporter; /** * * * @param EntityMetadataPool $pool * @return void */ public function setEntityMetadataPool(EntityMetadataPool $pool) { $this->entityMetadataPool = $pool; } /** * * * @param ConnectionPool $connectionPool * @return void */ public function setConnectionPool(ConnectionPool $pool) { $this->connectionPool = $pool; } /** * * * @param EntityImporter $importer * @return void */ public function setEntityImporter(EntityImporter $importer) { $this->entityImporter = $importer; } /** * * * @param EntityExporter $exporter * @return void */ public function setEntityExporter(EntityExporter $exporter) { $this->entityExporter = $exporter; } /** * * * @return Inserter */ public function getInserter() { static $inserter; if (!$inserter) { $inserter = new Inserter(); $inserter->setEntityMetadataPool($this->entityMetadataPool); $inserter->setConnectionPool($this->connectionPool); $inserter->setEntityExporter($this->getEntityExporter()); } return $inserter; } /** * * * @return Updater */ public function getUpdater() { static $updater; if (!$updater) { $updater = new Updater(); $updater->setEntityMetadataPool($this->entityMetadataPool); $updater->setConnectionPool($this->connectionPool); $updater->setEntityExporter($this->getEntityExporter()); } return $updater; } /** * * * @return EntityExporter */ private function getEntityExporter() { if (!$this->entityExporter) { $this->setEntityExporter(new EntityExporter()); } return $this->entityExporter; } /** * * * @return Deleter */ public function getDeleter() { static $deleter; if (!$deleter) { $deleter = new Deleter(); $deleter->setEntityMetadataPool($this->entityMetadataPool); $deleter->setConnectionPool($this->connectionPool); } return $deleter; } /** * * * @return Selecter */ public function getSelecter() { static $selecter; if (!$selecter) { $selecter = new Selecter(); $selecter->setEntityMetadataPool($this->entityMetadataPool); $selecter->setConnectionPool($this->connectionPool); $selecter->setEntityImporter($this->getEntityImporter()); } return $selecter; } /** * * * @return EntityImporter */ private function getEntityImporter() { if (!$this->entityImporter) { $this->setEntityImporter(new EntityImporter()); } return $this->entityImporter; } /** * * * @return Counter */ public function getCounter() { static $counter; if (!$counter) { $counter = new Counter(); $counter->setEntityMetadataPool($this->entityMetadataPool); $counter->setConnectionPool($this->connectionPool); } return $counter; } }
mit
JosePedroMatos/Tethys
tethys/__init__.py
198
from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa
mit
Patrick-Batenburg/Library_DummyData
Solution/src/main/java/library/domain/Member.java
7192
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package library.domain; import java.util.ArrayList; /** * * @author ppthgast */ public class Member { private int memberID; private String firstName; private String lastName; private String street; private String houseNumber; private String city; private String phoneNumber; private String emailAddress; private double fine; private ArrayList<Loan> loans; private ArrayList<Reservation> reservations; public Member(int memberID, String firstName, String lastName, String street, String houseNumber, String city, String phoneNumber, String emailAddress, double fine) { this.memberID = memberID; this.firstName = firstName; this.lastName = lastName; this.street = street; this.houseNumber = houseNumber; this.city = city; this.phoneNumber = phoneNumber; this.emailAddress = emailAddress; this.fine = fine; loans = new ArrayList(); reservations = new ArrayList(); } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getemailAddress() { return emailAddress; } public void setemailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getHouseNumber() { return houseNumber; } public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public double getFine() { return fine; } public void setFine(double fine) { this.fine = fine; } public void setLoans(Loan[] loans) { removeAllLoans(); for(Loan theLoan: loans) { addLoan(theLoan); } } public void addLoan(Loan newLoan) { loans.add(newLoan); } public void removeAllLoans() { loans.clear(); } public void addReservation(Reservation newReservation) { reservations.add(newReservation); } public boolean remove() { // Result is always true. If we later on use a database from which // the member needs to be removed as well, we can return a more // meaningfull value. boolean result = true; removeAllReservations(); return result; } private void removeAllReservations() { int index = reservations.size() - 1; while(index >= 0) { Reservation reservation = reservations.get(index); reservation.remove(); index--; } // Alternatives for this construction with the temporary copy of the // ArrayList field are for example: // // -- 1 -- // Start removing the reservations starting from the END OF the list // moving backwards until the list is empty. Starting from the first // element towards the end of the list will not succeed since the // index values are messed up. // int index = reservations.size() - 1; // // while(index >= 0) // { // reservations.r // Reservation reservation = reservations.get(index); // reservation.remove(); // // index--; // } // // -- 2 -- // // ArrayList<Reservation> tempList = new ArrayList<>(reservations); // // for(Reservation r: reservations) // { // r.remove(); // } // // This defenitely needs clarification. Using a for each or iterator // on a list, has the limitation that deletion of elements from that // list is not allowed. Therefore a new ArrayList object is created, // referring to the same Reservation objects as the reservations field. // The local variable tempList is not modified during execution of the // loop. The reservations field on the other hand is. } public boolean hasLoans() { return !loans.isEmpty(); } public boolean hasFine() { return fine > 0; } public boolean isRemovable() { return !hasLoans() && !hasFine(); } public void removeReservation(Reservation reservation) { reservations.remove(reservation); } @Override public boolean equals(Object o) { boolean equal = false; if(o == this) { // Equal instances of this class. equal = true; } else { if(o instanceof Member) { Member l = (Member)o; // Member is identified by memberID; checking on this attribute only will suffice. equal = this.memberID == l.memberID; } } return equal; } @Override public int hashCode() { // This implementation is based on the best practice as described in Effective Java, // 2nd edition, Joshua Bloch. // memberID is unique, so sufficient to be used as hashcode. return memberID; } public String toString() { String result = "========== lid info ==========\n" + memberID + " - " + firstName + " " + lastName + "\n" + "Boete: " + "\u20ac" + fine + "\n\n"; result += "========== leningen ==========\n"; if(loans.isEmpty()) { result += "Geen leningen"; } else { for (Loan loan : loans) { result += loan + "\n\n"; } } result += "\n\n"; result += "========== reserveringen ==========\n"; if(reservations.isEmpty()) { result += "Geen reserveringen"; } else { for (Reservation reservation : reservations) { result += reservation + "\n\n"; } } return result; } }
mit
JesusisFreedom/generator-ng-webpack
app/index.js
1782
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var NgComponentGenerator = yeoman.generators.Base.extend({ initializing: function () { if (!this.options['skip-message']) { console.log(chalk.magenta('You\'re using the fantastic NgWebpack generator.\n')); console.log(chalk.magenta('Initializing yo-rc.json configuration.\n')); } }, configuring: function () { var config = { 'routeDirectory': this.options.routeDirectory || 'app/components/', 'directiveDirectory': this.options.directiveDirectory || 'app/components/', 'filterDirectory': this.options.filterDirectory || 'app/components/', 'serviceDirectory': this.options.serviceDirectory || 'app/components/', 'basePath': this.options.basePath || 'app', 'moduleName': this.options.moduleName || '', 'filters': this.options.filters || ['uirouter', 'jasmine'], 'extensions': this.options.extensions || ['js', 'html', 'scss'], 'directiveSimpleTemplates': this.options.directiveSimple || '', 'directiveComplexTemplates': this.options.directiveComplex || '', 'filterTemplates': this.options.filter || '', 'serviceTemplates': this.options.service || '', 'factoryTemplates': this.options.factory || '', 'controllerTemplates': this.options.controller || '', 'decoratorTemplates': this.options.decorator || '', 'providerTemplates': this.options.provider || '', 'routeTemplates': this.options.route || '' }; if (this.options.forceConfig) { this.config.set(config); this.config.forceSave(); } else { this.config.defaults(config); } } }); module.exports = NgComponentGenerator;
mit
mbl-cli/DspaceTools
spec/app/models_spec.rb
5079
require_relative '../spec_helper' describe ApiKey do it 'should instantiate' do ak = ApiKey.where(eperson_id: 1).first ak.class.should == ApiKey end it 'should be able to have more than one api key per eperson' do aks = ApiKey.where(eperson_id: 1) aks.size.should > 1 aks = ApiKey.where(eperson_id: 2) aks.size.should == 1 end it 'should be able to get digest as a class and instance methods' do ApiKey.digest('onetwo', 'abcdef').should == '805d5daf' ApiKey.where(eperson_id: 1)[1].digest('onetwo').should == '805d5daf' end it 'should generate public key' do key = ApiKey.get_public_key key.match(/[\h]{8}/).should_not be_nil end it 'should generate private key' do key = ApiKey.get_private_key key.match(/[\h]{16}/).should_not be_nil end end describe Eperson do it 'should instantiate' do e = Eperson.where(email: 'jdoe@example.com').first e.class.should == Eperson e.firstname.should == 'John' e.api_keys.size.should > 1 e.groups.size.should > 0 Eperson.resource_number.should == 7 end it 'should have admin method' do e = Eperson.where(email: 'jdoe@example.com').first e.admin?.should == false e = Eperson.where(email: 'admin@example.com').first e.admin?.should be_true end end describe Group do it 'should have find method' do g = Group.first Group.find(g.eperson_group_id).should == g end it 'should have epsersons connected' do g = Group.first g.epersons[0].class.should == Eperson g.epersons.size.should > 0 end end describe Handle do it 'should not have a resource number' do Handle.resource_number.should be_nil end it 'should instantiate' do h = Handle.where(handle: '123/123').first h.class.should == Handle h.resource_type.should == Item h.resource.should == Item.find(1) h.path.should == '/rest/items/1' end it 'should modify path' do h = Handle.where(handle: '123/123').first original_fullpath = 'http://example.org/rest/handle.xml' + '?handle=http://hdl.handle.net/123/123' + '&api_key=jdoe_again&api_digest=8a5dabc2' original_path = '/rest/handle.xml' new_path = h.fullpath(original_fullpath, original_path) new_path.should == 'http://example.org/rest/items/1.xml' + '?handle=http://hdl.handle.net/123/123' + '&api_key=jdoe_again&api_digest=bf0f9de3' original_fullpath = 'http://example.org/rest/handle.xml' + '?handle=http://hdl.handle.net/123/123&api_key=jdoe_again' + '&api_digest=8a5dabc2&some_param=2' original_path = '/rest/handle.xml' new_path = h.fullpath(original_fullpath, original_path) new_path.should == 'http://example.org/rest/items/1.xml' + '?handle=http://hdl.handle.net/123/123&api_key=jdoe_again' + '&api_digest=bf0f9de3&some_param=2' end end describe Bitstream do it 'should have 0 resource number' do Bitstream.resource_number.should == 0 end it 'should have find method' do b = Bitstream.first Bitstream.find(b.bitstream_id).should == b end it 'should have path' do b = Bitstream.first b.path.match(%r|^/tmp/\d\d/\d\d/\d\d/[\d]*$|).should be_true end it 'should have mime type' do b = Bitstream.first b.mime.should == 'application/octet-stream' end end describe BitstreamFormat do it 'should not have resource number' do BitstreamFormat.resource_number.should be_nil end it 'should find it' do bf = BitstreamFormat.first BitstreamFormat.find(bf.bitstream_format_id).should == bf end end describe Collection do it 'should have find method' do c = Collection.first Collection.find(c.collection_id).should == c end end describe Community do it 'should have find method' do c = Community.first Community.find(c.community_id).should == c end end describe CommunityItem do it 'should connect items and communities' do Community.find(6).items.size.should > 1 item = Community.find(6).items[0] item.class.should == Item item.communities.size.should > 0 end end describe Item do it 'should have find method' do item = Item.first Item.find(item.item_id).should == item end it 'should find updates without timestamps or group' do Item.updates(nil).size.should > 1000 Item.updates('bad_ts').size.should == 0 end it 'should find updates with timestamp without group' do ts = Item.all[-5].last_modified Item.updates(ts).size.should == 4 end it 'should not break with a wrong group' do ts = Item.all[-5].last_modified Item.updates(ts, 'huh').size.should == 0 end it 'should return updates for a group' do ts = Item.all[-5].last_modified Item.updates(ts, 4).size.should == 3 end end describe Resourcepolicy do it 'should have action, group, or epserson' do r = Resourcepolicy.first r.action.should == 'READ' r.group.class.should == AnonymousGroup r.eperson.should be_nil r = Resourcepolicy.find(2) r.eperson.class.should == Eperson end end
mit
masche842/alchemy_nodes
spec/dummy/db/migrate/20120323095940_change_open_link_in_new_window_to_link_target.alchemy.rb
1002
# This migration comes from alchemy (originally 20110711142057) class ChangeOpenLinkInNewWindowToLinkTarget < ActiveRecord::Migration def self.up change_column :essence_pictures, :open_link_in_new_window, :string change_column :essence_texts, :open_link_in_new_window, :string rename_column :essence_pictures, :open_link_in_new_window, :link_target rename_column :essence_texts, :open_link_in_new_window, :link_target change_column_default :essence_pictures, :link_target, nil change_column_default :essence_texts, :link_target, nil end def self.down change_column_default :essence_texts, :link_target, 0 change_column_default :essence_pictures, :link_target, 0 rename_column :essence_texts, :link_target, :open_link_in_new_window rename_column :essence_pictures, :link_target, :open_link_in_new_window change_column :essence_texts, :open_link_in_new_window, :boolean change_column :essence_pictures, :open_link_in_new_window, :boolean end end
mit
EffectHub/effecthub
application/controllers/author.php
7829
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Author extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->helper('url'); if($this->session->userdata('language')) { $lang = $this->session->userdata('language'); } else { $language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); if (preg_match("/zh-c/i", $language)||$language=='cn'){ $lang = 2; } else { $lang = 1; } } if ($lang==2) { $this->lang->load('header','chinese'); $this->lang->load('footer','chinese'); $this->lang->load('user','chinese'); }else{ $this->lang->load('header','english'); $this->lang->load('footer','english'); $this->lang->load('user','english'); } } public function index() { $this->load->model('item_model'); $this->load->model('user_model'); $data['user_list'] = $this->user_model->order_popular_author(); $data['new_user_list'] = $this->user_model->order_new_author(); //$res= $this->user_model->find_allusers(); $user_count = $this->user_model->count_users(); $data['user_count'] = $user_count; $this->load->library('pagination');//加载分页类 $config['base_url'] = base_url().'author/index';//设置分页的url路径 $config['total_rows'] = $user_count;//得到数据库中的记录的总条数 $config['uri_segment']=3; $config['per_page'] = '20';//每页记录数 $config['first_link'] = 'First'; $config['last_link'] = 'Last'; $config['full_tag_open'] = '<p>'; $config['full_tag_close'] = '</p>'; $this->pagination->initialize($config);//分页的初始化 $data['author_list']= $this->user_model->find_users(array('active'=>1),$config['per_page'],$this->uri->segment(3));//得到数据库记录 $data['nav']= 'explore'; $data['feature']= 'author'; //$data['author_list'] =$this->user_model->find_users(array(), 100, 0); $data['item_list_everyauthor'] = array(); foreach ($data['author_list'] as $v1) { $data['item_list_'.$v1['id']] = $this->item_model->find_item_by_authorid($v1['id']); $data['item_list_everyauthor'][$v1['id']] = $data['item_list_'.$v1['id']]; } $this->load->view('user/author_list',$data); } function authorSearch($key=null) { /*$this->load->model('item_model'); $data['item_list'] = $this->item_model->find_items(array(), 100, 0); $this->load->model('item_type_model'); $data['item_type_list'] = $this->item_type_model->find_item_types(array(), 100, 0); $taglist = Array(); foreach($data['item_list'] as $item){ $tok = strtok($item['tags']," ,"); while($tok !== false){ if(!in_array($tok,$taglist)){ if($tok!='') array_push($taglist,$tok); } $tok = strtok(" ,"); } } $data['tags'] = $this->user_model->order_popular_tag($taglist);*/ $data['nav']= 'explore'; $data['feature']= 'author'; $this->load->model('user_model'); $data['user_list'] = $this->user_model->order_popular_author(); $data['new_user_list'] = $this->user_model->order_new_author(); //$res= $this->user_model->find_allusers(); $user_count = $this->user_model->count_users(); $data['user_count'] = $user_count; $input_str = $this->input->post('search'); if(!$input_str)$input_str = $key; else $key = $input_str; $res =$this->user_model->find_user_by_name($input_str); $this->load->model('item_model'); $this->load->library('pagination');//加载分页类 $config['base_url'] = base_url().'index.php/author/authorSearch/'.$key;//设置分页的url路径 $config['total_rows'] = count($res);//得到数据库中的记录的总条数 $config['per_page'] = '20';//每页记录数 $config['uri_segment']=4; $config['first_link'] = 'First'; $config['last_link'] = 'Last'; $config['full_tag_open'] = '<p>'; $config['full_tag_close'] = '</p>'; $this->pagination->initialize($config);//分页的初始化 $data['author_list']= $this->user_model->find_user_by_name_offset($input_str,$config['per_page'],$this->uri->segment(4));//得到数据库记录 $data['item_list_everyauthor'] = array(); foreach ($data['author_list'] as $v1) { $data['item_list_'.$v1['id']] = $this->item_model->find_item_by_authorid($v1['id']); $data['item_list_everyauthor'][$v1['id']] = $data['item_list_'.$v1['id']]; } $data['input_str'] = $input_str; $this->load->view('user/author_list',$data); } function countrySearch($countrycode) { $this->load->model('item_model'); $this->load->model('user_model'); $data['user_list'] = $this->user_model->order_popular_author(); $data['new_user_list'] = $this->user_model->order_new_author(); //$res= $this->user_model->find_allusers(); $user_count = $this->user_model->count_users(); $data['user_count'] = $user_count; $data['nav']= 'explore'; $data['feature']= 'author'; $res =$this->user_model->find_user_by_country($countrycode); $this->load->library('pagination');//加载分页类 $config['base_url'] = base_url().'index.php/author/countrySearch/'.$countrycode;//设置分页的url路径 $config['total_rows'] = count($res);//得到数据库中的记录的总条数 $config['per_page'] = '20';//每页记录数 $config['first_link'] = 'First'; $config['uri_segment']=4; $config['last_link'] = 'Last'; $config['full_tag_open'] = '<p>'; $config['full_tag_close'] = '</p>'; $this->pagination->initialize($config);//分页的初始化 $data['author_list']= $this->user_model->find_user_by_country_offset($countrycode,$config['per_page'],$this->uri->segment(4));//得到数据库记录 $data['item_list_everyauthor'] = array(); foreach ($data['author_list'] as $v1) { $data['item_list_'.$v1['id']] = $this->item_model->find_item_by_authorid($v1['id']); $data['item_list_everyauthor'][$v1['id']] = $data['item_list_'.$v1['id']]; } $this->load->view('user/author_list',$data); } function levelSearch($level) { $this->load->model('item_model'); $this->load->model('user_model'); $data['user_list'] = $this->user_model->order_popular_author(); $data['new_user_list'] = $this->user_model->order_new_author(); //$res= $this->user_model->find_allusers(); $user_count = $this->user_model->count_users(); $data['user_count'] = $user_count; $data['nav']= 'explore'; $data['feature']= 'author'; $res =$this->user_model->find_user_by_level($level); $this->load->library('pagination');//加载分页类 $config['base_url'] = base_url().'index.php/author/levelSearch/'.$level;//设置分页的url路径 $config['total_rows'] = count($res);//得到数据库中的记录的总条数 $config['per_page'] = '20';//每页记录数 $config['first_link'] = 'First'; $config['uri_segment']=4; $config['last_link'] = 'Last'; $config['full_tag_open'] = '<p>'; $config['full_tag_close'] = '</p>'; $this->pagination->initialize($config);//分页的初始化 $data['author_list']= $this->user_model->find_user_by_level_offset($level,$config['per_page'],$this->uri->segment(4));//得到数据库记录 $data['item_list_everyauthor'] = array(); foreach ($data['author_list'] as $v1) { $data['item_list_'.$v1['id']] = $this->item_model->find_item_by_authorid($v1['id']); $data['item_list_everyauthor'][$v1['id']] = $data['item_list_'.$v1['id']]; } $this->load->view('user/author_list',$data); } }
mit
Imms/imms.github.io
jspm_packages/npm/react@15.3.0/lib/ReactElementValidator.js
5595
/* */ (function(process) { 'use strict'; var ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactComponentTreeDevtool = require('./ReactComponentTreeDevtool'); var ReactElement = require('./ReactElement'); var ReactPropTypeLocations = require('./ReactPropTypeLocations'); var checkReactTypeSpec = require('./checkReactTypeSpec'); var canDefineProperty = require('./canDefineProperty'); var getIteratorFn = require('./getIteratorFn'); var warning = require('fbjs/lib/warning'); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeDevtool.getCurrentStackAddendum(element)) : void 0; } function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, ReactPropTypeLocations.prop, name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function(type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; process.env.NODE_ENV !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : void 0; var element = ReactElement.createElement.apply(this, arguments); if (element == null) { return element; } if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function(type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function() { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', {value: type}); return type; } }); } } return validatedFactory; }, cloneElement: function(element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; })(require('process'));
mit
js-fns/date-fns
src/locale/mk/index.d.ts
146
// This file is generated automatically by `scripts/build/typings.js`. Please, don't change it. import { mk } from 'date-fns/locale' export = mk
mit
jumbowhales/Pokemon-Showdown
server/chat-commands/room-settings.ts
53756
/** * Room settings commands * Pokemon Showdown - http://pokemonshowdown.com/ * * Commands for settings relating to room setting filtering. * * @license MIT */ 'use strict'; const RANKS: string[] = Config.groupsranking; const SLOWCHAT_MINIMUM = 2; const SLOWCHAT_MAXIMUM = 60; const SLOWCHAT_USER_REQUIREMENT = 10; const MAX_CHATROOM_ID_LENGTH = 225; export const commands: ChatCommands = { roomsetting: 'roomsettings', roomsettings(target, room, user, connection) { if (room.battle) return this.errorReply("This command cannot be used in battle rooms."); let uhtml = 'uhtml'; if (!target) { room.update(); } else { this.parse(`/${target}`); uhtml = 'uhtmlchange'; } let output = Chat.html`<div class="infobox">Room Settings for ${room.title}<br />`; for (const handler of Chat.roomSettings) { const setting = handler(room, user, connection); if (typeof setting.permission === 'string') setting.permission = user.can(setting.permission, null, room); output += `<strong>${setting.label}:</strong> <br />`; for (const option of setting.options) { // disabled button if (option[1] === true) { output += Chat.html`<button class="button disabled" style="font-weight:bold; color:#575757; font-weight:bold; background-color:#d3d3d3;">${option[0]}</button> `; } else { // only show proper buttons if we have the permissions to use them if (!setting.permission) continue; output += Chat.html`<button class="button" name="send" value="/roomsetting ${option[1]}">${option[0]}</button> `; } } output += `<br />`; } output += '</div>'; user.sendTo(room, `|${uhtml}|roomsettings|${output}`); }, roomsettingshelp: [`/roomsettings - Shows current room settings with buttons to change them (if you can).`], modchat(target, room, user) { if (!target) { const modchatSetting = (room.modchat || "OFF"); return this.sendReply(`Moderated chat is currently set to: ${modchatSetting}`); } if (!this.can('modchat', null, room)) return false; // 'modchat' lets you set up to 1 (ac/trusted also allowed) // 'modchatall' lets you set up to your current rank // 'makeroom' lets you set any rank, no limit const threshold = user.can('makeroom') ? Infinity : user.can('modchatall', null, room) ? Config.groupsranking.indexOf(room.getAuth(user)) : 1; if (room.modchat && room.modchat.length <= 1 && Config.groupsranking.indexOf(room.modchat) > threshold) { return this.errorReply(`/modchat - Access denied for changing a setting higher than ${Config.groupsranking[threshold]}.`); } if (!!(room as GameRoom).requestModchat) { const error = (room as GameRoom).requestModchat(user); if (error) return this.errorReply(error); } target = target.toLowerCase().trim(); const currentModchat = room.modchat; switch (target) { case 'off': case 'false': case 'no': case 'disable': room.modchat = null; break; case 'ac': case 'autoconfirmed': room.modchat = 'autoconfirmed'; break; case 'trusted': room.modchat = 'trusted'; break; case 'player': target = Users.PLAYER_SYMBOL; /* falls through */ default: if (!Config.groups[target]) { this.errorReply(`The rank '${target}' was unrecognized as a modchat level.`); return this.parse('/help modchat'); } if (Config.groupsranking.indexOf(target) > threshold) { return this.errorReply(`/modchat - Access denied for setting higher than ${Config.groupsranking[threshold]}.`); } room.modchat = target; break; } if (currentModchat === room.modchat) { return this.errorReply(`Modchat is already set to ${currentModchat || 'off'}.`); } if (!room.modchat) { this.add("|raw|<div class=\"broadcast-blue\"><strong>Moderated chat was disabled!</strong><br />Anyone may talk now.</div>"); } else { const modchatSetting = Chat.escapeHTML(room.modchat); this.add(`|raw|<div class="broadcast-red"><strong>Moderated chat was set to ${modchatSetting}!</strong><br />Only users of rank ${modchatSetting} and higher can talk.</div>`); } if ((room as GameRoom).requestModchat && !room.modchat) (room as GameRoom).requestModchat(null); this.privateModAction(`(${user.name} set modchat to ${room.modchat || "off"})`); this.modlog('MODCHAT', null, `to ${room.modchat || "false"}`); if (room.chatRoomData) { room.chatRoomData.modchat = room.modchat; Rooms.global.writeChatRoomData(); } }, modchathelp: [`/modchat [off/autoconfirmed/+/%/@/*/player/#/&/~] - Set the level of moderated chat. Requires: * @ \u2606 for off/autoconfirmed/+ options, # & ~ for all the options`], ioo(target, room, user) { return this.parse('/modjoin %'); }, '!ionext': true, inviteonlynext: 'ionext', ionext(target, room, user) { const groupConfig = Config.groups[Users.PLAYER_SYMBOL]; if (!(groupConfig && groupConfig.editprivacy)) return this.errorReply(`/ionext - Access denied.`); if (this.meansNo(target)) { user.inviteOnlyNextBattle = false; user.update('inviteOnlyNextBattle'); this.sendReply("Your next battle will be publicly visible."); } else { user.inviteOnlyNextBattle = true; user.update('inviteOnlyNextBattle'); if (user.forcedPublic) return this.errorReply(`Your next battle will be invite-only provided it is not rated, otherwise your '${user.forcedPublic}' prefix will force the battle to be public.`); this.sendReply("Your next battle will be invite-only."); } }, ionexthelp: [ `/ionext - Sets your next battle to be invite-only.`, `/ionext off - Sets your next battle to be publicly visible.`, ], inviteonly(target, room, user) { if (!target) return this.parse('/help inviteonly'); if (this.meansYes(target)) { return this.parse("/modjoin %"); } else { return this.parse(`/modjoin ${target}`); } }, inviteonlyhelp: [ `/inviteonly [on|off] - Sets modjoin %. Users can't join unless invited with /invite. Requires: # & ~`, `/ioo - Shortcut for /inviteonly on`, `/inviteonlynext OR /ionext - Sets your next battle to be invite-only.`, `/ionext off - Sets your next battle to be publicly visible.`, ], modjoin(target, room, user) { if (!target) { const modjoinSetting = room.modjoin === true ? "SYNC" : room.modjoin || "OFF"; return this.sendReply(`Modjoin is currently set to: ${modjoinSetting}`); } if (room.isPersonal) { if (!this.can('editroom', null, room)) return; } else if (room.battle) { if (!this.can('editprivacy', null, room)) return; const prefix = room.battle.forcedPublic(); if (prefix && !user.can('editprivacy')) return this.errorReply(`This battle is required to be public due to a player having a name prefixed by '${prefix}'.`); } else { if (!this.can('makeroom')) return; } if (room.tour && !room.tour.modjoin) return this.errorReply(`You can't do this in tournaments where modjoin is prohibited.`); if (target === 'player') target = Users.PLAYER_SYMBOL; if (this.meansNo(target)) { if (!room.modjoin) return this.errorReply(`Modjoin is already turned off in this room.`); room.modjoin = null; this.add(`|raw|<div class="broadcast-blue"><strong>This room is no longer invite only!</strong><br />Anyone may now join.</div>`); this.addModAction(`${user.name} turned off modjoin.`); this.modlog('MODJOIN', null, 'OFF'); if (room.chatRoomData) { room.chatRoomData.modjoin = null; Rooms.global.writeChatRoomData(); } return; } else if (target === 'sync') { if (room.modjoin === true) return this.errorReply(`Modjoin is already set to sync modchat in this room.`); room.modjoin = true; this.add(`|raw|<div class="broadcast-red"><strong>Moderated join is set to sync with modchat!</strong><br />Only users who can speak in modchat can join.</div>`); this.addModAction(`${user.name} set modjoin to sync with modchat.`); this.modlog('MODJOIN SYNC'); } else if (target === 'ac' || target === 'autoconfirmed') { if (room.modjoin === 'autoconfirmed') return this.errorReply(`Modjoin is already set to autoconfirmed.`); room.modjoin = 'autoconfirmed'; this.add(`|raw|<div class="broadcast-red"><strong>Moderated join is set to autoconfirmed!</strong><br />Users must be rank autoconfirmed or invited with <code>/invite</code> to join</div>`); this.addModAction(`${user.name} set modjoin to autoconfirmed.`); this.modlog('MODJOIN', null, 'autoconfirmed'); } else if (target in Config.groups || target === 'trusted') { if (room.battle && !user.can('makeroom') && !'+%'.includes(target)) { return this.errorReply(`/modjoin - Access denied from setting modjoin past % in battles.`); } if (room.isPersonal && !user.can('makeroom') && !'+%'.includes(target)) { return this.errorReply(`/modjoin - Access denied from setting modjoin past % in group chats.`); } if (room.modjoin === target) return this.errorReply(`Modjoin is already set to ${target} in this room.`); room.modjoin = target; this.add(`|raw|<div class="broadcast-red"><strong>This room is now invite only!</strong><br />Users must be rank ${target} or invited with <code>/invite</code> to join</div>`); this.addModAction(`${user.name} set modjoin to ${target}.`); this.modlog('MODJOIN', null, target); } else { this.errorReply(`Unrecognized modjoin setting.`); this.parse('/help modjoin'); return false; } if (room.chatRoomData) { room.chatRoomData.modjoin = room.modjoin; Rooms.global.writeChatRoomData(); } if (target === 'sync' && !room.modchat) this.parse(`/modchat ${Config.groupsranking[1]}`); if (!room.isPrivate) this.parse('/hiddenroom'); }, modjoinhelp: [ `/modjoin [+|%|@|*|player|&|~|#|off] - Sets modjoin. Users lower than the specified rank can't join this room unless they have a room rank. Requires: \u2606 # & ~`, `/modjoin [sync|off] - Sets modjoin. Only users who can speak in modchat can join this room. Requires: \u2606 # & ~`, ], roomlanguage(target, room, user) { if (!target) { return this.sendReply(`This room's primary language is ${Chat.languages.get(room.language || '') || 'English'}`); } if (!this.can('editroom', null, room)) return false; const targetLanguage = toID(target); if (!Chat.languages.has(targetLanguage)) return this.errorReply(`"${target}" is not a supported language.`); room.language = targetLanguage === 'english' ? false : targetLanguage; if (room.chatRoomData) { room.chatRoomData.language = room.language; Rooms.global.writeChatRoomData(); } this.modlog(`LANGUAGE`, null, Chat.languages.get(targetLanguage)); this.sendReply(`The room's language has been set to ${Chat.languages.get(targetLanguage)}`); }, roomlanguagehelp: [ `/roomlanguage [language] - Sets the the language for the room, which changes language of a few commands. Requires # & ~`, `Supported Languages: English, Spanish, Italian, French, Simplified Chinese, Traditional Chinese, Japanese, Hindi, Turkish, Dutch, German.`, ], slowchat(target, room, user) { if (!target) { const slowchatSetting = (room.slowchat || "OFF"); return this.sendReply(`Slow chat is currently set to: ${slowchatSetting}`); } if (!this.canTalk()) return; if (!this.can('modchat', null, room)) return false; let targetInt = parseInt(target); if (this.meansNo(target)) { if (!room.slowchat) return this.errorReply(`Slow chat is already disabled in this room.`); room.slowchat = false; } else if (targetInt) { if (!user.can('bypassall') && room.userCount < SLOWCHAT_USER_REQUIREMENT) return this.errorReply(`This room must have at least ${SLOWCHAT_USER_REQUIREMENT} users to set slowchat; it only has ${room.userCount} right now.`); if (room.slowchat === targetInt) return this.errorReply(`Slow chat is already set to ${room.slowchat} seconds in this room.`); if (targetInt < SLOWCHAT_MINIMUM) targetInt = SLOWCHAT_MINIMUM; if (targetInt > SLOWCHAT_MAXIMUM) targetInt = SLOWCHAT_MAXIMUM; room.slowchat = targetInt; } else { return this.parse("/help slowchat"); } const slowchatSetting = (room.slowchat || "OFF"); this.privateModAction(`(${user.name} set slowchat to ${slowchatSetting})`); this.modlog('SLOWCHAT', null, '' + slowchatSetting); if (room.chatRoomData) { room.chatRoomData.slowchat = room.slowchat; Rooms.global.writeChatRoomData(); } }, slowchathelp: [ `/slowchat [number] - Sets a limit on how often users in the room can send messages, between 2 and 60 seconds. Requires @ # & ~`, `/slowchat off - Disables slowchat in the room. Requires @ # & ~`, ], stretching: 'stretchfilter', stretchingfilter: 'stretchfilter', stretchfilter(target, room, user) { if (!target) { const stretchSetting = (room.filterStretching ? "ON" : "OFF"); return this.sendReply(`This room's stretch filter is currently: ${stretchSetting}`); } if (!this.canTalk()) return; if (!this.can('editroom', null, room)) return false; if (this.meansYes(target)) { if (room.filterStretching) return this.errorReply(`This room's stretch filter is already ON`); room.filterStretching = true; } else if (this.meansNo(target)) { if (!room.filterStretching) return this.errorReply(`This room's stretch filter is already OFF`); room.filterStretching = false; } else { return this.parse("/help stretchfilter"); } const stretchSetting = (room.filterStretching ? "ON" : "OFF"); this.privateModAction(`(${user.name} turned the stretch filter ${stretchSetting})`); this.modlog('STRETCH FILTER', null, stretchSetting); if (room.chatRoomData) { room.chatRoomData.filterStretching = room.filterStretching; Rooms.global.writeChatRoomData(); } }, stretchfilterhelp: [`/stretchfilter [on/off] - Toggles filtering messages in the room for stretchingggggggg. Requires # & ~`], capitals: 'capsfilter', capitalsfilter: 'capsfilter', capsfilter(target, room, user) { if (!target) { const capsSetting = (room.filterCaps ? "ON" : "OFF"); return this.sendReply(`This room's caps filter is currently: ${capsSetting}`); } if (!this.canTalk()) return; if (!this.can('editroom', null, room)) return false; if (this.meansYes(target)) { if (room.filterCaps) return this.errorReply(`This room's caps filter is already ON`); room.filterCaps = true; } else if (this.meansNo(target)) { if (!room.filterCaps) return this.errorReply(`This room's caps filter is already OFF`); room.filterCaps = false; } else { return this.parse("/help capsfilter"); } const capsSetting = (room.filterCaps ? "ON" : "OFF"); this.privateModAction(`(${user.name} turned the caps filter ${capsSetting})`); this.modlog('CAPS FILTER', null, capsSetting); if (room.chatRoomData) { room.chatRoomData.filterCaps = room.filterCaps; Rooms.global.writeChatRoomData(); } }, capsfilterhelp: [`/capsfilter [on/off] - Toggles filtering messages in the room for EXCESSIVE CAPS. Requires # & ~`], emojis: 'emojifilter', emoji: 'emojifilter', emojifilter(target, room, user) { if (!target) { const emojiSetting = (room.filterEmojis ? "ON" : "OFF"); return this.sendReply(`This room's emoji filter is currently: ${emojiSetting}`); } if (!this.canTalk()) return; if (!this.can('editroom', null, room)) return false; if (this.meansYes(target)) { if (room.filterEmojis) return this.errorReply(`This room's emoji filter is already ON`); room.filterEmojis = true; } else if (this.meansNo(target)) { if (!room.filterEmojis) return this.errorReply(`This room's emoji filter is already OFF`); room.filterEmojis = false; } else { return this.parse("/help emojifilter"); } const emojiSetting = (room.filterEmojis ? "ON" : "OFF"); this.privateModAction(`(${user.name} turned the emoji filter ${emojiSetting})`); this.modlog('EMOJI FILTER', null, emojiSetting); if (room.chatRoomData) { room.chatRoomData.filterEmojis = room.filterEmojis; Rooms.global.writeChatRoomData(); } }, emojifilterhelp: [`/emojifilter [on/off] - Toggles filtering messages in the room for emojis. Requires # & ~`], banwords: 'banword', banword: { regexadd: 'add', addregex: 'add', add(target, room, user, connection, cmd) { if (!target || target === ' ') return this.parse('/help banword'); if (!this.can('declare', null, room)) return false; const regex = cmd.includes('regex'); if (regex && !user.can('makeroom')) return this.errorReply("Regex banwords are only allowed for leaders or above."); // Most of the regex code is copied from the client. TODO: unify them? // Regex banwords can have commas in the {1,5} pattern let words = (regex ? target.match(/[^,]+(,\d*}[^,]*)?/g)! : target.split(',')) .map(word => word.replace(/\n/g, '').trim()); if (!words) return this.parse('/help banword'); // Escape any character with a special meaning in regex if (!regex) { words = words.map(word => { if (/[\\^$*+?()|{}[\]]/.test(word)) this.errorReply(`"${word}" might be a regular expression, did you mean "/banword addregex"?`); return word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }); } // PS adds a preamble to the banword regex that's 32 chars long let banwordRegexLen = (room.banwordRegex instanceof RegExp) ? room.banwordRegex.source.length : 32; for (const word of words) { try { // tslint:disable-next-line: no-unused-expression new RegExp(word); } catch (e) { return this.errorReply(e.message.startsWith('Invalid regular expression: ') ? e.message : `Invalid regular expression: /${word}/: ${e.message}`); } if (room.banwords.includes(word)) return this.errorReply(`${word} is already a banned phrase.`); // Banword strings are joined, so account for the first string not having the prefix banwordRegexLen += (banwordRegexLen === 32) ? word.length : `|${word}`.length; // RegExp instances whose source is greater than or equal to // v8's RegExpMacroAssembler::kMaxRegister in length will crash // the server on compile. In this case, that would happen each // time a chat message gets tested for any banned phrases. if (banwordRegexLen >= (1 << 16 - 1)) return this.errorReply("This room has too many banned phrases to add the ones given."); } for (const word of words) { room.banwords.push(word); } room.banwordRegex = null; if (words.length > 1) { this.privateModAction(`(The banwords ${words.map(w => `'${w}'`).join(', ')} were added by ${user.name}.)`); this.modlog('BANWORD', null, words.map(w => `'${w}'`).join(', ')); this.sendReply(`Banned phrases successfully added.`); } else { this.privateModAction(`(The banword '${words[0]}' was added by ${user.name}.)`); this.modlog('BANWORD', null, words[0]); this.sendReply(`Banned phrase successfully added.`); } this.sendReply(`The list is currently: ${room.banwords.join(', ')}`); if (room.chatRoomData) { room.chatRoomData.banwords = room.banwords; Rooms.global.writeChatRoomData(); } }, delete(target, room, user) { if (!target) return this.parse('/help banword'); if (!this.can('declare', null, room)) return false; if (!room.banwords.length) return this.errorReply("This room has no banned phrases."); let words = target.match(/[^,]+(,\d*}[^,]*)?/g); if (!words) return this.parse('/help banword'); words = words.map(word => word.replace(/\n/g, '').trim()); for (const word of words) { if (!room.banwords.includes(word)) return this.errorReply(`${word} is not a banned phrase in this room.`); } // ts bug? `words` guaranteed non-null by above falsey check room.banwords = room.banwords.filter(w => !words!.includes(w)); room.banwordRegex = null; if (words.length > 1) { this.privateModAction(`(The banwords ${words.map(w => `'${w}'`).join(', ')} were removed by ${user.name}.)`); this.modlog('UNBANWORD', null, words.map(w => `'${w}'`).join(', ')); this.sendReply(`Banned phrases successfully deleted.`); } else { this.privateModAction(`(The banword '${words[0]}' was removed by ${user.name}.)`); this.modlog('UNBANWORD', null, words[0]); this.sendReply(`Banned phrase successfully deleted.`); } this.sendReply(room.banwords && room.banwords.length ? `The list is currently: ${room.banwords.join(', ')}` : `The list is now empty.`); if (room.chatRoomData) { room.chatRoomData.banwords = room.banwords; if (!room.banwords) delete room.chatRoomData.banwords; Rooms.global.writeChatRoomData(); } }, list(target, room, user) { if (!this.can('mute', null, room)) return false; if (!room.banwords || !room.banwords.length) return this.sendReply("This room has no banned phrases."); return this.sendReply(`Banned phrases in room ${room.roomid}: ${room.banwords.join(', ')}`); }, ""(target, room, user) { return this.parse("/help banword"); }, }, banwordhelp: [ `/banword add [words] - Adds the comma-separated list of phrases to the banword list of the current room. Requires: # & ~`, `/banword addregex [words] - Adds the comma-separated list of regular expressions to the banword list of the current room. Requires & ~`, `/banword delete [words] - Removes the comma-separated list of phrases from the banword list. Requires: # & ~`, `/banword list - Shows the list of banned words in the current room. Requires: % @ # & ~`, ], hightraffic(target, room, user) { if (!target) { return this.sendReply(`This room is${!room.highTraffic ? ' not' : ''} currently marked as high traffic.`); } if (!this.can('makeroom')) return false; if (this.meansYes(target)) { room.highTraffic = true; } else if (this.meansNo(target)) { room.highTraffic = false; } else { return this.parse('/help hightraffic'); } if (room.chatRoomData) { room.chatRoomData.highTraffic = room.highTraffic; Rooms.global.writeChatRoomData(); } this.modlog(`HIGHTRAFFIC`, null, '' + room.highTraffic); this.addModAction(`This room was marked as high traffic by ${user.name}.`); }, hightraffichelp: [ `/hightraffic [true|false] - (Un)marks a room as a high traffic room. Requires & ~`, `When a room is marked as high-traffic, PS requires all messages sent to that room to contain at least 2 letters.`, ], /********************************************************* * Room management *********************************************************/ makeprivatechatroom: 'makechatroom', makechatroom(target, room, user, connection, cmd) { if (!this.can('makeroom')) return; // `,` is a delimiter used by a lot of /commands // `|` and `[` are delimiters used by the protocol // `-` has special meaning in roomids if (target.includes(',') || target.includes('|') || target.includes('[') || target.includes('-')) { return this.errorReply("Room titles can't contain any of: ,|[-"); } const id = toID(target); if (!id) return this.parse('/help makechatroom'); if (id.length > MAX_CHATROOM_ID_LENGTH) return this.errorReply("The given room title is too long."); // Check if the name already exists as a room or alias if (Rooms.search(id)) return this.errorReply(`The room '${target}' already exists.`); if (!Rooms.global.addChatRoom(target)) return this.errorReply(`An error occurred while trying to create the room '${target}'.`); const targetRoom = Rooms.search(target); if (!targetRoom) throw new Error(`Error in room creation.`); if (cmd === 'makeprivatechatroom') { targetRoom.isPrivate = true; if (!targetRoom.chatRoomData) throw new Error(`Private chat room created without chatRoomData.`); targetRoom.chatRoomData.isPrivate = true; Rooms.global.writeChatRoomData(); const upperStaffRoom = Rooms.get('upperstaff'); if (upperStaffRoom) { upperStaffRoom.add(`|raw|<div class="broadcast-green">Private chat room created: <b>${Chat.escapeHTML(target)}</b></div>`).update(); } this.sendReply(`The private chat room '${target}' was created.`); } else { const staffRoom = Rooms.get('staff'); if (staffRoom) { staffRoom.add(`|raw|<div class="broadcast-green">Public chat room created: <b>${Chat.escapeHTML(target)}</b></div>`).update(); } const upperStaffRoom = Rooms.get('upperstaff'); if (upperStaffRoom) { upperStaffRoom.add(`|raw|<div class="broadcast-green">Public chat room created: <b>${Chat.escapeHTML(target)}</b></div>`).update(); } this.sendReply(`The chat room '${target}' was created.`); } }, makechatroomhelp: [`/makechatroom [roomname] - Creates a new room named [roomname]. Requires: & ~`], subroomgroupchat: 'makegroupchat', makegroupchat(target, room, user, connection, cmd) { if (!this.canTalk()) return; if (!user.autoconfirmed) { return this.errorReply("You must be autoconfirmed to make a groupchat."); } if (cmd === 'subroomgroupchat') { if (!user.can('mute', null, room)) return this.errorReply("You can only create subroom groupchats for rooms you're staff in."); if (room.battle) return this.errorReply("You cannot create a subroom of a battle."); if (room.isPersonal) return this.errorReply("You cannot create a subroom of a groupchat."); } const parent = cmd === 'subroomgroupchat' ? room.roomid : null; // if (!this.can('makegroupchat')) return false; // Title defaults to a random 8-digit number. let title = target.trim(); if (title.length >= 32) { return this.errorReply("Title must be under 32 characters long."); } else if (!title) { title = (`${Math.floor(Math.random() * 100000000)}`); } else if (Config.chatfilter) { const filterResult = Config.chatfilter.call(this, title, user, null, connection); if (!filterResult) return; if (title !== filterResult) { return this.errorReply("Invalid title."); } } // `,` is a delimiter used by a lot of /commands // `|` and `[` are delimiters used by the protocol // `-` has special meaning in roomids if (title.includes(',') || title.includes('|') || title.includes('[') || title.includes('-')) { return this.errorReply("Room titles can't contain any of: ,|[-"); } // Even though they're different namespaces, to cut down on confusion, you // can't share names with registered chatrooms. const existingRoom = Rooms.search(toID(title)); if (existingRoom && !existingRoom.modjoin) return this.errorReply(`The room '${title}' already exists.`); // Room IDs for groupchats are groupchat-TITLEID let titleid = toID(title); if (!titleid) { titleid = `${Math.floor(Math.random() * 100000000)}` as ID; } const roomid = `groupchat-${parent || user.id}-${titleid}` as RoomID; // Titles must be unique. if (Rooms.search(roomid)) return this.errorReply(`A group chat named '${title}' already exists.`); // Tab title is prefixed with '[G]' to distinguish groupchats from // registered chatrooms if (Monitor.countGroupChat(connection.ip)) { this.errorReply("Due to high load, you are limited to creating 4 group chats every hour."); return; } const titleMsg = Chat.html `Welcome to ${parent ? room.title : user.name}'s${!/^[0-9]+$/.test(title) ? ` ${title}` : ''}${parent ? ' subroom' : ''} groupchat!`; const targetRoom = Rooms.createChatRoom(roomid, `[G] ${title}`, { isPersonal: true, isPrivate: 'hidden', creationTime: parent ? null : Date.now(), modjoin: parent ? null : '+', parentid: parent, auth: {}, introMessage: `<div style="text-align: center"><table style="margin:auto;"><tr><td><img src="//${Config.routes.client}/fx/groupchat.png" width=120 height=100></td><td><h2>${titleMsg}</h2><p>Follow the <a href="/rules">Pokémon Showdown Global Rules</a>!<br>Don't be disruptive to the rest of the site.</p></td></tr></table></div>`, staffMessage: `<p>Groupchats are temporary rooms, and will expire if there hasn't been any activity in 40 minutes.</p><p>You can invite new users using <code>/invite</code>. Be careful with who you invite!</p><p>Commands: <button class="button" name="send" value="/roomhelp">Room Management</button> | <button class="button" name="send" value="/roomsettings">Room Settings</button> | <button class="button" name="send" value="/tournaments help">Tournaments</button></p><p>As creator of this groupchat, <u>you are entirely responsible for what occurs in this chatroom</u>. Global rules apply at all times.</p><p>If this room is used to break global rules or disrupt other areas of the server, <strong>you as the creator will be held accountable and punished</strong>.</p>`, }); if (targetRoom) { // The creator is a Room Owner in subroom groupchats and a Host otherwise.. targetRoom.auth![user.id] = parent ? '#' : Users.HOST_SYMBOL; // Join after creating room. No other response is given. user.joinRoom(targetRoom.roomid); user.popup(`You've just made a groupchat; it is now your responsibility, regardless of whether or not you actively partake in the room. For more info, read your groupchat's staff intro.`); if (parent) this.modlog('SUBROOMGROUPCHAT', null, title); return; } return this.errorReply(`An unknown error occurred while trying to create the room '${title}'.`); }, makegroupchathelp: [ `/makegroupchat [roomname] - Creates an invite-only group chat named [roomname].`, `/subroomgroupchat [roomname] - Creates a subroom groupchat of the current room. Can only be used in a public room you have staff in.`, ], '!groupchatuptime': true, groupchatuptime(target, room, user) { if (!room || !room.creationTime) return this.errorReply("Can only be used in a groupchat."); if (!this.runBroadcast()) return; const uptime = Chat.toDurationString(Date.now() - room.creationTime); this.sendReplyBox(`Groupchat uptime: <b>${uptime}</b>`); }, groupchatuptimehelp: [`/groupchatuptime - Displays the uptime if the current room is a groupchat.`], deregisterchatroom(target, room, user) { if (!this.can('makeroom')) return; this.errorReply("NOTE: You probably want to use `/deleteroom` now that it exists."); const id = toID(target); if (!id) return this.parse('/help deregisterchatroom'); const targetRoom = Rooms.search(id); if (!targetRoom) return this.errorReply(`The room '${target}' doesn't exist.`); target = targetRoom.title || targetRoom.roomid; const isPrivate = targetRoom.isPrivate; const staffRoom = Rooms.get('staff'); const upperStaffRoom = Rooms.get('upperstaff'); if (Rooms.global.deregisterChatRoom(id)) { this.sendReply(`The room '${target}' was deregistered.`); this.sendReply("It will be deleted as of the next server restart."); target = Chat.escapeHTML(target); if (isPrivate) { if (upperStaffRoom) upperStaffRoom.add(`|raw|<div class="broadcast-red">Private chat room deregistered by ${user.id}: <b>${target}</b></div>`).update(); } else { if (staffRoom) { staffRoom.add(`|raw|<div class="broadcast-red">Public chat room deregistered: <b>${target}</b></div>`).update(); } if (upperStaffRoom) { upperStaffRoom.add(`|raw|<div class="broadcast-red">Public chat room deregistered by ${user.id}: <b>${target}</b></div>`).update(); } } return; } return this.errorReply(`The room "${target}" isn't registered.`); }, deregisterchatroomhelp: [`/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: & ~`], deletechatroom: 'deleteroom', deletegroupchat: 'deleteroom', deleteroom(target, room, user, connection, cmd) { const roomid = target.trim(); if (!roomid) { // allow deleting personal rooms without typing out the room name if (!room.isPersonal || cmd !== "deletegroupchat") { return this.parse(`/help deleteroom`); } } else { const targetRoom = Rooms.search(roomid); if (targetRoom !== room) { return this.parse(`/help deleteroom`); } } if (room.isPersonal) { if (!this.can('gamemanagement', null, room)) return; } else { if (!this.can('makeroom')) return; } const title = room.title || room.roomid; if (room.roomid === 'global') { return this.errorReply(`This room can't be deleted.`); } if (room.chatRoomData) { if (room.isPrivate) { const upperStaffRoom = Rooms.get('upperstaff'); if (upperStaffRoom) { upperStaffRoom.add(Chat.html`|raw|<div class="broadcast-red">Private chat room deleted by ${user.id}: <b>${title}</b></div>`).update(); } } else { const staffRoom = Rooms.get('staff'); if (staffRoom) { staffRoom.add(Chat.html`|raw|<div class="broadcast-red">Public chat room deleted: <b>${title}</b></div>`).update(); } const upperStaffRoom = Rooms.get('upperstaff'); if (upperStaffRoom) { upperStaffRoom.add(Chat.html`|raw|<div class="broadcast-red">Public chat room deleted by ${user.id}: <b>${title}</b></div>`).update(); } } } if (room.subRooms) { for (const subRoom of room.subRooms.values()) subRoom.parent = null; } room.add(`|raw|<div class="broadcast-red"><b>This room has been deleted.</b></div>`); room.update(); // |expire| needs to be its own message room.add(`|expire|This room has been deleted.`); this.sendReply(`The room "${title}" was deleted.`); room.update(); room.destroy(); }, deleteroomhelp: [ `/deleteroom [roomname] - Deletes room [roomname]. Must be typed in the room to delete. Requires: & ~`, `/deletegroupchat - Deletes the current room, if it's a groupchat. Requires: ★ # & ~`, ], hideroom: 'privateroom', hiddenroom: 'privateroom', secretroom: 'privateroom', publicroom: 'privateroom', privateroom(target, room, user, connection, cmd) { if (room.isPersonal) { if (!this.can('editroom', null, room)) return; } else if (room.battle) { if (!this.can('editprivacy', null, room)) return; const prefix = room.battle.forcedPublic(); if (prefix && !user.can('editprivacy')) return this.errorReply(`This battle is required to be public due to a player having a name prefixed by '${prefix}'.`); } else { // registered chatrooms show up on the room list and so require // higher permissions to modify privacy settings if (!this.can('makeroom')) return; } let setting: boolean | 'hidden'; switch (cmd) { case 'privateroom': return this.parse('/help privateroom'); case 'publicroom': setting = false; break; case 'secretroom': setting = true; break; default: if (room.isPrivate === true && target !== 'force') { return this.sendReply(`This room is a secret room. Use "/publicroom" to make it public, or "/hiddenroom force" to force it hidden.`); } setting = 'hidden'; break; } if ((setting === true || room.isPrivate === true) && !room.isPersonal) { if (!this.can('makeroom')) return; } if (this.meansNo(target) || !setting) { if (!room.isPrivate) { return this.errorReply(`This room is already public.`); } if (room.parent && room.parent.isPrivate) { return this.errorReply(`This room's parent ${room.parent.title} must be public for this room to be public.`); } if (room.isPersonal) return this.errorReply(`This room can't be made public.`); if (room.privacySetter && user.can('nooverride', null, room) && !user.can('makeroom')) { if (!room.privacySetter.has(user.id)) { const privacySetters = [...room.privacySetter].join(', '); return this.errorReply(`You can't make the room public since you didn't make it private - only ${privacySetters} can.`); } room.privacySetter.delete(user.id); if (room.privacySetter.size) { const privacySetters = [...room.privacySetter].join(', '); return this.sendReply(`You are no longer forcing the room to stay private, but ${privacySetters} also need${Chat.plural(room.privacySetter, "", "s")} to use /publicroom to make the room public.`); } } delete room.isPrivate; room.privacySetter = null; this.addModAction(`${user.name} made this room public.`); this.modlog('PUBLICROOM'); if (room.chatRoomData) { delete room.chatRoomData.isPrivate; Rooms.global.writeChatRoomData(); } } else { const settingName = (setting === true ? 'secret' : setting); if (room.subRooms) { if (settingName === 'secret') return this.errorReply("Secret rooms cannot have subrooms."); for (const subRoom of room.subRooms.values()) { if (!subRoom.isPrivate) return this.errorReply(`Subroom ${subRoom.title} must be private to make this room private.`); } } if (room.isPrivate === setting) { if (room.privacySetter && !room.privacySetter.has(user.id)) { room.privacySetter.add(user.id); return this.sendReply(`This room is already ${settingName}, but is now forced to stay that way until you use /publicroom.`); } return this.errorReply(`This room is already ${settingName}.`); } room.isPrivate = setting; this.addModAction(`${user.name} made this room ${settingName}.`); this.modlog(`${settingName.toUpperCase()}ROOM`); if (room.chatRoomData) { room.chatRoomData.isPrivate = setting; Rooms.global.writeChatRoomData(); } room.privacySetter = new Set([user.id]); } }, privateroomhelp: [ `/secretroom - Makes a room secret. Secret rooms are visible to & and up. Requires: & ~`, `/hiddenroom [on/off] - Makes a room hidden. Hidden rooms are visible to % and up, and inherit global ranks. Requires: \u2606 & ~`, `/publicroom - Makes a room public. Requires: \u2606 & ~`, ], officialchatroom: 'officialroom', officialroom(target, room, user) { if (!this.can('makeroom')) return; if (!room.chatRoomData) { return this.errorReply(`/officialroom - This room can't be made official`); } if (this.meansNo(target)) { if (!room.isOfficial) return this.errorReply(`This chat room is already unofficial.`); delete room.isOfficial; this.addModAction(`${user.name} made this chat room unofficial.`); this.modlog('UNOFFICIALROOM'); delete room.chatRoomData.isOfficial; Rooms.global.writeChatRoomData(); } else { if (room.isOfficial) return this.errorReply(`This chat room is already official.`); room.isOfficial = true; this.addModAction(`${user.name} made this chat room official.`); this.modlog('OFFICIALROOM'); room.chatRoomData.isOfficial = true; Rooms.global.writeChatRoomData(); } }, psplwinnerroom(target, room, user) { if (!this.can('makeroom')) return; if (!room.chatRoomData) { return this.errorReply(`/psplwinnerroom - This room can't be marked as a PSPL Winner room`); } if (this.meansNo(target)) { // @ts-ignore if (!room.pspl) return this.errorReply(`This chat room is already not a PSPL Winner room.`); // @ts-ignore delete room.pspl; this.addModAction(`${user.name} made this chat room no longer a PSPL Winner room.`); this.modlog('PSPLROOM'); delete room.chatRoomData.pspl; Rooms.global.writeChatRoomData(); } else { // @ts-ignore if (room.pspl) return this.errorReply("This chat room is already a PSPL Winner room."); // @ts-ignore room.pspl = true; this.addModAction(`${user.name} made this chat room a PSPL Winner room.`); this.modlog('UNPSPLROOM'); room.chatRoomData.pspl = true; Rooms.global.writeChatRoomData(); } }, setsubroom: 'subroom', subroom(target, room, user) { if (!user.can('makeroom')) return this.errorReply(`/subroom - Access denied. Did you mean /subrooms?`); if (!target) return this.parse('/help subroom'); if (!room.chatRoomData) return this.errorReply(`Temporary rooms cannot be subrooms.`); if (room.parent) return this.errorReply(`This room is already a subroom. To change which room this subroom belongs to, remove the subroom first.`); if (room.subRooms) return this.errorReply(`This room is already a parent room, and a parent room cannot be made as a subroom.`); const main = Rooms.search(target); if (!main) return this.errorReply(`The room '${target}' does not exist.`); if (main.parent) return this.errorReply(`Subrooms cannot have subrooms.`); if (main.isPrivate === true) return this.errorReply(`Only public and hidden rooms can have subrooms.`); if (main.isPrivate && !room.isPrivate) return this.errorReply(`Private rooms cannot have public subrooms.`); if (!main.chatRoomData) return this.errorReply(`Temporary rooms cannot be parent rooms.`); if (room === main) return this.errorReply(`You cannot set a room to be a subroom of itself.`); room.parent = main; if (!main.subRooms) main.subRooms = new Map(); main.subRooms.set(room.roomid, room as ChatRoom); const mainIdx = Rooms.global.chatRoomDataList.findIndex(r => r.title === main.title); const subIdx = Rooms.global.chatRoomDataList.findIndex(r => r.title === room.title); // This is needed to ensure that the main room gets loaded before the subroom. if (mainIdx > subIdx) { const tmp = Rooms.global.chatRoomDataList[mainIdx]; Rooms.global.chatRoomDataList[mainIdx] = Rooms.global.chatRoomDataList[subIdx]; Rooms.global.chatRoomDataList[subIdx] = tmp; } room.chatRoomData.parentid = main.roomid; Rooms.global.writeChatRoomData(); for (const userid in room.users) { room.users[userid].updateIdentity(room.roomid); } this.modlog('SUBROOM', null, `of ${main.title}`); return this.addModAction(`This room was set as a subroom of ${main.title} by ${user.name}.`); }, removesubroom: 'unsubroom', desubroom: 'unsubroom', unsubroom(target, room, user) { if (!this.can('makeroom')) return; if (!room.parent || !room.chatRoomData) return this.errorReply(`This room is not currently a subroom of a public room.`); const parent = room.parent; if (parent && parent.subRooms) { parent.subRooms.delete(room.roomid); if (!parent.subRooms.size) parent.subRooms = null; } room.parent = null; delete room.chatRoomData.parentid; Rooms.global.writeChatRoomData(); for (const userid in room.users) { room.users[userid].updateIdentity(room.roomid); } this.modlog('UNSUBROOM'); return this.addModAction(`This room was unset as a subroom by ${user.name}.`); }, parentroom: 'subrooms', subrooms(target, room, user, connection, cmd) { if (cmd === 'parentroom') { if (!room.parent) return this.errorReply(`This room is not a subroom.`); return this.sendReply(`This is a subroom of ${room.parent.title}.`); } if (!room.chatRoomData) return this.errorReply(`Temporary rooms cannot have subrooms.`); if (!this.runBroadcast()) return; const showSecret = !this.broadcasting && user.can('mute', null, room); const subRooms = room.getSubRooms(showSecret); if (!subRooms.length) return this.sendReply(`This room doesn't have any subrooms.`); const subRoomText = subRooms.map(subRoom => Chat.html`<a href="/${subRoom.roomid}">${subRoom.title}</a><br/><small>${subRoom.desc}</small>`); return this.sendReplyBox(`<p style="font-weight:bold;">${Chat.escapeHTML(room.title)}'s subroom${Chat.plural(subRooms)}:</p><ul><li>${subRoomText.join('</li><br/><li>')}</li></ul></strong>`); }, subroomhelp: [ `/subroom [room] - Marks the current room as a subroom of [room]. Requires: & ~`, `/unsubroom - Unmarks the current room as a subroom. Requires: & ~`, `/subrooms - Displays the current room's subrooms.`, `/parentroom - Displays the current room's parent room.`, ], roomdesc(target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.desc) return this.sendReply(`This room does not have a description set.`); this.sendReplyBox(Chat.html`The room description is: ${room.desc}`); return; } if (!this.can('declare')) return false; if (target.length > 80) { return this.errorReply(`Error: Room description is too long (must be at most 80 characters).`); } const normalizedTarget = ' ' + target.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' '; if (normalizedTarget.includes(' welcome ')) { return this.errorReply(`Error: Room description must not contain the word "welcome".`); } if (normalizedTarget.slice(0, 9) === ' discuss ') { return this.errorReply(`Error: Room description must not start with the word "discuss".`); } if (normalizedTarget.slice(0, 12) === ' talk about ' || normalizedTarget.slice(0, 17) === ' talk here about ') { return this.errorReply(`Error: Room description must not start with the phrase "talk about".`); } room.desc = target; this.sendReply(`(The room description is now: ${target})`); this.privateModAction(`(${user.name} changed the roomdesc to: "${target}".)`); this.modlog('ROOMDESC', null, `to "${target}"`); if (room.chatRoomData) { room.chatRoomData.desc = room.desc; Rooms.global.writeChatRoomData(); } }, topic: 'roomintro', roomintro(target, room, user, connection, cmd) { if (!target) { if (!this.runBroadcast()) return; if (!room.introMessage) return this.sendReply("This room does not have an introduction set."); this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage.replace(/\n/g, '') + '</div>'); if (!this.broadcasting && user.can('declare', null, room) && cmd !== 'topic') { this.sendReply('Source:'); const code = Chat.escapeHTML(room.introMessage).replace(/\n/g, '<br />'); this.sendReplyBox(`<code style="white-space: pre-wrap">/roomintro ${code}</code>`); } return; } if (!this.can('editroom', null, room)) return false; if (this.meansNo(target) || target === 'delete') return this.errorReply('Did you mean "/deleteroomintro"?'); target = this.canHTML(target)!; if (!target) return; // canHTML sends its own errors if (!/</.test(target)) { // not HTML, do some simple URL linking const re = /(https?:\/\/(([\w.-]+)+(:\d+)?(\/([\w/_.]*(\?\S+)?)?)?))/g; target = target.replace(re, '<a href="$1">$1</a>'); } if (target.substr(0, 11) === '/roomintro ') target = target.substr(11); room.introMessage = target.replace(/\r/g, ''); this.sendReply("(The room introduction has been changed to:)"); this.sendReply(`|raw|<div class="infobox infobox-limited">${room.introMessage.replace(/\n/g, '')}</div>`); this.privateModAction(`(${user.name} changed the roomintro.)`); this.modlog('ROOMINTRO'); this.roomlog(room.introMessage.replace(/\n/g, '')); if (room.chatRoomData) { room.chatRoomData.introMessage = room.introMessage; Rooms.global.writeChatRoomData(); } }, deletetopic: 'deleteroomintro', deleteroomintro(target, room, user) { if (!this.can('declare', null, room)) return false; if (!room.introMessage) return this.errorReply("This room does not have a introduction set."); this.privateModAction(`(${user.name} deleted the roomintro.)`); this.modlog('DELETEROOMINTRO'); this.roomlog(target); delete room.introMessage; if (room.chatRoomData) { delete room.chatRoomData.introMessage; Rooms.global.writeChatRoomData(); } }, stafftopic: 'staffintro', staffintro(target, room, user, connection, cmd) { if (!target) { if (!this.can('mute', null, room)) return false; if (!room.staffMessage) return this.sendReply("This room does not have a staff introduction set."); this.sendReply(`|raw|<div class="infobox">${room.staffMessage.replace(/\n/g, ``)}</div>`); if (user.can('ban', null, room) && cmd !== 'stafftopic') { this.sendReply('Source:'); const code = Chat.escapeHTML(room.staffMessage).replace(/\n/g, '<br />'); this.sendReplyBox(`<code style="white-space: pre-wrap">/staffintro ${code}</code>`); } return; } if (!this.can('ban', null, room)) return false; if (!this.canTalk()) return; if (this.meansNo(target) || target === 'delete') return this.errorReply('Did you mean "/deletestaffintro"?'); target = this.canHTML(target)!; if (!target) return; if (!/</.test(target)) { // not HTML, do some simple URL linking const re = /(https?:\/\/(([\w.-]+)+(:\d+)?(\/([\w/_.]*(\?\S+)?)?)?))/g; target = target.replace(re, '<a href="$1">$1</a>'); } if (target.substr(0, 12) === '/staffintro ') target = target.substr(12); room.staffMessage = target.replace(/\r/g, ''); this.sendReply("(The staff introduction has been changed to:)"); this.sendReply(`|raw|<div class="infobox">${target.replace(/\n/g, ``)}</div>`); this.privateModAction(`(${user.name} changed the staffintro.)`); this.modlog('STAFFINTRO'); this.roomlog(room.staffMessage.replace(/\n/g, ``)); if (room.chatRoomData) { room.chatRoomData.staffMessage = room.staffMessage; Rooms.global.writeChatRoomData(); } }, deletestafftopic: 'deletestaffintro', deletestaffintro(target, room, user) { if (!this.can('ban', null, room)) return false; if (!room.staffMessage) return this.errorReply("This room does not have a staff introduction set."); this.privateModAction(`(${user.name} deleted the staffintro.)`); this.modlog('DELETESTAFFINTRO'); this.roomlog(target); delete room.staffMessage; if (room.chatRoomData) { delete room.chatRoomData.staffMessage; Rooms.global.writeChatRoomData(); } }, roomalias(target, room, user) { if (!target) { if (!this.runBroadcast()) return; if (!room.aliases || !room.aliases.length) return this.sendReplyBox("This room does not have any aliases."); return this.sendReplyBox(`This room has the following aliases: ${room.aliases.join(", ")}`); } if (!this.can('makeroom')) return false; if (target.includes(',')) { this.errorReply(`Invalid room alias: ${target.trim()}`); return this.parse('/help roomalias'); } const alias = toID(target); if (!alias.length) return this.errorReply("Only alphanumeric characters are valid in an alias."); if (Rooms.get(alias) || Rooms.aliases.has(alias)) return this.errorReply("You cannot set an alias to an existing room or alias."); if (room.isPersonal) return this.errorReply("Personal rooms can't have aliases."); Rooms.aliases.set(alias, room.roomid); this.privateModAction(`(${user.name} added the room alias '${alias}'.)`); this.modlog('ROOMALIAS', null, alias); if (!room.aliases) room.aliases = []; room.aliases.push(alias); if (room.chatRoomData) { room.chatRoomData.aliases = room.aliases; Rooms.global.writeChatRoomData(); } }, roomaliashelp: [ `/roomalias - displays a list of all room aliases of the room the command was entered in.`, `/roomalias [alias] - adds the given room alias to the room the command was entered in. Requires: & ~`, `/removeroomalias [alias] - removes the given room alias of the room the command was entered in. Requires: & ~`, ], deleteroomalias: 'removeroomalias', deroomalias: 'removeroomalias', unroomalias: 'removeroomalias', removeroomalias(target, room, user) { if (!room.aliases) return this.errorReply("This room does not have any aliases."); if (!this.can('makeroom')) return false; if (target.includes(',')) { this.errorReply(`Invalid room alias: ${target.trim()}`); return this.parse('/help removeroomalias'); } const alias = toID(target); if (!alias || !Rooms.aliases.has(alias)) return this.errorReply("Please specify an existing alias."); if (Rooms.aliases.get(alias) !== room.roomid) return this.errorReply("You may only remove an alias from the current room."); this.privateModAction(`(${user.name} removed the room alias '${alias}'.)`); this.modlog('REMOVEALIAS', null, alias); const aliasIndex = room.aliases.indexOf(alias); if (aliasIndex >= 0) { room.aliases.splice(aliasIndex, 1); Rooms.aliases.delete(alias); Rooms.global.writeChatRoomData(); } }, removeroomaliashelp: [`/removeroomalias [alias] - removes the given room alias of the room the command was entered in. Requires: & ~`], }; export const roomSettings: SettingsHandler[] = [ // modchat (room, user) => { const threshold = user.can('makeroom') ? Infinity : user.can('modchatall', null, room) ? Config.groupsranking.indexOf(room.getAuth(user)) : user.can('modchat', null, room) ? 1 : null; const permission = !!threshold; // typescript seems to think that [prop, true] is of type [prop, boolean] unless we tell it explicitly const options: [string, string | true][] = !permission ? [[room.modchat || 'off', true]] : [ 'off', 'autoconfirmed', 'trusted', ...RANKS.slice(1, threshold + 1), ].map(rank => [rank, (rank === 'off' ? !room.modchat : rank === room.modchat) || `modchat ${rank || 'off'}`]); return { label: "Modchat", permission, options, }; }, (room, user) => ({ label: "Modjoin", permission: room.isPersonal ? user.can('editroom', null, room) : user.can('makeroom'), options: [ 'off', 'autoconfirmed', // groupchat ROs can set modjoin, but only to + // first rank is for modjoin off ...RANKS.slice(1, room.isPersonal && !user.can('makeroom') ? 2 : undefined), ].map(rank => [rank, (rank === 'off' ? !room.modjoin : rank === room.modjoin) || `modjoin ${rank || 'off'}`] ), }), room => ({ label: "Language", permission: 'editroom', options: [...Chat.languages].map(([id, name]) => [name, (id === 'english' ? !room.language : id === room.language) || `roomlanguage ${id}`] ), }), room => ({ label: "Stretch filter", permission: 'editroom', options: [ [`off`, !room.filterStretching || 'stretchfilter off'], [`on`, room.filterStretching || 'stretchfilter on'], ], }), room => ({ label: "Caps filter", permission: 'editroom', options: [ [`off`, !room.filterCaps || 'capsfilter off'], [`on`, room.filterCaps || 'capsfilter on'], ], }), room => ({ label: "Emoji filter", permission: 'editroom', options: [ [`off`, !room.filterEmojis || 'emojifilter off'], [`on`, room.filterEmojis || 'emojifilter on'], ], }), room => ({ label: "Slowchat", permission: room.userCount < SLOWCHAT_USER_REQUIREMENT ? 'bypassall' : 'editroom', options: ['off', 5, 10, 20, 30, 60].map(time => [`${time}`, (time === 'off' ? !room.slowchat : time === room.slowchat) || `slowchat ${time || 'false'}`] ), }), ];
mit
knq/xo
_examples/pgcatalog/ischema/elementtype.xo.go
2983
package ischema // Code generated by xo. DO NOT EDIT. import ( "database/sql" ) // ElementType represents a row from 'information_schema.element_types'. type ElementType struct { ObjectCatalog sql.NullString `json:"object_catalog"` // object_catalog ObjectSchema sql.NullString `json:"object_schema"` // object_schema ObjectName sql.NullString `json:"object_name"` // object_name ObjectType sql.NullString `json:"object_type"` // object_type CollectionTypeIdentifier sql.NullString `json:"collection_type_identifier"` // collection_type_identifier DataType sql.NullString `json:"data_type"` // data_type CharacterMaximumLength sql.NullInt64 `json:"character_maximum_length"` // character_maximum_length CharacterOctetLength sql.NullInt64 `json:"character_octet_length"` // character_octet_length CharacterSetCatalog sql.NullString `json:"character_set_catalog"` // character_set_catalog CharacterSetSchema sql.NullString `json:"character_set_schema"` // character_set_schema CharacterSetName sql.NullString `json:"character_set_name"` // character_set_name CollationCatalog sql.NullString `json:"collation_catalog"` // collation_catalog CollationSchema sql.NullString `json:"collation_schema"` // collation_schema CollationName sql.NullString `json:"collation_name"` // collation_name NumericPrecision sql.NullInt64 `json:"numeric_precision"` // numeric_precision NumericPrecisionRadix sql.NullInt64 `json:"numeric_precision_radix"` // numeric_precision_radix NumericScale sql.NullInt64 `json:"numeric_scale"` // numeric_scale DatetimePrecision sql.NullInt64 `json:"datetime_precision"` // datetime_precision IntervalType sql.NullString `json:"interval_type"` // interval_type IntervalPrecision sql.NullInt64 `json:"interval_precision"` // interval_precision DomainDefault sql.NullString `json:"domain_default"` // domain_default UdtCatalog sql.NullString `json:"udt_catalog"` // udt_catalog UdtSchema sql.NullString `json:"udt_schema"` // udt_schema UdtName sql.NullString `json:"udt_name"` // udt_name ScopeCatalog sql.NullString `json:"scope_catalog"` // scope_catalog ScopeSchema sql.NullString `json:"scope_schema"` // scope_schema ScopeName sql.NullString `json:"scope_name"` // scope_name MaximumCardinality sql.NullInt64 `json:"maximum_cardinality"` // maximum_cardinality DtdIdentifier sql.NullString `json:"dtd_identifier"` // dtd_identifier }
mit
RaviRajpurohit/CodeIgniter
application/views/jobseeker/employer_retry_sign_in.php
1792
<?php defined('BASEPATH') OR exit('No direct script access allowed'); if($this->session->userdata('e_mail')!=''){ redirect(base_url().'index.php/home'); } ?> <?php echo form_open('employer_sign_in/sing_in_user'); echo '<span style="color:red;">'.$this->session->flashdata('error').'</span>'; ?> <div class="modal-header"> <h4 class="modal-title">Employer Sign In</h4> </div> <div class="modal-body"> <div class="row"> <div class="col-lg-12 form-group"> <label>E-mail</label> <?php echo form_error('e_mail');?> <?php echo form_input(array('id' => 'e_mail', 'name' => 'e_mail', 'class'=>'form-control', 'placeholder'=>"E-mail", 'required'=>'required')); ?> </div> <div class="col-lg-12 form-group"> <label>Password</label> <?php echo form_error('password');?> <?php echo form_password(array('id' => 'password', 'name' => 'password', 'class'=>'form-control', 'placeholder'=>"Password", 'required'=>'required')); ?> </div> <div class="col-lg-12 form-group"> <!-- Try next tmie --> <input type="checkbox" /> Remember Me <!-- --> <a href="<?php echo base_url();?>index.php/employer_sign_in/forgot_password" class="mt-3 pull-right">Forgot Password?</a> </div> <div class="col-lg-12">By signing, you agree to HedgeLinks <a href="<?php echo base_url();?>index.php/employer_sign_in/terms_of_use">Terms of use</a> and <a href="<?php echo base_url();?>index.php/employer_sign_in/privacy_policy">Privacy Policy</a>.</div> <div class="col-lg-12">Don't have account? <a href="<?php echo base_url();?>index.php/employer_register">Register Now</a>.</div> </div> </div> <div class="modal-footer"> <input type="submit" value="Submit" class="theme-btn" /> </div> <?php echo form_close(); ?>
mit
dmaslov/super-coin-box
gulpfile.js
2079
var gulp = require('gulp'), jsmin = require('gulp-jsmin'), rename = require('gulp-rename'), imagemin = require('gulp-imagemin'), optipng = require('imagemin-optipng'), cssmin = require('gulp-cssmin'), concat = require('gulp-concat'), connect = require('gulp-connect'); var srcPath = 'public'; var paths = { js: [ srcPath + '/js/**/*.js', '!' + srcPath + '/js/*.min.js' ], jsMinified: [ 'bower_components/phaser/build/phaser.min.js', srcPath + '/js/all.min.js', ], mapFile: ['bower_components/phaser/build/phaser.map'], images: [ srcPath + '/assets/images/*', '!' + srcPath + '/assets/images/*.map', ], css: [ srcPath + '/css/*', '!' + srcPath + '/css/*.min.css', ] }; var copyMapFile = function(){ gulp.src(paths.mapFile) .pipe(gulp.dest(srcPath + '/js/')); }; var jsGluer = function(){ gulp.src(paths.jsMinified) .pipe(concat('tmp.js')) .pipe(rename('all.min.js')) .pipe(gulp.dest(srcPath + '/js/')) .on('end', copyMapFile); }; gulp.task('js-minifier', function() { gulp.src(paths.js) .pipe(concat('tmp.js')) .pipe(rename('all.min.js')) .pipe(jsmin()) .pipe(gulp.dest(srcPath + '/js/')) .on('end', jsGluer); }); gulp.task('image-minifier', function () { return gulp.src(paths.images) .pipe(imagemin({ progressive: true, svgoPlugins: [{removeViewBox: false}], use:[optipng({optimizationLevel: 7})] })) .pipe(gulp.dest(srcPath + '/assets/images/')); }); gulp.task('css-minifier', function () { gulp.src(paths.css) .pipe(cssmin()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(srcPath + '/css/')); }); gulp.task('server', function() { connect.server({ root: 'public', port: 8080, livereload: false }); }); gulp.task('watch', function(){ gulp.watch(paths.js, ['js-minifier']); gulp.watch(paths.css, ['css-minifier']); }); gulp.task('default', ['js-minifier', 'image-minifier', 'css-minifier', 'watch']); //gulp-devtools module.exports = gulp;
mit
michelson/BigBroda
spec/dummy/config/initializers/bigquery.rb
537
def fixture_key(type, filename) dir_name = type.to_s + "s" Rails.root + "../fixtures/#{dir_name}/#{filename}" end def config_options config = YAML.load( File.open(fixture_key("config", "account_config.yml")) ) config["key_file"] = fixture_key("key", config["pem"]) return config end GoogleBigquery::Config.setup do |config| config.pass_phrase = config_options["pass_phrase"] config.key_file = config_options["key_file"] config.scope = config_options["scope"] config.email = config_options["email"] end
mit
CamelKing/alpha
src/common/sortedLastInsertAt.ts
825
/** * Perform a binary search on a sorted array to determine * highest index to insert the target and maintain the sorting order. * * This index will be different than sortedIndex when there are * redundant elements, and this function will return the position * after the highest index as the position to insert the new item. * * Note: ASSUME array is sorted in ascending order [1,2,3] * * @since 0.0.1 * @category Array * * @refactor April 13, 2017 * * @export * @param {any[]} array * @param {*} target * @returns {number} */ import { AnyIteratee } from '../constants'; import { _searchArray } from '../base/_searchArray'; export function sortedLastInsertAt(array: any[], target: any, iteratee?: AnyIteratee): number { return _searchArray(array, target, { iteratee, insert: true, last: true }); }
mit
hiasinho/acts_as_explorable
spec/spec_helper.rb
591
begin require 'byebug' rescue LoadError end $LOAD_PATH << '.' unless $LOAD_PATH.include?('.') $LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__)) require 'logger' require File.expand_path('../../lib/acts_as_explorable', __FILE__) I18n.enforce_available_locales = true require 'rails' require 'rspec/its' require 'sqlite3' require 'factory_girl' require 'database_cleaner' Dir['./spec/support/**/*.rb'].sort.each { |f| require f } RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.raise_errors_for_deprecations! end FactoryGirl.find_definitions
mit
mrYakamoto/phase-0
week-5/pad-array/my_solution.rb
3087
=begin Pad an Array # I worked on this challenge [with: Gregg Wehmeier & Shea Munion] # I spent [1.5] hours on this challenge. # 0. Pseudocode # What is the input? - an array - a new length of array/minimum size - a string to pad the array (value) # What is the output? (i.e. What should the code return?) - an array # What are the steps needed to solve the problem? IF min size is larger than input array's length add "value" to new array ELSE return the array IF there's a value, fill the new array with value WHILE min size is larger than array's length add "value" to array END RETURN output array =end # 1. Initial Solution def pad!(array, min_size, value = nil) #destructive while min_size > array.length array << value end return array end def pad(array, min_size, value = nil) #non-destructive new_array = [] array.each do |item| new_array << item end while min_size > new_array.length new_array << value end return new_array end # 3. Refactored Solution def pad!(array, min_size, value = nil) #destructive while min_size > array.length array << value end return array end def pad(array, min_size, value = nil) #non-destructive new_array = [] new_array = array.map{|x| x} while min_size > new_array.length new_array << value end return new_array end =begin # 4. Reflection Were you successful in breaking the problem down into small steps? Yes, we were able to break the problem down into just a few, basic steps. Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have? My partner Shea and I really took our time while pseudocoding to think the problem through from a couple different angles. By the time we got to actually coding, it was pretty straightforward. We had a little bit of difficulty initially when our non-destructive method wasn't returning a new object, but we figured it out pretty quickly. Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them? Our initial non-destuctive method wasn't successful at passing the tests. We realized that our 'output array' was pointing to the same object number as the 'input array.' We were able to solve this by initializing the 'new array' as an empty array before populating it. When you refactored, did you find any existing methods in Ruby to clean up your code? We were able to use .map to slightly shorten our non-destructive method. How readable is your solution? Did you and your pair choose descriptive variable names? I think our solution is very simple and easy to read. Variable names were already included in the prepared my_solution file, so we went with those. What is the difference between destructive and non-destructive methods in your own words? Destructive methods permanently alter the object they're passed on, whereas non-destructive methods leave the original object intact and return a wholly new object. =end
mit
razsilev/TelerikAcademy_Homework
High-Quality_Code/HQC-Exam-2014-Morning-Send/Computers-problem/Niki/Ram/RamMemory.cs
438
namespace ComputerBuildingSystem.Ram { public class RamMemory : IRamMemory { private int value; public RamMemory(int amount) { this.Amount = amount; } public int Amount { get; set; } public void SaveValue(int newValue) { this.value = newValue; } public int LoadValue() { return this.value; } } }
mit
mattsnider/html5-game-engine
src/snake/main.js
408
// todo: generify this... probably a game controller of some kind. (function() { 'use strict'; var game = new GameSnake(); game.start(); // todo: move this into a game controller system $(document).keydown(function(e) { if (game.setKey(e.keyCode)) { e.preventDefault(); } }); $(document).keyup(function(e) { if (game.setKey(0)) { e.preventDefault(); } }); }());
mit
SciresM/3DS-Builder
3DS Builder/Properties/Settings.Designer.cs
1069
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace _3DS_Builder.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
mit
jtuds/wordstart-theme
gruntfile.js
7869
module.exports = function(grunt) { // To support SASS/SCSS or Stylus, just install // the appropriate grunt package and it will be automatically included // in the build process, Sass is included by default: // // * for SASS/SCSS support, run `npm install --save-dev grunt-contrib-sass` // * for Stylus/Nib support, `npm install --save-dev grunt-contrib-stylus` var npmDependencies = require('./package.json').devDependencies; var hasSass = npmDependencies['grunt-sass'] !== undefined; var environment = "james"; if (environment == "james") { grunt.initConfig({ path: { assets: 'assets', src: 'src', dist: 'dist', sass: '<%= path.assets %>/css', js: '<%= path.assets %>/js', images: '<%= path.assets %>/images', fonts: '<%= path.assets %>/fonts', }, // Watches for changes and runs tasks watch : { sass : { files : ['<%= path.sass %>/*.scss', '<%= path.sass %>/**/*.scss'], tasks : (hasSass) ? ['sass:dev', 'autoprefixer'] : null, options : { livereload : true, sourceMap : true } }, js : { files : ['assets/js/**/*.js'], tasks : ['jshint', 'uglicat'], options : { livereload : true } }, php : { files : ['**/*.php'], options : { livereload : true } } }, // JsHint your javascript jshint : { all : ['js/*.js', '!js/modernizr.js', '!js/*.min.js', '!js/vendor/**/*.js'], options : { browser: true, curly: false, eqeqeq: false, eqnull: true, expr: true, immed: true, newcap: true, noarg: true, smarttabs: true, sub: true, undef: false } }, // Dev and production build for sass sass : { production : { files : [ { src : ['**/*.scss', '!**/_*.scss'], cwd : 'assets/css', dest : 'dist/css', ext : '.css', expand : true } ], options : { style : 'compressed' } }, dev : { files : [ { src : ['**/*.scss', '!**/_*.scss'], cwd : 'assets/css', dest : 'dist/css', ext : '.css', expand : true } ], options : { style : 'expanded' } } }, // Image min imagemin : { production : { files : [ { expand: true, cwd: 'assets/images', src: '**/*.{png,jpg,jpeg}', dest: 'dist/images' } ] } }, // SVG min svgmin: { options: { plugins: [{ removeViewBox: false, collapseGroups: false }, { removeUnknownsAndDefaults: false }] }, dist: { files: [{ expand: true, cwd: '<%= path.images %>', src: ['*.svg'], dest: '<%= path.dist %>/images', ext: '.svg' }] } }, grunticon: { icons: { files: [{ expand: true, cwd: '<%= path.images %>', src : ['*.svg'], dest: '<%= path.dist %>/images' }], options: { cssprefix: '.icon--' } } }, // Minify JS uglify: { js: { files: [ { expand:true, cwd: 'assets/js', src: ['**/*.js'], dest: 'dist/js' }] } }, // Concat JS concat: { dist: { src: ['dist/js/*.js', '!dist/js/global.js'], dest: 'dist/js/scripts.js', } }, // Autoprefixer autoprefixer: { single_file: { flatten : true, src: 'dist/css/style.css', dest: 'dist/css/style.css' } }, cssmin: { options: { shorthandCompacting: false, roundingPrecision: -1 }, target: { files: { 'dist/css/style.css': ['dist/css/style.css'] } } }, // Modernizr build modernizr: { dist: { // [REQUIRED] Path to the build you're using for development. "devFile" : "bower_components/modernizr/modernizr.js", // Path to save out the built file. "outputFile" : "assets/js/modernizr-custom.js", // Based on default settings on http://modernizr.com/download/ "extra" : { "shiv" : true, "printshiv" : false, "load" : true, "mq" : true, "cssclasses" : true }, // Based on default settings on http://modernizr.com/download/ "extensibility" : { "addtest" : false, "prefixed" : false, "teststyles" : false, "testprops" : false, "testallprops" : false, "hasevents" : false, "prefixes" : false, "domprefixes" : false, "cssclassprefix": "" }, // By default, source is uglified before saving "uglify" : true, // Define any tests you want to implicitly include. "tests" : [], // By default, this task will crawl your project for references to Modernizr tests. // Set to false to disable. "parseFiles" : true, // When parseFiles = true, this task will crawl all *.js, *.css, *.scss and *.sass files, // except files that are in node_modules/. // You can override this by defining a "files" array below. // "files" : { // "src": [] // }, // This handler will be passed an array of all the test names passed to the Modernizr API, and will run after the API call has returned // "handler": function (tests) {}, // When parseFiles = true, matchCommunityTests = true will attempt to // match user-contributed tests. "matchCommunityTests" : false, // Have custom Modernizr tests? Add paths to their location here. "customTests" : [] } }, // Move bower components to desired directories bowercopy: { options: { srcPrefix: 'bower_components' }, scripts: { options: { destPrefix: 'assets' }, files: { 'js/modernizr.js': 'modernizr/modernizr.js', 'css/compass': 'compass-mixins/lib' } } } }); // Uglify and concat grunt.registerTask("uglicat", ["uglify", "concat"]) // Default task grunt.registerTask('default', ['watch']); // Build task grunt.registerTask('build', function() { var arr = ['jshint']; if (hasSass) { arr.push('sass:production'); } if (hasStylus) { arr.push('stylus:production'); } arr.push('autoprefixer', 'cssmin', 'imagemin:production', 'svgmin:production', 'requirejs:production', 'uglify', 'concat', 'modernizr:dist'); return arr; }); // Template Setup Task grunt.registerTask('setup', function() { var arr = []; if (hasSass) { arr.push['sass:dev']; } if (hasStylus) { arr.push('stylus:dev'); } arr.push('bower-install'); }); // Load up tasks grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-imagemin'); grunt.loadNpmTasks('grunt-svgmin'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks("grunt-modernizr"); grunt.loadNpmTasks('grunt-bowercopy'); grunt.loadNpmTasks('grunt-grunticon'); // Run bower install grunt.registerTask('bower-install', function() { var done = this.async(); var bower = require('bower').commands; bower.install().on('end', function(data) { done(); }).on('data', function(data) { console.log(data); }).on('error', function(err) { console.error(err); done(); }); }); } else if (environment == "steve") { } };
mit
PhilAndrew/JumpMicro
JMCloner/src/main/resources/korolev.js
9686
(function(global) { global.Korolev = (function() { var root = null, els = null, addHandler = null, removeHandler = null, scheduledAddHandlerItems = [], formDataProgressHandler = null, renderNum = 0, rootListeners = [], listenFun = null, historyHandler = null, initialPath = global.location.pathname; function scheduleAddHandler(element) { if (!addHandler) return; if (scheduledAddHandlerItems.length == 0) { setTimeout(function() { scheduledAddHandlerItems.forEach(addHandler); scheduledAddHandlerItems.length = 0; }, 0); } scheduledAddHandlerItems.push(element); } return { SetRenderNum: function(n) { renderNum = n; }, RegisterRoot: function(rootNode) { function aux(prefix, node) { var children = node.childNodes; for (var i = 0; i < children.length; i++) { var child = children[i]; var id = prefix + '_' + i; child.vId = id; els[id] = child; aux(id, child); } } root = rootNode; els = { "0": rootNode }; aux("0", rootNode); }, CleanRoot: function() { while (root.children.length > 0) root.removeChild(root.children[0]); }, RegisterGlobalAddHandler: function(f) { addHandler = f; }, RegisterFormDataProgressHandler: function(f) { formDataProgressHandler = f; }, RegisterGlobalRemoveHandler: function(f) { removeHandler = f; }, RegisterGlobalEventHandler: function(eventHandler) { listenFun = function(name, preventDefault) { var listener = function(event) { if (event.target.vId) { if (preventDefault) { event.preventDefault(); } eventHandler(renderNum + ':' + event.target.vId + ':' + event.type); } } root.addEventListener(name, listener); rootListeners.push({ 'listener': listener, 'type': name }); } listenFun('submit', true); }, UnregisterGlobalEventHandler: function() { rootListeners.forEach(function(item) { root.removeEventListener(item.type, item.listener); }); listenFun = null; rootListeners.length = 0; }, ListenEvent: function(type, preventDefault) { listenFun(type, preventDefault); }, Create: function(id, childId, tag) { var parent = els[id], child = els[childId], newElement; if (!parent) return; newElement = document.createElement(tag); newElement.vId = childId; scheduleAddHandler(newElement); if (child && child.parentNode == parent) { parent.replaceChild(newElement, child); } else { parent.appendChild(newElement); } els[childId] = newElement; }, CreateText: function(id, childId, text) { var parent = els[id], child = els[childId], newElement; if (!parent) return; newElement = document.createTextNode(text); newElement.vId = childId; if (child && child.parentNode == parent) { parent.replaceChild(newElement, child); } else { parent.appendChild(newElement); } els[childId] = newElement; }, Remove: function(id, childId) { var parent = els[id], child = els[childId]; if (!parent) return; if (child) { if (removeHandler) removeHandler(child); parent.removeChild(child); } }, ExtractProperty: function(id, propertyName) { var element = els[id]; return element[propertyName]; }, SetAttr: function(id, name, value, isProperty) { var element = els[id]; if (isProperty) element[name] = value else element.setAttribute(name, value); }, RemoveAttr: function(id, name, isProperty) { var element = els[id]; if (isProperty) element[name] = undefined else element.removeAttribute(name); }, RegisterHistoryHandler: function(handler) { global.addEventListener('popstate', historyHandler = function(event) { if (event.state === null) handler(initialPath); else handler(event.state); }); }, UnregisterHistoryHandler: function() { if (historyHandler !== null) { global.removeEventListener('popstate', historyHandler); historyHandler = null; } }, ChangePageUrl: function(path) { console.log(path); if (path !== global.location.pathname) global.history.pushState(path, '', path); }, UploadForm: function(id, descriptor) { var form = els[id]; var formData = new FormData(form); var request = new XMLHttpRequest(); var deviceId = getCookie('device'); var uri = KorolevServerRootPath + 'bridge' + '/' + deviceId + '/' + KorolevSessionId + '/form-data' + '/' + descriptor; request.open("POST", uri, true); request.upload.onprogress = function(event) { var arg = [descriptor, event.loaded, event.total].join(':'); formDataProgressHandler(arg); } request.send(formData); return; } } })(); global.document.addEventListener("DOMContentLoaded", function() { var deviceId = getCookie('device'); var root = global.document.body; var loc = global.location; global.Korolev.RegisterRoot(root); function initializeBridgeWs() { var uri, ws; if (loc.protocol === "https:") uri = "wss://"; else uri = "ws://"; uri += loc.host + KorolevServerRootPath + 'bridge/web-socket' + '/' + deviceId + '/' + KorolevSessionId; console.log('Try to open connection to ' + uri + ' using WebSocket'); ws = new WebSocket(uri); ws.addEventListener('open', onOpen); global.Korolev.connection = ws; Bridge.webSocket(ws).catch(function(errorEvent) { // Try to reconnect after 2s setTimeout(initializeBridgeLongPolling, 1); }); } function initializeBridgeLongPolling() { var uriPrefix = loc.protocol + "//" + loc.host + KorolevServerRootPath + 'bridge/long-polling' + '/' + deviceId + '/' + KorolevSessionId + '/'; console.log('Try to open connection to ' + uriPrefix + ' using long polling'); function lpSubscribe(target, firstTime) { var request = new XMLHttpRequest(); request.addEventListener('readystatechange', function() { if (request.readyState === 4) { switch (request.status) { case 200: if (firstTime) { var event = new Event('open'); target.dispatchEvent(event); } var event = new MessageEvent('message', { 'data': request.responseText }); target.dispatchEvent(event); break; case 410: var event = new Close('close'); target.dispatchEvent(event); break; case 400: var event = new ErrorEvent('error', { error: new Error(request.responseText), message: request.responseText }); target.dispatchEvent(event); break; } lpSubscribe(target); } }); request.open('GET', uriPrefix + 'subscribe', true); request.send(null); } function lpPublish(target, message) { var request = new XMLHttpRequest(); request.addEventListener('readystatechange', function() { if (request.readyState === 4) { switch (request.status) { case 400: var event = new ErrorEvent('error', { error: new Error(request.responseText), message: request.responseText, }); target.dispatchEvent(event); break; } } }); request.open('POST', uriPrefix + 'publish', true); request.setRequestHeader("Content-Type", "application/json"); request.send(message); } var fakeWs = global.document.createDocumentFragment() global.Korolev.connection = fakeWs; fakeWs.send = function(message) { lpPublish(fakeWs, message); } fakeWs.addEventListener('open', onOpen); Bridge.webSocket(fakeWs).catch(function(errorEvent) { // Try to reconnect after 2s setTimeout(initializeBridgeWs, 2000); }); lpSubscribe(fakeWs, true); } function onOpen(event) { console.log("Connection opened."); event.target.addEventListener('close', onClose); } function onClose(event) { Korolev.UnregisterGlobalEventHandler(); Korolev.UnregisterHistoryHandler(); console.log("Connection closed. Global event handler us unregistered. Try to reconnect."); initializeBridgeWs(); } initializeBridgeWs(); }); function getCookie(name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; } })(this);
mit
OskarStark/EasyAdminBundle
src/Form/Filter/Type/EntityFilterType.php
2746
<?php namespace EasyCorp\Bundle\EasyAdminBundle\Form\Filter\Type; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query\Expr; use Doctrine\ORM\QueryBuilder; use EasyCorp\Bundle\EasyAdminBundle\Form\Type\ComparisonType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * @author Yonel Ceruto <yonelceruto@gmail.com> */ class EntityFilterType extends FilterType { use FilterTypeTrait; /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'comparison_type_options' => ['type' => 'entity'], 'value_type' => EntityType::class, ]); } /** * {@inheritdoc} */ public function getParent(): string { return ChoiceFilterType::class; } /** * {@inheritdoc} */ public function filter(QueryBuilder $queryBuilder, FormInterface $form, array $metadata) { $alias = current($queryBuilder->getRootAliases()); $property = $metadata['property']; $paramName = static::createAlias($property); $multiple = $form->get('value')->getConfig()->getOption('multiple'); $data = $form->getData(); if ('association' === $metadata['dataType'] && $metadata['associationType'] & ClassMetadata::TO_MANY) { $assocAlias = static::createAlias($property); $queryBuilder->leftJoin(sprintf('%s.%s', $alias, $property), $assocAlias); if (0 === \count($data['value'])) { $queryBuilder->andWhere(sprintf('%s %s', $assocAlias, $data['comparison'])); } else { $orX = new Expr\Orx(); $orX->add(sprintf('%s %s (:%s)', $assocAlias, $data['comparison'], $paramName)); if ('NOT IN' === $data['comparison']) { $orX->add(sprintf('%s IS NULL', $assocAlias)); } $queryBuilder->andWhere($orX) ->setParameter($paramName, $data['value']); } } elseif (null === $data['value'] || ($multiple && 0 === \count($data['value']))) { $queryBuilder->andWhere(sprintf('%s.%s %s', $alias, $property, $data['comparison'])); } else { $orX = new Expr\Orx(); $orX->add(sprintf('%s.%s %s (:%s)', $alias, $property, $data['comparison'], $paramName)); if (ComparisonType::NEQ === $data['comparison']) { $orX->add(sprintf('%s.%s IS NULL', $alias, $property)); } $queryBuilder->andWhere($orX) ->setParameter($paramName, $data['value']); } } }
mit
rjz/hubbub
common/repository.go
761
package common import ( "encoding/json" "io/ioutil" "strings" ) type Repository struct { URL string `json:"url,omitempty"` urlPieces []string } func (r *Repository) urlFragment(n int) *string { if r.urlPieces == nil { r.urlPieces = strings.Split(r.URL, "/") } return &r.urlPieces[n] } func (r *Repository) Host() *string { return r.urlFragment(0) } func (r *Repository) Owner() *string { return r.urlFragment(1) } func (r *Repository) Name() *string { return r.urlFragment(2) } func LoadRepositories(filename string) (*[]Repository, error) { data, err := ioutil.ReadFile(filename) if err != nil { return nil, err } rs := []Repository{} if err := json.Unmarshal(data, &rs); err != nil { return nil, err } return &rs, nil }
mit
johanvandegriff/BoggleSolver
display.py
750
#!/usr/bin/python import sys import pickle if len(sys.argv) == 1: quit() file = pickle.load(open(sys.argv[1],'r')) #import the board board = file[0] size = len(board) score = 0; numwords = 0 if(len(file) > 1): words = file[1] for word in words: length = len(word) if length < 7: points = length - 3 elif length == 7: points = 5 else: points = 11 if points < 1: points = 1; print ("%2d" %(points)), word score += points numwords += 1 print "Word Count: " + str(numwords) print "Total Score: " + str(score) for x in range(size): for y in range(size): #for each board spot sys.stdout.write("%-2s" %(board[x][y])) #write the letter padded with spaces print #write a new row
mit
Insire/MvvmScarletToolkit
src/MvvmScarletToolkit.Wpf/Features/HtmlTextBlock/Enums/SymbolType.cs
164
namespace MvvmScarletToolkit.Wpf { internal enum SymbolType { Reserved, European, Symbol, Scientific, Shape } }
mit
imrancluster/bms
src/BMS/PublicBundle/PublicBundle.php
123
<?php namespace BMS\PublicBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PublicBundle extends Bundle { }
mit
webholics/node-trader
test/endpoints/boersennews.js
2243
(function() { var assertEquity, should; should = require('should'); assertEquity = function(equity, name) { var f, _i, _len, _ref, _results; should.exist(equity); equity.should.have.keys('name', 'isin', 'wkn', 'latestFacts', 'historicFacts'); if (name) { equity.name.should.equal(name); } equity.latestFacts.should.be.a('object'); equity.historicFacts.should.be.an.instanceOf(Array); _ref = equity.historicFacts; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { f = _ref[_i]; _results.push(f.should.be.a('object')); } return _results; }; describe('BoersennewsEndpoint', function() { var Endpoint, endpoint; Endpoint = require('../../lib/endpoints/boersennews.js'); endpoint = new Endpoint; describe('getEquityByIsin()', function() { it('should return null when no equity can be found', function(done) { return endpoint.getEquityByIsin('123456789foobar', function(err, equity) { if (err) { done(err); } should.not.exist(equity); return done(); }); }); return it('should return valid equity object when searching for DE0005140008', function(done) { return endpoint.getEquityByIsin('DE0005140008', function(err, equity) { if (err) { done(err); } assertEquity(equity, 'DEUTSCHE BANK'); return done(); }); }); }); return describe('crawlEquity()', function() { it('should raise error when URL is wrong', function(done) { return endpoint.crawlEquity('http://www.boersennews.de/markt/indizes/dax-performance-index-de0008469008/20735/profile', function(err, equity) { err.should.be.instanceOf(Error); return done(); }); }); return it('should return a valid equity object', function(done) { return endpoint.crawlEquity('http://www.boersennews.de/markt/aktien/adidas-ag-na-on-de000a1ewww0/36714349/fundamental', function(err, equity) { if (err) { done(err); } assertEquity(equity, 'ADIDAS'); return done(); }); }); }); }); }).call(this);
mit
angular/angularfire
samples/advanced/src/app/app.component.ts
692
import { ApplicationRef, Component, isDevMode } from '@angular/core'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; @Component({ selector: 'app-root', template: ` <h1>AngularFire kitchen sink (<a href="https://github.com/angular/angularfire/tree/master/samples/advanced"><code>samples/advanced</code></a>)</h1> <router-outlet></router-outlet> `, styles: [] }) export class AppComponent { title = 'sample'; constructor( appRef: ApplicationRef, ) { if (isDevMode()) { appRef.isStable.pipe( debounceTime(200), distinctUntilChanged(), ).subscribe(it => { console.log('isStable', it); }); } } }
mit
ArxOne/OneFilesystem
OneFilesystem/Protocols/File/FileProtocolFilesystem.cs
12957
#region OneFilesystem // OneFilesystem // (to rule them all... Or at least some...) // https://github.com/ArxOne/OneFilesystem // Released under MIT license http://opensource.org/licenses/MIT #endregion namespace ArxOne.OneFilesystem.Protocols.File { using System; using System.Collections.Generic; using System.IO; using System.Linq; using LanExchange.Network; using LanExchange.Network.Models; /// <summary> /// Default filesystem protocol /// </summary> public class FileProtocolFilesystem : IOneProtocolFilesystem { private enum NodeType { LocalComputer, Server, Default, ServersRoot } /// <summary> /// Gets the protocol. /// If this is null, then the Handle() method has to be called to see if the file is handled here /// </summary> /// <value> /// The protocol. /// </value> public string Protocol { get { return "file"; } } /// <summary> /// Initializes a new instance of the <see cref="FileProtocolFilesystem"/> class. /// </summary> /// <param name="parameters">The parameters.</param> public FileProtocolFilesystem(OneFilesystemParameters parameters) { } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } /// <summary> /// Indicates if this filesystem handles the given protocol. /// </summary> /// <param name="entryPath">The entry path.</param> /// <returns></returns> public bool Handle(OnePath entryPath) { return entryPath.Protocol == Protocol; } /// <summary> /// Gets the type of the node. /// </summary> /// <param name="entryPath">The entry path.</param> /// <returns></returns> private static NodeType GetNodeType(OnePath entryPath) { if (entryPath.Path.Count > 0) return NodeType.Default; if (string.IsNullOrEmpty(entryPath.Host)) return NodeType.ServersRoot; if (IsLocalhost(entryPath)) return NodeType.LocalComputer; return NodeType.Server; } /// <summary> /// Determines whether the specified entry path is localhost. /// </summary> /// <param name="entryPath">The entry path.</param> /// <returns></returns> private static bool IsLocalhost(OnePath entryPath) { // TODO a real identification for localhost return entryPath.Host == "localhost"; } /// <summary> /// Gets the local path. /// </summary> /// <param name="entryPath">The entry path.</param> /// <returns></returns> private static string GetLocalPath(OnePath entryPath) { var localPath = string.Join(Path.DirectorySeparatorChar.ToString(), entryPath.Path); if (IsLocalhost(entryPath)) return localPath; return string.Format("{0}{0}{1}{0}{2}", Path.DirectorySeparatorChar, entryPath.Host, localPath); } /// <summary> /// Enumerates the entries. /// </summary> /// <param name="directoryPath">A directory path to get listing from</param> /// <returns> /// A list, or null if the directory is not found (if the directoryPath points to a file, an empty list is returned) /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public IEnumerable<OneEntryInformation> GetChildren(OnePath directoryPath) { switch (GetNodeType(directoryPath)) { case NodeType.LocalComputer: return GetLocalComputerChildren(directoryPath); case NodeType.Default: return GetDefaultChildren(directoryPath); case NodeType.ServersRoot: return GetServers(directoryPath); case NodeType.Server: return GetServerShares(directoryPath); default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Creates the entry information. /// </summary> /// <param name="path">The path.</param> /// <param name="localPath">The local path to speed up things.</param> /// <param name="isDirectory">if set to <c>true</c> [is directory].</param> /// <returns></returns> private static OneEntryInformation CreateEntryInformation(OnePath path, string localPath, bool isDirectory) { // -- directory if (isDirectory) { var directoryInfo = new DirectoryInfo(localPath); return new OneEntryInformation(path, true, null, directoryInfo.CreationTimeUtc, directoryInfo.LastWriteTimeUtc, directoryInfo.LastAccessTimeUtc); } // -- file var fileInfo = new FileInfo(localPath); return new OneEntryInformation(path, false, fileInfo.Length, fileInfo.CreationTimeUtc, fileInfo.LastWriteTimeUtc, fileInfo.LastAccessTimeUtc); } /// <summary> /// Enumerates the local computer drives. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns></returns> private static IEnumerable<OneEntryInformation> GetLocalComputerChildren(OnePath directoryPath) { return DriveInfo.GetDrives().Select(d => CreateEntryInformation(directoryPath + d.Name, d.Name, true)); } /// <summary> /// Gets the network servers. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns></returns> private static IEnumerable<OneEntryInformation> GetServers(OnePath directoryPath) { yield return new OneEntryInformation("file://localhost", true); var servers = NetworkHelper.NetServerEnum<ServerInfo100>(100, null, SoftwareTypes.SV_TYPE_ALL); foreach (var server in servers) { if (IsLocalhost(server.Name)) continue; yield return CreateEntryInformation(directoryPath + server.Name, server.Name, true); } } /// <summary> /// Determines whether the specified server name is localhost. /// </summary> /// <param name="serverName">Name of the server.</param> /// <returns></returns> private static bool IsLocalhost(string serverName) { // laziness can come in many flavors (but does the job) return string.Equals(serverName, Environment.MachineName, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Gets the server shares. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns></returns> private static IEnumerable<OneEntryInformation> GetServerShares(OnePath directoryPath) { var shares = NetworkHelper.NetShareEnum(directoryPath.Host); return shares.Select(s => CreateEntryInformation(directoryPath + s.netname, s.netname, true)); } /// <summary> /// Enumerates the entries using the defaut filesystem. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns></returns> private static IEnumerable<OneEntryInformation> GetDefaultChildren(OnePath directoryPath) { var localPath = GetLocalPath(directoryPath) + Path.DirectorySeparatorChar; if (File.Exists(localPath)) return new OneEntryInformation[0]; if (Directory.Exists(localPath)) { return Directory.EnumerateDirectories(localPath).Select(n => CreateEntryInformation(directoryPath + Path.GetFileName(n), n, true)) .Union(Directory.EnumerateFiles(localPath).Select(n => CreateEntryInformation(directoryPath + Path.GetFileName(n), n, false))); } return null; } /// <summary> /// Gets the information about the referenced file. /// </summary> /// <param name="entryPath">A file path to get information about</param> /// <returns> /// Information or null if entry is not found /// </returns> public OneEntryInformation GetInformation(OnePath entryPath) { var localPath = GetLocalPath(entryPath); if (Directory.Exists(localPath)) return CreateEntryInformation(entryPath, localPath, true); if (File.Exists(localPath)) return CreateEntryInformation(entryPath, localPath, false); return null; } /// <summary> /// Opens file for reading. /// </summary> /// <param name="filePath">The file path.</param> /// <returns> /// A readable stream, or null if the file does not exist /// </returns> public Stream OpenRead(OnePath filePath) { var localPath = GetLocalPath(filePath); if (File.Exists(localPath)) return File.OpenRead(localPath); return null; } /// <summary> /// Deletes the specified file or directory (does not recurse directories). /// </summary> /// <param name="entryPath"></param> /// <returns> /// true is entry was successfully deleted /// </returns> public bool Delete(OnePath entryPath) { var localPath = GetLocalPath(entryPath); if (File.Exists(localPath)) return DeleteFile(localPath); if (Directory.Exists(localPath)) return DeleteDirectory(localPath); return false; } /// <summary> /// Deletes the file. /// </summary> /// <param name="localPath">The local path.</param> /// <returns></returns> private static bool DeleteFile(string localPath) { try { File.Delete(localPath); return true; } catch (DirectoryNotFoundException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } /// <summary> /// Deletes the directory. /// </summary> /// <param name="localPath">The local path.</param> /// <returns></returns> private static bool DeleteDirectory(string localPath) { try { Directory.Delete(localPath); return true; } catch (DirectoryNotFoundException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } /// <summary> /// Creates the file and returns a writable stream. /// </summary> /// <param name="filePath"></param> /// <returns> /// A writable stream or null if creation fails (entry exists or path not found) /// </returns> public Stream CreateFile(OnePath filePath) { var localPath = GetLocalPath(filePath); if (Directory.Exists(localPath) || File.Exists(localPath)) return null; if (!Directory.Exists(GetLocalPath(filePath.GetParent()))) return null; return File.Create(localPath); } /// <summary> /// Creates the directory. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns> /// true if directory was created /// </returns> public bool CreateDirectory(OnePath directoryPath) { var localPath = GetLocalPath(directoryPath); if (Directory.Exists(localPath) || File.Exists(localPath)) return false; if (!Directory.Exists(GetLocalPath(directoryPath.GetParent()))) return false; try { Directory.CreateDirectory(localPath); return true; } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } } }
mit
hannahhoward/angular
modules/@angular/compiler/test/css/parser_spec.ts
22399
import { ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach } from '@angular/core/testing/testing_internal'; import {BaseException} from '../../src/facade/exceptions'; import { ParsedCssResult, CssParser, BlockType, CssSelectorRuleAST, CssKeyframeRuleAST, CssKeyframeDefinitionAST, CssBlockDefinitionRuleAST, CssMediaQueryRuleAST, CssBlockRuleAST, CssInlineRuleAST, CssStyleValueAST, CssSelectorAST, CssDefinitionAST, CssStyleSheetAST, CssRuleAST, CssBlockAST, CssParseError } from '@angular/compiler/src/css/parser'; import {CssLexer} from '@angular/compiler/src/css/lexer'; export function assertTokens(tokens, valuesArr) { for (var i = 0; i < tokens.length; i++) { expect(tokens[i].strValue == valuesArr[i]); } } export function main() { describe('CssParser', () => { function parse(css): ParsedCssResult { var lexer = new CssLexer(); var scanner = lexer.scan(css); var parser = new CssParser(scanner, 'some-fake-file-name.css'); return parser.parse(); } function makeAST(css): CssStyleSheetAST { var output = parse(css); var errors = output.errors; if (errors.length > 0) { throw new BaseException(errors.map((error: CssParseError) => error.msg).join(', ')); } return output.ast; } it('should parse CSS into a stylesheet AST', () => { var styles = ` .selector { prop: value123; } `; var ast = makeAST(styles); expect(ast.rules.length).toEqual(1); var rule = <CssSelectorRuleAST>ast.rules[0]; var selector = rule.selectors[0]; expect(selector.strValue).toEqual('.selector'); var block: CssBlockAST = rule.block; expect(block.entries.length).toEqual(1); var definition = <CssDefinitionAST>block.entries[0]; expect(definition.property.strValue).toEqual('prop'); var value = <CssStyleValueAST>definition.value; expect(value.tokens[0].strValue).toEqual('value123'); }); it('should parse mutliple CSS selectors sharing the same set of styles', () => { var styles = ` .class, #id, tag, [attr], key + value, * value, :-moz-any-link { prop: value123; } `; var ast = makeAST(styles); expect(ast.rules.length).toEqual(1); var rule = <CssSelectorRuleAST>ast.rules[0]; expect(rule.selectors.length).toBe(7); assertTokens(rule.selectors[0].tokens, [".", "class"]); assertTokens(rule.selectors[1].tokens, ["#", "id"]); assertTokens(rule.selectors[2].tokens, ["tag"]); assertTokens(rule.selectors[3].tokens, ["[", "attr", "]"]); assertTokens(rule.selectors[4].tokens, ["key", " ", "+", " ", "value"]); assertTokens(rule.selectors[5].tokens, ["*", " ", "value"]); assertTokens(rule.selectors[6].tokens, [":", "-moz-any-link"]); var style1 = <CssDefinitionAST>rule.block.entries[0]; expect(style1.property.strValue).toEqual("prop"); assertTokens(style1.value.tokens, ["value123"]); }); it('should parse keyframe rules', () => { var styles = ` @keyframes rotateMe { from { transform: rotate(-360deg); } 50% { transform: rotate(0deg); } to { transform: rotate(360deg); } } `; var ast = makeAST(styles); expect(ast.rules.length).toEqual(1); var rule = <CssKeyframeRuleAST>ast.rules[0]; expect(rule.name.strValue).toEqual('rotateMe'); var block = <CssBlockAST>rule.block; var fromRule = <CssKeyframeDefinitionAST>block.entries[0]; expect(fromRule.name.strValue).toEqual('from'); var fromStyle = <CssDefinitionAST>(<CssBlockAST>fromRule.block).entries[0]; expect(fromStyle.property.strValue).toEqual('transform'); assertTokens(fromStyle.value.tokens, ['rotate', '(', '-360', 'deg', ')']); var midRule = <CssKeyframeDefinitionAST>block.entries[1]; expect(midRule.name.strValue).toEqual('50%'); var midStyle = <CssDefinitionAST>(<CssBlockAST>midRule.block).entries[0]; expect(midStyle.property.strValue).toEqual('transform'); assertTokens(midStyle.value.tokens, ['rotate', '(', '0', 'deg', ')']); var toRule = <CssKeyframeDefinitionAST>block.entries[2]; expect(toRule.name.strValue).toEqual('to'); var toStyle = <CssDefinitionAST>(<CssBlockAST>toRule.block).entries[0]; expect(toStyle.property.strValue).toEqual('transform'); assertTokens(toStyle.value.tokens, ['rotate', '(', '360', 'deg', ')']); }); it('should parse media queries into a stylesheet AST', () => { var styles = ` @media all and (max-width:100px) { .selector { prop: value123; } } `; var ast = makeAST(styles); expect(ast.rules.length).toEqual(1); var rule = <CssMediaQueryRuleAST>ast.rules[0]; assertTokens(rule.query, ['all', 'and', '(', 'max-width', ':', '100', 'px', ')']); var block = <CssBlockAST>rule.block; expect(block.entries.length).toEqual(1); var rule2 = <CssSelectorRuleAST>block.entries[0]; expect(rule2.selectors[0].strValue).toEqual('.selector'); var block2 = <CssBlockAST>rule2.block; expect(block2.entries.length).toEqual(1); }); it('should parse inline CSS values', () => { var styles = ` @import url('remote.css'); @charset "UTF-8"; @namespace ng url(http://angular.io/namespace/ng); `; var ast = makeAST(styles); var importRule = <CssInlineRuleAST>ast.rules[0]; expect(importRule.type).toEqual(BlockType.Import); assertTokens(importRule.value.tokens, ["url", "(", "remote", ".", "css", ")"]); var charsetRule = <CssInlineRuleAST>ast.rules[1]; expect(charsetRule.type).toEqual(BlockType.Charset); assertTokens(charsetRule.value.tokens, ["UTF-8"]); var namespaceRule = <CssInlineRuleAST>ast.rules[2]; expect(namespaceRule.type).toEqual(BlockType.Namespace); assertTokens(namespaceRule.value.tokens, ["ng", "url", "(", "http://angular.io/namespace/ng", ")"]); }); it('should parse CSS values that contain functions and leave the inner function data untokenized', () => { var styles = ` .class { background: url(matias.css); animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); height: calc(100% - 50px); background-image: linear-gradient( 45deg, rgba(100, 0, 0, 0.5), black ); } `; var ast = makeAST(styles); expect(ast.rules.length).toEqual(1); var defs = (<CssSelectorRuleAST>ast.rules[0]).block.entries; expect(defs.length).toEqual(4); assertTokens((<CssDefinitionAST>defs[0]).value.tokens, ['url', '(', 'matias.css', ')']); assertTokens((<CssDefinitionAST>defs[1]).value.tokens, ['cubic-bezier', '(', '0.755, 0.050, 0.855, 0.060', ')']); assertTokens((<CssDefinitionAST>defs[2]).value.tokens, ['calc', '(', '100% - 50px', ')']); assertTokens((<CssDefinitionAST>defs[3]).value.tokens, ['linear-gradient', '(', '45deg, rgba(100, 0, 0, 0.5), black', ')']); }); it('should parse un-named block-level CSS values', () => { var styles = ` @font-face { font-family: "Matias"; font-weight: bold; src: url(font-face.ttf); } @viewport { max-width: 100px; min-height: 1000px; } `; var ast = makeAST(styles); var fontFaceRule = <CssBlockRuleAST>ast.rules[0]; expect(fontFaceRule.type).toEqual(BlockType.FontFace); expect(fontFaceRule.block.entries.length).toEqual(3); var viewportRule = <CssBlockRuleAST>ast.rules[1]; expect(viewportRule.type).toEqual(BlockType.Viewport); expect(viewportRule.block.entries.length).toEqual(2); }); it('should parse multiple levels of semicolons', () => { var styles = ` ;;; @import url('something something') ;;;;;;;; ;;;;;;;; ;@font-face { ;src : url(font-face.ttf);;;;;;;; ;;;-webkit-animation:my-animation };;; @media all and (max-width:100px) {; .selector {prop: value123;}; ;.selector2{prop:1}} `; var ast = makeAST(styles); var importRule = <CssInlineRuleAST>ast.rules[0]; expect(importRule.type).toEqual(BlockType.Import); assertTokens(importRule.value.tokens, ["url", "(", "something something", ")"]); var fontFaceRule = <CssBlockRuleAST>ast.rules[1]; expect(fontFaceRule.type).toEqual(BlockType.FontFace); expect(fontFaceRule.block.entries.length).toEqual(2); var mediaQueryRule = <CssMediaQueryRuleAST>ast.rules[2]; assertTokens(mediaQueryRule.query, ['all', 'and', '(', 'max-width', ':', '100', 'px', ')']); expect(mediaQueryRule.block.entries.length).toEqual(2); }); it('should throw an error if an unknown @value block rule is parsed', () => { var styles = ` @matias { hello: there; } `; expect(() => { makeAST(styles); }).toThrowError(/^CSS Parse Error: The CSS "at" rule "@matias" is not allowed to used here/g); }); it('should parse empty rules', () => { var styles = ` .empty-rule { } .somewhat-empty-rule { /* property: value; */ } .non-empty-rule { property: value; } `; var ast = makeAST(styles); var rules = ast.rules; expect((<CssSelectorRuleAST>rules[0]).block.entries.length).toEqual(0); expect((<CssSelectorRuleAST>rules[1]).block.entries.length).toEqual(0); expect((<CssSelectorRuleAST>rules[2]).block.entries.length).toEqual(1); }); it('should parse the @document rule', () => { var styles = ` @document url(http://www.w3.org/), url-prefix(http://www.w3.org/Style/), domain(mozilla.org), regexp("https:.*") { /* CSS rules here apply to: - The page "http://www.w3.org/". - Any page whose URL begins with "http://www.w3.org/Style/" - Any page whose URL's host is "mozilla.org" or ends with ".mozilla.org" - Any page whose URL starts with "https:" */ /* make the above-mentioned pages really ugly */ body { color: purple; background: yellow; } } `; var ast = makeAST(styles); var rules = ast.rules; var documentRule = <CssBlockDefinitionRuleAST>rules[0]; expect(documentRule.type).toEqual(BlockType.Document); var rule = <CssSelectorRuleAST>documentRule.block.entries[0]; expect(rule.strValue).toEqual("body"); }); it('should parse the @page rule', () => { var styles = ` @page one { .selector { prop: value; } } @page two { .selector2 { prop: value2; } } `; var ast = makeAST(styles); var rules = ast.rules; var pageRule1 = <CssBlockDefinitionRuleAST>rules[0]; expect(pageRule1.strValue).toEqual("one"); expect(pageRule1.type).toEqual(BlockType.Page); var pageRule2 = <CssBlockDefinitionRuleAST>rules[1]; expect(pageRule2.strValue).toEqual("two"); expect(pageRule2.type).toEqual(BlockType.Page); var selectorOne = <CssSelectorRuleAST>pageRule1.block.entries[0]; expect(selectorOne.strValue).toEqual('.selector'); var selectorTwo = <CssSelectorRuleAST>pageRule2.block.entries[0]; expect(selectorTwo.strValue).toEqual('.selector2'); }); it('should parse the @supports rule', () => { var styles = ` @supports (animation-name: "rotate") { a:hover { animation: rotate 1s; } } `; var ast = makeAST(styles); var rules = ast.rules; var supportsRule = <CssBlockDefinitionRuleAST>rules[0]; assertTokens(supportsRule.query, ['(', 'animation-name', ':', 'rotate', ')']); expect(supportsRule.type).toEqual(BlockType.Supports); var selectorOne = <CssSelectorRuleAST>supportsRule.block.entries[0]; expect(selectorOne.strValue).toEqual('a:hover'); }); it('should collect multiple errors during parsing', () => { var styles = ` .class$value { something: something } @custom { something: something } #id { cool^: value } `; var output = parse(styles); expect(output.errors.length).toEqual(3); }); it('should recover from selector errors and continue parsing', () => { var styles = ` tag& { key: value; } .%tag { key: value; } #tag$ { key: value; } `; var output = parse(styles); var errors = output.errors; var ast = output.ast; expect(errors.length).toEqual(3); expect(ast.rules.length).toEqual(3); var rule1 = <CssSelectorRuleAST>ast.rules[0]; expect(rule1.selectors[0].strValue).toEqual("tag&"); expect(rule1.block.entries.length).toEqual(1); var rule2 = <CssSelectorRuleAST>ast.rules[1]; expect(rule2.selectors[0].strValue).toEqual(".%tag"); expect(rule2.block.entries.length).toEqual(1); var rule3 = <CssSelectorRuleAST>ast.rules[2]; expect(rule3.selectors[0].strValue).toEqual("#tag$"); expect(rule3.block.entries.length).toEqual(1); }); it('should throw an error when parsing invalid CSS Selectors', () => { var styles = '.class[[prop%=value}] { style: val; }'; var output = parse(styles); var errors = output.errors; expect(errors.length).toEqual(3); expect(errors[0].msg).toMatchPattern(/Unexpected character \[\[\] at column 0:7/g); expect(errors[1].msg).toMatchPattern(/Unexpected character \[%\] at column 0:12/g); expect(errors[2].msg).toMatchPattern(/Unexpected character \[}\] at column 0:19/g); }); it('should throw an error if an attribute selector is not closed properly', () => { var styles = '.class[prop=value { style: val; }'; var output = parse(styles); var errors = output.errors; expect(errors[0].msg).toMatchPattern(/Unbalanced CSS attribute selector at column 0:12/g); }); it('should throw an error if a pseudo function selector is not closed properly', () => { var styles = 'body:lang(en { key:value; }'; var output = parse(styles); var errors = output.errors; expect(errors[0].msg) .toMatchPattern(/Unbalanced pseudo selector function value at column 0:10/g); }); it('should raise an error when a semi colon is missing from a CSS style/pair that isn\'t the last entry', () => { var styles = `.class { color: red background: blue }`; var output = parse(styles); var errors = output.errors; expect(errors.length).toEqual(1); expect(errors[0].msg) .toMatchPattern( /The CSS key\/value definition did not end with a semicolon at column 1:15/g); }); it('should parse the inner value of a :not() pseudo-selector as a CSS selector', () => { var styles = `div:not(.ignore-this-div) { prop: value; }`; var output = parse(styles); var errors = output.errors; var ast = output.ast; expect(errors.length).toEqual(0); var rule1 = <CssSelectorRuleAST>ast.rules[0]; expect(rule1.selectors.length).toEqual(1); var selector = rule1.selectors[0]; assertTokens(selector.tokens, ['div', ':', 'not', '(', '.', 'ignore-this-div', ')']); }); it('should raise parse errors when CSS key/value pairs are invalid', () => { var styles = `.class { background color: value; color: value font-size; font-weight }`; var output = parse(styles); var errors = output.errors; expect(errors.length).toEqual(4); expect(errors[0].msg) .toMatchPattern( /Identifier does not match expected Character value \("color" should match ":"\) at column 1:19/g); expect(errors[1].msg) .toMatchPattern( /The CSS key\/value definition did not end with a semicolon at column 2:15/g); expect(errors[2].msg) .toMatchPattern(/The CSS property was not paired with a style value at column 3:8/g); expect(errors[3].msg) .toMatchPattern(/The CSS property was not paired with a style value at column 4:8/g); }); it('should recover from CSS key/value parse errors', () => { var styles = ` .problem-class { background color: red; color: white; } .good-boy-class { background-color: red; color: white; } `; var output = parse(styles); var ast = output.ast; expect(ast.rules.length).toEqual(2); var rule1 = <CssSelectorRuleAST>ast.rules[0]; expect(rule1.block.entries.length).toEqual(2); var style1 = <CssDefinitionAST>rule1.block.entries[0]; expect(style1.property.strValue).toEqual('background color'); assertTokens(style1.value.tokens, ['red']); var style2 = <CssDefinitionAST>rule1.block.entries[1]; expect(style2.property.strValue).toEqual('color'); assertTokens(style2.value.tokens, ['white']); }); it('should parse minified CSS content properly', () => { // this code was taken from the angular.io webpage's CSS code var styles = ` .is-hidden{display:none!important} .is-visible{display:block!important} .is-visually-hidden{height:1px;width:1px;overflow:hidden;opacity:0.01;position:absolute;bottom:0;right:0;z-index:1} .grid-fluid,.grid-fixed{margin:0 auto} .grid-fluid .c1,.grid-fixed .c1,.grid-fluid .c2,.grid-fixed .c2,.grid-fluid .c3,.grid-fixed .c3,.grid-fluid .c4,.grid-fixed .c4,.grid-fluid .c5,.grid-fixed .c5,.grid-fluid .c6,.grid-fixed .c6,.grid-fluid .c7,.grid-fixed .c7,.grid-fluid .c8,.grid-fixed .c8,.grid-fluid .c9,.grid-fixed .c9,.grid-fluid .c10,.grid-fixed .c10,.grid-fluid .c11,.grid-fixed .c11,.grid-fluid .c12,.grid-fixed .c12{display:inline;float:left} .grid-fluid .c1.grid-right,.grid-fixed .c1.grid-right,.grid-fluid .c2.grid-right,.grid-fixed .c2.grid-right,.grid-fluid .c3.grid-right,.grid-fixed .c3.grid-right,.grid-fluid .c4.grid-right,.grid-fixed .c4.grid-right,.grid-fluid .c5.grid-right,.grid-fixed .c5.grid-right,.grid-fluid .c6.grid-right,.grid-fixed .c6.grid-right,.grid-fluid .c7.grid-right,.grid-fixed .c7.grid-right,.grid-fluid .c8.grid-right,.grid-fixed .c8.grid-right,.grid-fluid .c9.grid-right,.grid-fixed .c9.grid-right,.grid-fluid .c10.grid-right,.grid-fixed .c10.grid-right,.grid-fluid .c11.grid-right,.grid-fixed .c11.grid-right,.grid-fluid .c12.grid-right,.grid-fixed .c12.grid-right{float:right} .grid-fluid .c1.nb,.grid-fixed .c1.nb,.grid-fluid .c2.nb,.grid-fixed .c2.nb,.grid-fluid .c3.nb,.grid-fixed .c3.nb,.grid-fluid .c4.nb,.grid-fixed .c4.nb,.grid-fluid .c5.nb,.grid-fixed .c5.nb,.grid-fluid .c6.nb,.grid-fixed .c6.nb,.grid-fluid .c7.nb,.grid-fixed .c7.nb,.grid-fluid .c8.nb,.grid-fixed .c8.nb,.grid-fluid .c9.nb,.grid-fixed .c9.nb,.grid-fluid .c10.nb,.grid-fixed .c10.nb,.grid-fluid .c11.nb,.grid-fixed .c11.nb,.grid-fluid .c12.nb,.grid-fixed .c12.nb{margin-left:0} .grid-fluid .c1.na,.grid-fixed .c1.na,.grid-fluid .c2.na,.grid-fixed .c2.na,.grid-fluid .c3.na,.grid-fixed .c3.na,.grid-fluid .c4.na,.grid-fixed .c4.na,.grid-fluid .c5.na,.grid-fixed .c5.na,.grid-fluid .c6.na,.grid-fixed .c6.na,.grid-fluid .c7.na,.grid-fixed .c7.na,.grid-fluid .c8.na,.grid-fixed .c8.na,.grid-fluid .c9.na,.grid-fixed .c9.na,.grid-fluid .c10.na,.grid-fixed .c10.na,.grid-fluid .c11.na,.grid-fixed .c11.na,.grid-fluid .c12.na,.grid-fixed .c12.na{margin-right:0} `; var output = parse(styles); var errors = output.errors; expect(errors.length).toEqual(0); var ast = output.ast; expect(ast.rules.length).toEqual(8); }); it('should parse a snippet of keyframe code from animate.css properly', () => { // this code was taken from the angular.io webpage's CSS code var styles = ` @charset "UTF-8"; /*! * animate.css -http://daneden.me/animate * Version - 3.5.1 * Licensed under the MIT license - http://opensource.org/licenses/MIT * * Copyright (c) 2016 Daniel Eden */ .animated { -webkit-animation-duration: 1s; animation-duration: 1s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } .animated.infinite { -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; } .animated.hinge { -webkit-animation-duration: 2s; animation-duration: 2s; } .animated.flipOutX, .animated.flipOutY, .animated.bounceIn, .animated.bounceOut { -webkit-animation-duration: .75s; animation-duration: .75s; } @-webkit-keyframes bounce { from, 20%, 53%, 80%, to { -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000); animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000); -webkit-transform: translate3d(0,0,0); transform: translate3d(0,0,0); } 40%, 43% { -webkit-animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); -webkit-transform: translate3d(0, -30px, 0); transform: translate3d(0, -30px, 0); } 70% { -webkit-animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); -webkit-transform: translate3d(0, -15px, 0); transform: translate3d(0, -15px, 0); } 90% { -webkit-transform: translate3d(0,-4px,0); transform: translate3d(0,-4px,0); } } `; var output = parse(styles); var errors = output.errors; expect(errors.length).toEqual(0); var ast = output.ast; expect(ast.rules.length).toEqual(6); var finalRule = <CssBlockRuleAST>ast.rules[ast.rules.length - 1]; expect(finalRule.type).toEqual(BlockType.Keyframes); expect(finalRule.block.entries.length).toEqual(4); }); }); }
mit
siftware/live-connect
src/Siftware/TokenStore/TokenStoreSession.php
1685
<?php /* * This file is part of the siftware/live-connect package. * * (c) 2014 Siftware <code@siftware.com> * * Author - Darren Beale @bealers * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Siftware\TokenStore; class TokenStoreSession implements TokenStore { private $tokenStoreSessionVar; public function __construct() { session_start(); $this->tokenStoreSessionVar = "swLiveConnect"; } public function getTokens() { if (!isset($_SESSION[$this->tokenStoreSessionVar])) { $_SESSION[$this->tokenStoreSessionVar] = array(); } return $_SESSION[$this->tokenStoreSessionVar]; } // -- public function saveTokens($tokens) { $saveTokens = array( 'access_token' => $tokens->access_token, 'refresh_token' => $tokens->refresh_token, 'token_expires' => (time() + (int) $tokens->expires_in) ); $_SESSION[$this->tokenStoreSessionVar] = $saveTokens; if (is_array($_SESSION[$this->tokenStoreSessionVar])) { return true; } else { return false; } } // -- public function deleteTokens() { unset($_SESSION[$this->tokenStoreSessionVar]); if (!isset($_SESSION[$this->tokenStoreSessionVar])) { return true; } else { return false; } } /** * @param string path $storeName */ public function setTokenStoreSessionVarName($storeName) { $this->tokenStoreSessionVar = $storeName; } }
mit
astrada/smartwishlistapp-android
app/src/main/java/net/smartwishlist/smartwishlistapp/ApiSignature.java
1369
package net.smartwishlist.smartwishlistapp; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.Locale; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class ApiSignature { private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final String HMAC_SHA_256 = "HmacSHA256"; public static String generateRequestSignature(String token, String payload, double timestamp) { if (token == null) { throw new NullPointerException("ApiSignature.generateRequestSignature: token cannot be null"); } try { String value = String.format(Locale.US, "%s%.3f", payload, timestamp); byte[] keyBytes = token.getBytes(UTF_8); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA_256); Mac mac = Mac.getInstance(HMAC_SHA_256); mac.init(signingKey); byte[] rawHmac = mac.doFinal(value.getBytes(UTF_8)); return toHex(rawHmac); } catch (Exception e) { throw new RuntimeException(e); } } public static double getTimestamp() { return System.currentTimeMillis() / AppConstants.ONE_SECOND_IN_MILLISECONDS; } private static String toHex(byte[] bytes) { return String.format("%064x", new BigInteger(1, bytes)); } }
mit
next-l/enju_nii
spec/dummy/config/initializers/devise.rb
9773
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| config.secret_key = 'cfb73aad651cfc020276d86a1370418674322f9191ea58045ffad5dbe066028f98f2cc14d0acbe0b25a46ae6a05c0c48d003a55b6137baf041ff384cb2d7a33f' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class with default "from" parameter. config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com" # Configure the class responsible to send e-mails. # config.mailer = "Devise::Mailer" # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # config.params_authenticatable = true # Tell if authentication through HTTP Basic Auth is enabled. False by default. # config.http_authenticatable = false # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. "Application" by default. # config.http_authentication_realm = "Application" # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = "3125870d8e124367f0d9acbd3ea99f180abc4deede5a2c7b449169713dc3cb6a1ef7518e823bcd208650c4d4da3a6894e07da1c527ba411820d6571c445c8c71" # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming his account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming his account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming his account. # config.confirm_within = 2.days # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, a valid remember token can be re-used between multiple browsers. # config.remember_across_browsers = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # :secure => true in order to force SSL only cookies. # config.cookie_options = {} # ==> Configuration for :validatable # Range for password length. Default is 6..128. # config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that # an one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 2.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper) # config.encryptor = :sha512 # ==> Configuration for :token_authenticatable # Defines name of the authentication token params key # config.token_authentication_key = :auth_token # If true, authentication through token does not store user in session and needs # to be supplied on each request. Useful if you are using the token as API token. # config.stateless_token = false # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Configure sign_out behavior. # Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope). # The default is true, which means any logout action will sign out all active scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The :"*/*" and "*/*" formats below is required to match Internet # Explorer requests. # config.navigational_formats = [:"*/*", "*/*", :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(:scope => :user).unshift :some_external_strategy # end end
mit
biola/profile-publisher
db/migrate/20140818154030_group_persons_to_memberships.rb
488
class GroupPersonsToMemberships < Mongoid::Migration def self.up Group.all.each do |group| if group["person_ids"].present? group["person_ids"].each do |p_id| if group.memberships.where(person_id: p_id).blank? group.memberships.new(person_id: p_id, order: group.memberships.map(&:order).max.to_i + 1) end end group["person_ids"] = [] group.save(validate: false) end end end def self.down end end
mit
djeppe/Simcoe
test/index.php
28
<?php echo "mumintrollet" ?>
mit
shadowinlife/biplatform
application/models/page_model.php
281
<?php /** * 页面操作 * * @author fefeding * @date 2014-12-21 */ class Page_model extends MY_Model { //获取页面 public function getById($id) { $sql = "select * from tbpageconfig where id=?"; return $this->dbHelper->select_row($sql, array($id)); } }
mit
Eelco81/server-test-project
Lib/Http/Src/HttpResponseEncoderTester.cpp
3182
#include "gmock/gmock.h" #include "HttpResponseEncoder.h" namespace { std::string Encode (HTTP::Response& inResponse) { HTTP::ResponseEncoder encoder; std::string result; encoder.Pipe ([&](const std::string& data) { result = data; }); encoder.Write (inResponse); return result; } } using TestParam = std::tuple<std::string, HTTP::Code, HTTP::Version>; class HttpResponseEncoderTester : public ::testing::TestWithParam<TestParam> {}; INSTANTIATE_TEST_CASE_P (HttpResponseEncoderTester, HttpResponseEncoderTester, ::testing::Values( std::make_tuple (std::string ("HTTP/1.0 200 OK"), HTTP::Code::OK, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 200 OK"), HTTP::Code::OK, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/1.0 201 Created"), HTTP::CREATED, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 201 Created"), HTTP::CREATED, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/1.0 202 Accepted"), HTTP::ACCEPTED, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 202 Accepted"), HTTP::Code::ACCEPTED, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/1.0 400 Bad Request"), HTTP::Code::BAD_REQUEST, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 400 Bad Request"), HTTP::Code::BAD_REQUEST, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/1.0 403 Forbidden"), HTTP::Code::FORBIDDEN, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 403 Forbidden"), HTTP::Code::FORBIDDEN, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/1.0 404 Not Found"), HTTP::Code::NOT_FOUND, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 404 Not Found"), HTTP::Code::NOT_FOUND, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/1.0 500 Internal Server Error"), HTTP::Code::INTERNAL_SERVER_ERROR, HTTP::Version::V10 ), std::make_tuple (std::string ("HTTP/1.1 500 Internal Server Error"), HTTP::Code::INTERNAL_SERVER_ERROR, HTTP::Version::V11 ), std::make_tuple (std::string ("HTTP/x.x 0 Unknown"), HTTP::Code::UNKNOWN_CODE, HTTP::Version::UNKNOWN_VERSION ) ) ); TEST_P (HttpResponseEncoderTester, BuildInitialLine) { HTTP::Response response (std::get<1> (GetParam ()), std::get<2> (GetParam ())); EXPECT_THAT ( Encode (response), ::testing::HasSubstr (std::get<0> (GetParam ()))); } TEST_P (HttpResponseEncoderTester, ContainsZeroContentLength) { HTTP::Response response (std::get<1> (GetParam ()), std::get<2> (GetParam ())); EXPECT_THAT ( Encode (response), ::testing::HasSubstr ("\r\ncontent-length: 0\r\n")); } TEST_P (HttpResponseEncoderTester, ContainsLastModified) { HTTP::Response response (std::get<1> (GetParam ()), std::get<2> (GetParam ())); EXPECT_THAT ( Encode (response), ::testing::HasSubstr ("\r\nlast-modified: ")); } TEST_P (HttpResponseEncoderTester, ContainsUserAgent) { HTTP::Response response (std::get<1> (GetParam ()), std::get<2> (GetParam ())); EXPECT_THAT ( Encode (response), ::testing::HasSubstr ("\r\nuser-agent: Unknown/0.0.1")); }
mit
udacity/FEF-Quiz-Angular-Module
app/scripts/app.js
187
'use strict'; /** * @ngdoc overview * @name newModuleQuizApp * @description * # newModuleQuizApp * * Main module of the application. */ angular .module('newModuleQuizApp', []);
mit
nhs0912/BOJ
src/Problems/P_2606.java
2437
package Problems; import java.io.*; import java.util.StringTokenizer; /** * 문제 번호 : 2606 * 문제 이름 : 바이러스 * 문제 주소 : https://www.acmicpc.net/problem/2606 */ class P_2606 { int[][] adjMatrix; boolean[] visited; int virusCnt = 0; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public void printArr(int[][] arr) { for (int i = 1; i < arr.length; i++) { for (int j = 1; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } public void printArr(boolean[][] arr) { for (int i = 1; i < arr.length; i++) { for (int j = 1; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } public void printArr(int[] arr) { for (int i = 1; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public void inputData() throws IOException { FileInputStream fis = new FileInputStream("test.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); //Computer Count int edgeCnt = Integer.parseInt(br.readLine());// Edge Count StringTokenizer st; adjMatrix = new int[N + 1][N + 1]; visited = new boolean[N + 1]; while (edgeCnt-- > 0) { st = new StringTokenizer(br.readLine()); int v1 = Integer.parseInt(st.nextToken()); int v2 = Integer.parseInt(st.nextToken()); adjMatrix[v1][v2] = 1; adjMatrix[v2][v1] = 1; } } public void DFS(int start) { visited[start]=true; for (int i = 1; i < adjMatrix.length; i++) { if (adjMatrix[start][i] == 1 && visited[i] == false) { virusInfected();// Increase virusCnt DFS(i); } } } public void virusInfected() { virusCnt++; } public void Solve() throws IOException { inputData(); DFS(1); System.out.println(virusCnt); } public static void main(String[] args) throws IOException { new P_2606().Solve(); } }
mit
MrScraty59/bit
application/controllers/Classes.php
2263
<?php class Classes extends CI_Controller { public function liste() { $data = Array(); $data['classes'] = $this->classe->getClasses(); $this->load->view('template/header'); $this->load->view('pages/classes/liste', $data); $this->load->view('template/footer'); } public function creer() { //Initialisation des données $data = Array(); $data["cours"] = $this->cour->getAll(); //Validation du formulaire $this->form_validation->set_rules('intitule', 'Intitulé', 'trim|xss_clean|encode_php_tags|required'); if ($this->input->post() && $this->form_validation->run()) { //Le formualire est valide, on va créer l'examen $classe = new StdClass(); $classe->intitule = $this->input->post('intitule'); $classe->coursIds = json_encode($this->input->post('coursIds')); $this->classe->add($classe); redirect(base_url('classes/liste')); } $this->load->view('template/header'); $this->load->view('pages/classes/creer', $data); $this->load->view('template/footer'); } public function delete($id = 0) { $this->classe->delete($id); redirect('classes/liste/'); } public function edit($id = 0) { //Initialisation des données $data = Array(); $data["classe"] = $this->classe->constructeur($id); $data["cours"] = $this->cour->getAll(); $this->load->view('template/header'); $this->load->view('pages/classes/edit', $data); $this->load->view('template/footer'); } public function listeEleves($id) { $data=array(); $liste = $this->user->getUserByidClasse($id); if(!empty($liste)) { foreach($liste as $a_user) { $note[$a_user->id]=$this->user->getNote($id, $a_user->id); } } $data['liste'] = $liste; $data['id'] = $id; $data['note'] = $note; $this->load->view('template/header'); $this->load->view('pages/classes/listeEleves', $data); $this->load->view('template/footer'); } } ?>
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_91/safe/CWE_91__POST__func_preg_replace__username-concatenation_simple_quote.php
1362
<?php /* Safe sample input : get the field UserData from the variable $_POST SANITIZE : use of preg_replace construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_POST['UserData']; $tainted = preg_replace('/\'/', '', $tainted); $query = "user[username='". $tainted . "']"; $xml = simplexml_load_file("users.xml");//file load echo "query : ". $query ."<br /><br />" ; $res=$xml->xpath($query);//execution print_r($res); echo "<br />" ; ?>
mit
cronelab/radroom
conversion/dcmtk/dcmrt/libsrc/drtcss.cc
29796
/* * * Copyright (C) 2008-2012, OFFIS e.V. and ICSMED AG, Oldenburg, Germany * Copyright (C) 2013-2015, J. Riesmeier, Oldenburg, Germany * All rights reserved. See COPYRIGHT file for details. * * Source file for class DRTChannelSourceSequence * * Generated automatically from DICOM PS 3.3-2015c * File created on 2015-12-07 16:29:33 * */ #include "dcmtk/config/osconfig.h" // make sure OS specific configuration is included first #include "dcmtk/dcmrt/seq/drtcss.h" // --- item class --- DRTChannelSourceSequence::Item::Item(const OFBool emptyDefaultItem) : EmptyDefaultItem(emptyDefaultItem), CodeMeaning(DCM_CodeMeaning), CodeValue(DCM_CodeValue), CodingSchemeDesignator(DCM_CodingSchemeDesignator), CodingSchemeVersion(DCM_CodingSchemeVersion), ContextGroupExtensionCreatorUID(DCM_ContextGroupExtensionCreatorUID), ContextGroupExtensionFlag(DCM_ContextGroupExtensionFlag), ContextGroupLocalVersion(DCM_ContextGroupLocalVersion), ContextGroupVersion(DCM_ContextGroupVersion), ContextIdentifier(DCM_ContextIdentifier), ContextUID(DCM_ContextUID), EquivalentCodeSequence(emptyDefaultItem /*emptyDefaultSequence*/), LongCodeValue(DCM_LongCodeValue), MappingResource(DCM_MappingResource), MappingResourceUID(DCM_MappingResourceUID), URNCodeValue(DCM_URNCodeValue) { } DRTChannelSourceSequence::Item::Item(const Item &copy) : EmptyDefaultItem(copy.EmptyDefaultItem), CodeMeaning(copy.CodeMeaning), CodeValue(copy.CodeValue), CodingSchemeDesignator(copy.CodingSchemeDesignator), CodingSchemeVersion(copy.CodingSchemeVersion), ContextGroupExtensionCreatorUID(copy.ContextGroupExtensionCreatorUID), ContextGroupExtensionFlag(copy.ContextGroupExtensionFlag), ContextGroupLocalVersion(copy.ContextGroupLocalVersion), ContextGroupVersion(copy.ContextGroupVersion), ContextIdentifier(copy.ContextIdentifier), ContextUID(copy.ContextUID), EquivalentCodeSequence(copy.EquivalentCodeSequence), LongCodeValue(copy.LongCodeValue), MappingResource(copy.MappingResource), MappingResourceUID(copy.MappingResourceUID), URNCodeValue(copy.URNCodeValue) { } DRTChannelSourceSequence::Item::~Item() { } DRTChannelSourceSequence::Item &DRTChannelSourceSequence::Item::operator=(const Item &copy) { if (this != &copy) { EmptyDefaultItem = copy.EmptyDefaultItem; CodeMeaning = copy.CodeMeaning; CodeValue = copy.CodeValue; CodingSchemeDesignator = copy.CodingSchemeDesignator; CodingSchemeVersion = copy.CodingSchemeVersion; ContextGroupExtensionCreatorUID = copy.ContextGroupExtensionCreatorUID; ContextGroupExtensionFlag = copy.ContextGroupExtensionFlag; ContextGroupLocalVersion = copy.ContextGroupLocalVersion; ContextGroupVersion = copy.ContextGroupVersion; ContextIdentifier = copy.ContextIdentifier; ContextUID = copy.ContextUID; EquivalentCodeSequence = copy.EquivalentCodeSequence; LongCodeValue = copy.LongCodeValue; MappingResource = copy.MappingResource; MappingResourceUID = copy.MappingResourceUID; URNCodeValue = copy.URNCodeValue; } return *this; } void DRTChannelSourceSequence::Item::clear() { if (!EmptyDefaultItem) { /* clear all DICOM attributes */ CodeValue.clear(); CodingSchemeDesignator.clear(); CodingSchemeVersion.clear(); CodeMeaning.clear(); LongCodeValue.clear(); URNCodeValue.clear(); EquivalentCodeSequence.clear(); ContextIdentifier.clear(); ContextUID.clear(); MappingResource.clear(); MappingResourceUID.clear(); ContextGroupVersion.clear(); ContextGroupExtensionFlag.clear(); ContextGroupLocalVersion.clear(); ContextGroupExtensionCreatorUID.clear(); } } OFBool DRTChannelSourceSequence::Item::isEmpty() { return CodeValue.isEmpty() && CodingSchemeDesignator.isEmpty() && CodingSchemeVersion.isEmpty() && CodeMeaning.isEmpty() && LongCodeValue.isEmpty() && URNCodeValue.isEmpty() && EquivalentCodeSequence.isEmpty() && ContextIdentifier.isEmpty() && ContextUID.isEmpty() && MappingResource.isEmpty() && MappingResourceUID.isEmpty() && ContextGroupVersion.isEmpty() && ContextGroupExtensionFlag.isEmpty() && ContextGroupLocalVersion.isEmpty() && ContextGroupExtensionCreatorUID.isEmpty(); } OFBool DRTChannelSourceSequence::Item::isValid() const { return !EmptyDefaultItem; } OFCondition DRTChannelSourceSequence::Item::read(DcmItem &item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { /* re-initialize object */ clear(); getAndCheckElementFromDataset(item, CodeValue, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, CodingSchemeDesignator, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, CodingSchemeVersion, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, CodeMeaning, "1", "1", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, LongCodeValue, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, URNCodeValue, "1", "1C", "ChannelSourceSequence"); EquivalentCodeSequence.read(item, "1-n", "3", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, ContextIdentifier, "1", "3", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, ContextUID, "1", "3", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, MappingResource, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, MappingResourceUID, "1", "3", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, ContextGroupVersion, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, ContextGroupExtensionFlag, "1", "3", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, ContextGroupLocalVersion, "1", "1C", "ChannelSourceSequence"); getAndCheckElementFromDataset(item, ContextGroupExtensionCreatorUID, "1", "1C", "ChannelSourceSequence"); result = EC_Normal; } return result; } OFCondition DRTChannelSourceSequence::Item::write(DcmItem &item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = EC_Normal; addElementToDataset(result, item, new DcmShortString(CodeValue), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmShortString(CodingSchemeDesignator), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmShortString(CodingSchemeVersion), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmLongString(CodeMeaning), "1", "1", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmUnlimitedCharacters(LongCodeValue), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmUniversalResourceIdentifierOrLocator(URNCodeValue), "1", "1C", "ChannelSourceSequence"); if (result.good()) result = EquivalentCodeSequence.write(item, "1-n", "3", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmCodeString(ContextIdentifier), "1", "3", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmUniqueIdentifier(ContextUID), "1", "3", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmCodeString(MappingResource), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmUniqueIdentifier(MappingResourceUID), "1", "3", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmDateTime(ContextGroupVersion), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmCodeString(ContextGroupExtensionFlag), "1", "3", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmDateTime(ContextGroupLocalVersion), "1", "1C", "ChannelSourceSequence"); addElementToDataset(result, item, new DcmUniqueIdentifier(ContextGroupExtensionCreatorUID), "1", "1C", "ChannelSourceSequence"); } return result; } OFCondition DRTChannelSourceSequence::Item::getCodeMeaning(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(CodeMeaning, value, pos); } OFCondition DRTChannelSourceSequence::Item::getCodeValue(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(CodeValue, value, pos); } OFCondition DRTChannelSourceSequence::Item::getCodingSchemeDesignator(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(CodingSchemeDesignator, value, pos); } OFCondition DRTChannelSourceSequence::Item::getCodingSchemeVersion(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(CodingSchemeVersion, value, pos); } OFCondition DRTChannelSourceSequence::Item::getContextGroupExtensionCreatorUID(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(ContextGroupExtensionCreatorUID, value, pos); } OFCondition DRTChannelSourceSequence::Item::getContextGroupExtensionFlag(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(ContextGroupExtensionFlag, value, pos); } OFCondition DRTChannelSourceSequence::Item::getContextGroupLocalVersion(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(ContextGroupLocalVersion, value, pos); } OFCondition DRTChannelSourceSequence::Item::getContextGroupVersion(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(ContextGroupVersion, value, pos); } OFCondition DRTChannelSourceSequence::Item::getContextIdentifier(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(ContextIdentifier, value, pos); } OFCondition DRTChannelSourceSequence::Item::getContextUID(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(ContextUID, value, pos); } OFCondition DRTChannelSourceSequence::Item::getLongCodeValue(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(LongCodeValue, value, pos); } OFCondition DRTChannelSourceSequence::Item::getMappingResource(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(MappingResource, value, pos); } OFCondition DRTChannelSourceSequence::Item::getMappingResourceUID(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(MappingResourceUID, value, pos); } OFCondition DRTChannelSourceSequence::Item::getURNCodeValue(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(URNCodeValue, value, pos); } OFCondition DRTChannelSourceSequence::Item::setCodeMeaning(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmLongString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = CodeMeaning.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setCodeValue(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmShortString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = CodeValue.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setCodingSchemeDesignator(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmShortString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = CodingSchemeDesignator.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setCodingSchemeVersion(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmShortString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = CodingSchemeVersion.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setContextGroupExtensionCreatorUID(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmUniqueIdentifier::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = ContextGroupExtensionCreatorUID.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setContextGroupExtensionFlag(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmCodeString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = ContextGroupExtensionFlag.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setContextGroupLocalVersion(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmDateTime::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = ContextGroupLocalVersion.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setContextGroupVersion(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmDateTime::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = ContextGroupVersion.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setContextIdentifier(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmCodeString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = ContextIdentifier.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setContextUID(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmUniqueIdentifier::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = ContextUID.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setLongCodeValue(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmUnlimitedCharacters::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = LongCodeValue.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setMappingResource(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmCodeString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = MappingResource.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setMappingResourceUID(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmUniqueIdentifier::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = MappingResourceUID.putOFStringArray(value); } return result; } OFCondition DRTChannelSourceSequence::Item::setURNCodeValue(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmUniversalResourceIdentifierOrLocator::checkStringValue(value) : EC_Normal; if (result.good()) result = URNCodeValue.putOFStringArray(value); } return result; } // --- sequence class --- DRTChannelSourceSequence::DRTChannelSourceSequence(const OFBool emptyDefaultSequence) : EmptyDefaultSequence(emptyDefaultSequence), SequenceOfItems(), CurrentItem(), EmptyItem(OFTrue /*emptyDefaultItem*/) { CurrentItem = SequenceOfItems.end(); } DRTChannelSourceSequence::DRTChannelSourceSequence(const DRTChannelSourceSequence &copy) : EmptyDefaultSequence(copy.EmptyDefaultSequence), SequenceOfItems(), CurrentItem(), EmptyItem(OFTrue /*emptyDefaultItem*/) { /* create a copy of the internal sequence of items */ Item *item = NULL; OFListConstIterator(Item *) current = copy.SequenceOfItems.begin(); const OFListConstIterator(Item *) last = copy.SequenceOfItems.end(); while (current != last) { item = new Item(**current); if (item != NULL) { SequenceOfItems.push_back(item); } else { /* memory exhausted, there is nothing we can do about it */ break; } ++current; } CurrentItem = SequenceOfItems.begin(); } DRTChannelSourceSequence &DRTChannelSourceSequence::operator=(const DRTChannelSourceSequence &copy) { if (this != &copy) { clear(); EmptyDefaultSequence = copy.EmptyDefaultSequence; /* create a copy of the internal sequence of items */ Item *item = NULL; OFListConstIterator(Item *) current = copy.SequenceOfItems.begin(); const OFListConstIterator(Item *) last = copy.SequenceOfItems.end(); while (current != last) { item = new Item(**current); if (item != NULL) { SequenceOfItems.push_back(item); } else { /* memory exhausted, there is nothing we can do about it */ break; } ++current; } CurrentItem = SequenceOfItems.begin(); } return *this; } DRTChannelSourceSequence::~DRTChannelSourceSequence() { clear(); } void DRTChannelSourceSequence::clear() { if (!EmptyDefaultSequence) { CurrentItem = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); /* delete all items and free memory */ while (CurrentItem != last) { delete (*CurrentItem); CurrentItem = SequenceOfItems.erase(CurrentItem); } /* make sure that the list is empty */ SequenceOfItems.clear(); CurrentItem = SequenceOfItems.end(); } } OFBool DRTChannelSourceSequence::isEmpty() { return SequenceOfItems.empty(); } OFBool DRTChannelSourceSequence::isValid() const { return !EmptyDefaultSequence; } unsigned long DRTChannelSourceSequence::getNumberOfItems() const { return SequenceOfItems.size(); } OFCondition DRTChannelSourceSequence::gotoFirstItem() { OFCondition result = EC_IllegalCall; if (!SequenceOfItems.empty()) { CurrentItem = SequenceOfItems.begin(); result = EC_Normal; } return result; } OFCondition DRTChannelSourceSequence::gotoNextItem() { OFCondition result = EC_IllegalCall; if (CurrentItem != SequenceOfItems.end()) { ++CurrentItem; result = EC_Normal; } return result; } OFCondition DRTChannelSourceSequence::gotoItem(const unsigned long num, OFListIterator(Item *) &iterator) { OFCondition result = EC_IllegalCall; if (!SequenceOfItems.empty()) { unsigned long idx = num + 1; iterator = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); while ((--idx > 0) && (iterator != last)) ++iterator; /* specified list item found? */ if ((idx == 0) && (iterator != last)) result = EC_Normal; else result = EC_IllegalParameter; } return result; } OFCondition DRTChannelSourceSequence::gotoItem(const unsigned long num, OFListConstIterator(Item *) &iterator) const { OFCondition result = EC_IllegalCall; if (!SequenceOfItems.empty()) { unsigned long idx = num + 1; iterator = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); while ((--idx > 0) && (iterator != last)) ++iterator; /* specified list item found? */ if ((idx == 0) && (iterator != last)) result = EC_Normal; else result = EC_IllegalParameter; } return result; } OFCondition DRTChannelSourceSequence::gotoItem(const unsigned long num) { return gotoItem(num, CurrentItem); } OFCondition DRTChannelSourceSequence::getCurrentItem(Item *&item) const { OFCondition result = EC_IllegalCall; if (CurrentItem != SequenceOfItems.end()) { item = *CurrentItem; result = EC_Normal; } return result; } DRTChannelSourceSequence::Item &DRTChannelSourceSequence::getCurrentItem() { if (CurrentItem != SequenceOfItems.end()) return **CurrentItem; else return EmptyItem; } const DRTChannelSourceSequence::Item &DRTChannelSourceSequence::getCurrentItem() const { if (CurrentItem != SequenceOfItems.end()) return **CurrentItem; else return EmptyItem; } OFCondition DRTChannelSourceSequence::getItem(const unsigned long num, Item *&item) { OFListIterator(Item *) iterator; OFCondition result = gotoItem(num, iterator); if (result.good()) item = *iterator; return result; } DRTChannelSourceSequence::Item &DRTChannelSourceSequence::getItem(const unsigned long num) { OFListIterator(Item *) iterator; if (gotoItem(num, iterator).good()) return **iterator; else return EmptyItem; } const DRTChannelSourceSequence::Item &DRTChannelSourceSequence::getItem(const unsigned long num) const { OFListConstIterator(Item *) iterator; if (gotoItem(num, iterator).good()) return **iterator; else return EmptyItem; } DRTChannelSourceSequence::Item &DRTChannelSourceSequence::operator[](const unsigned long num) { return getItem(num); } const DRTChannelSourceSequence::Item &DRTChannelSourceSequence::operator[](const unsigned long num) const { return getItem(num); } OFCondition DRTChannelSourceSequence::addItem(Item *&item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { item = new Item(); if (item != NULL) { SequenceOfItems.push_back(item); result = EC_Normal; } else result = EC_MemoryExhausted; } return result; } OFCondition DRTChannelSourceSequence::insertItem(const unsigned long pos, Item *&item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { OFListIterator(Item *) iterator; result = gotoItem(pos, iterator); if (result.good()) { item = new Item(); if (item != NULL) { SequenceOfItems.insert(iterator, 1, item); result = EC_Normal; } else result = EC_MemoryExhausted; } else result = addItem(item); } return result; } OFCondition DRTChannelSourceSequence::removeItem(const unsigned long pos) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { OFListIterator(Item *) iterator; if (gotoItem(pos, iterator).good()) { delete *iterator; iterator = SequenceOfItems.erase(iterator); result = EC_Normal; } else result = EC_IllegalParameter; } return result; } OFCondition DRTChannelSourceSequence::read(DcmItem &dataset, const OFString &card, const OFString &type, const char *moduleName) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { /* re-initialize object */ clear(); /* retrieve sequence element from dataset */ DcmSequenceOfItems *sequence; result = dataset.findAndGetSequence(DCM_ChannelSourceSequence, sequence); if (sequence != NULL) { if (checkElementValue(*sequence, card, type, result, moduleName)) { DcmStack stack; OFBool first = OFTrue; /* iterate over all sequence items */ while (result.good() && sequence->nextObject(stack, first /*intoSub*/).good()) { DcmItem *ditem = OFstatic_cast(DcmItem *, stack.top()); if (ditem != NULL) { Item *item = new Item(); if (item != NULL) { result = item->read(*ditem); if (result.good()) { /* append new item to the end of the list */ SequenceOfItems.push_back(item); first = OFFalse; } } else result = EC_MemoryExhausted; } else result = EC_CorruptedData; } } } else { DcmSequenceOfItems element(DCM_ChannelSourceSequence); checkElementValue(element, card, type, result, moduleName); } } return result; } OFCondition DRTChannelSourceSequence::write(DcmItem &dataset, const OFString &card, const OFString &type, const char *moduleName) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { result = EC_MemoryExhausted; DcmSequenceOfItems *sequence = new DcmSequenceOfItems(DCM_ChannelSourceSequence); if (sequence != NULL) { result = EC_Normal; /* an empty optional sequence is not written */ if ((type == "2") || !SequenceOfItems.empty()) { OFListIterator(Item *) iterator = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); /* iterate over all sequence items */ while (result.good() && (iterator != last)) { DcmItem *item = new DcmItem(); if (item != NULL) { /* append new item to the end of the sequence */ result = sequence->append(item); if (result.good()) { result = (*iterator)->write(*item); ++iterator; } else delete item; } else result = EC_MemoryExhausted; } if (result.good()) { /* insert sequence element into the dataset */ result = dataset.insert(sequence, OFTrue /*replaceOld*/); } if (DCM_dcmrtLogger.isEnabledFor(OFLogger::WARN_LOG_LEVEL)) checkElementValue(*sequence, card, type, result, moduleName); if (result.good()) { /* forget reference to sequence object (avoid deletion below) */ sequence = NULL; } } else if (type == "1") { /* empty type 1 sequence not allowed */ result = RT_EC_InvalidValue; if (DCM_dcmrtLogger.isEnabledFor(OFLogger::WARN_LOG_LEVEL)) checkElementValue(*sequence, card, type, result, moduleName); } /* delete sequence (if not inserted into the dataset) */ delete sequence; } } return result; } // end of source file
mit
rdkmaster/jigsaw
src/app/demo/pc/graph/map/demo.component.ts
12069
import {AfterViewInit, Component, ViewChild} from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {AbstractGraphData, EchartOptions, JigsawGraph} from "jigsaw/public_api"; @Component({ templateUrl: './demo.component.html' }) export class MapGraphComponent implements AfterViewInit { data: AbstractGraphData; constructor(public http: HttpClient) { } @ViewChild('gisGraph') gisGraph: JigsawGraph; ngAfterViewInit() { this.http.get('mock-data/map/china').subscribe(data => { console.log(data); this.gisGraph.registerMap('china', data); this.data = new GraphDataDemo(); }) } // ==================================================================== // ignore the following lines, they are not important to this demo // ==================================================================== summary: string = ''; description: string = ''; } export class GraphDataDemo extends AbstractGraphData { geoCoordMap = { '上海': [121.4648,31.2891], '东莞': [113.8953,22.901], '东营': [118.7073,37.5513], '中山': [113.4229,22.478], '临汾': [111.4783,36.1615], '临沂': [118.3118,35.2936], '丹东': [124.541,40.4242], '丽水': [119.5642,28.1854], '乌鲁木齐': [87.9236,43.5883], '佛山': [112.8955,23.1097], '保定': [115.0488,39.0948], '兰州': [103.5901,36.3043], '包头': [110.3467,41.4899], '北京': [116.4551,40.2539], '北海': [109.314,21.6211], '南京': [118.8062,31.9208], '南宁': [108.479,23.1152], '南昌': [116.0046,28.6633], '南通': [121.1023,32.1625], '厦门': [118.1689,24.6478], '台州': [121.1353,28.6688], '合肥': [117.29,32.0581], '呼和浩特': [111.4124,40.4901], '咸阳': [108.4131,34.8706], '哈尔滨': [127.9688,45.368], '唐山': [118.4766,39.6826], '嘉兴': [120.9155,30.6354], '大同': [113.7854,39.8035], '大连': [122.2229,39.4409], '天津': [117.4219,39.4189], '太原': [112.3352,37.9413], '威海': [121.9482,37.1393], '宁波': [121.5967,29.6466], '宝鸡': [107.1826,34.3433], '宿迁': [118.5535,33.7775], '常州': [119.4543,31.5582], '广州': [113.5107,23.2196], '廊坊': [116.521,39.0509], '延安': [109.1052,36.4252], '张家口': [115.1477,40.8527], '徐州': [117.5208,34.3268], '德州': [116.6858,37.2107], '惠州': [114.6204,23.1647], '成都': [103.9526,30.7617], '扬州': [119.4653,32.8162], '承德': [117.5757,41.4075], '拉萨': [91.1865,30.1465], '无锡': [120.3442,31.5527], '日照': [119.2786,35.5023], '昆明': [102.9199,25.4663], '杭州': [119.5313,29.8773], '枣庄': [117.323,34.8926], '柳州': [109.3799,24.9774], '株洲': [113.5327,27.0319], '武汉': [114.3896,30.6628], '汕头': [117.1692,23.3405], '江门': [112.6318,22.1484], '沈阳': [123.1238,42.1216], '沧州': [116.8286,38.2104], '河源': [114.917,23.9722], '泉州': [118.3228,25.1147], '泰安': [117.0264,36.0516], '泰州': [120.0586,32.5525], '济南': [117.1582,36.8701], '济宁': [116.8286,35.3375], '海口': [110.3893,19.8516], '淄博': [118.0371,36.6064], '淮安': [118.927,33.4039], '深圳': [114.5435,22.5439], '清远': [112.9175,24.3292], '温州': [120.498,27.8119], '渭南': [109.7864,35.0299], '湖州': [119.8608,30.7782], '湘潭': [112.5439,27.7075], '滨州': [117.8174,37.4963], '潍坊': [119.0918,36.524], '烟台': [120.7397,37.5128], '玉溪': [101.9312,23.8898], '珠海': [113.7305,22.1155], '盐城': [120.2234,33.5577], '盘锦': [121.9482,41.0449], '石家庄': [114.4995,38.1006], '福州': [119.4543,25.9222], '秦皇岛': [119.2126,40.0232], '绍兴': [120.564,29.7565], '聊城': [115.9167,36.4032], '肇庆': [112.1265,23.5822], '舟山': [122.2559,30.2234], '苏州': [120.6519,31.3989], '莱芜': [117.6526,36.2714], '菏泽': [115.6201,35.2057], '营口': [122.4316,40.4297], '葫芦岛': [120.1575,40.578], '衡水': [115.8838,37.7161], '衢州': [118.6853,28.8666], '西宁': [101.4038,36.8207], '西安': [109.1162,34.2004], '贵阳': [106.6992,26.7682], '连云港': [119.1248,34.552], '邢台': [114.8071,37.2821], '邯郸': [114.4775,36.535], '郑州': [113.4668,34.6234], '鄂尔多斯': [108.9734,39.2487], '重庆': [107.7539,30.1904], '金华': [120.0037,29.1028], '铜川': [109.0393,35.1947], '银川': [106.3586,38.1775], '镇江': [119.4763,31.9702], '长春': [125.8154,44.2584], '长沙': [113.0823,28.2568], '长治': [112.8625,36.4746], '阳泉': [113.4778,38.0951], '青岛': [120.4651,36.3373], '韶关': [113.7964,24.7028] }; BJData = [ [{name:'北京'}, {name:'上海',value:95}], [{name:'北京'}, {name:'广州',value:90}], [{name:'北京'}, {name:'大连',value:80}], [{name:'北京'}, {name:'南宁',value:70}], [{name:'北京'}, {name:'南昌',value:60}], [{name:'北京'}, {name:'拉萨',value:50}], [{name:'北京'}, {name:'长春',value:40}], [{name:'北京'}, {name:'包头',value:30}], [{name:'北京'}, {name:'重庆',value:20}], [{name:'北京'}, {name:'常州',value:10}] ]; SHData = [ [{name:'上海'},{name:'包头',value:95}], [{name:'上海'},{name:'昆明',value:90}], [{name:'上海'},{name:'广州',value:80}], [{name:'上海'},{name:'郑州',value:70}], [{name:'上海'},{name:'长春',value:60}], [{name:'上海'},{name:'重庆',value:50}], [{name:'上海'},{name:'长沙',value:40}], [{name:'上海'},{name:'北京',value:30}], [{name:'上海'},{name:'丹东',value:20}], [{name:'上海'},{name:'大连',value:10}] ]; GZData = [ [{name:'广州'},{name:'福州',value:95}], [{name:'广州'},{name:'太原',value:90}], [{name:'广州'},{name:'长春',value:80}], [{name:'广州'},{name:'重庆',value:70}], [{name:'广州'},{name:'西安',value:60}], [{name:'广州'},{name:'成都',value:50}], [{name:'广州'},{name:'常州',value:40}], [{name:'广州'},{name:'北京',value:30}], [{name:'广州'},{name:'北海',value:20}], [{name:'广州'},{name:'海口',value:10}] ]; planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'; convertData(data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = this.geoCoordMap[dataItem[0].name]; var toCoord = this.geoCoordMap[dataItem[1].name]; if (fromCoord && toCoord) { res.push({ fromName: dataItem[0].name, toName: dataItem[1].name, coords: [fromCoord, toCoord] }); } } return res; }; color = ['#a6c84c', '#ffa022', '#46bee9']; series = []; protected createChartOptions(): EchartOptions { [['北京', this.BJData], ['上海', this.SHData], ['广州', this.GZData]].forEach((item: any, i) => { this.series.push({ name: item[0] + ' Top10', type: 'lines', zlevel: 1, effect: { show: true, period: 6, trailLength: 0.7, color: '#fff', symbolSize: 3 }, lineStyle: { normal: { color: this.color[i], width: 0, curveness: 0.2 } }, data: this.convertData(item[1]) }, { name: item[0] + ' Top10', type: 'lines', zlevel: 2, symbol: ['none', 'arrow'], symbolSize: 10, effect: { show: true, period: 6, trailLength: 0, symbol: this.planePath, symbolSize: 15 }, lineStyle: { normal: { color: this.color[i], width: 1, opacity: 0.6, curveness: 0.2 } }, data: this.convertData(item[1]) }, { name: item[0] + ' Top10', type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, rippleEffect: { brushType: 'stroke' }, label: { normal: { show: true, position: 'right', formatter: '{b}' } }, symbolSize: function (val) { return val[2] / 8; }, itemStyle: { normal: { color: this.color[i] } }, data: item[1].map(dataItem => { return { name: dataItem[1].name, value: this.geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); return { backgroundColor: '#404a59', title : { text: '模拟迁徙', subtext: '数据纯属虚构', left: 'center', textStyle : { color: '#fff' } }, tooltip : { trigger: 'item' }, legend: { orient: 'vertical', top: 'bottom', left: 'right', data:['北京 Top10', '上海 Top10', '广州 Top10'], textStyle: { color: '#fff' }, selectedMode: 'single' }, geo: { map: 'china', label: { emphasis: { show: false } }, roam: true, itemStyle: { normal: { areaColor: '#323c48', borderColor: '#404a59' }, emphasis: { areaColor: '#2a333d' } } }, series: this.series }; } }
mit
ardliath/vor
Source/Liath.Vor.UI.Web.Tests/Properties/AssemblyInfo.cs
956
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Liath.Vor.UI.Web.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Liath.Vor.UI.Web.Tests")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0f86c375-1dfc-443c-9bfd-a90c2a370fdd")]
mit